sx-cli-tool
Version:
Laravel va Vue frameworklaridagi monolith arxitektura loyihalarni boshqarish uchun mo'ljallangan CLI tool
225 lines (217 loc) • 8.86 kB
JavaScript
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.generateVueComponent = generateVueComponent;
const fs_1 = __importDefault(require("fs"));
const path_1 = __importDefault(require("path"));
const folder_1 = require("../../utils/folder");
const prettier_1 = require("../../utils/prettier");
function generateVueComponent(entityName, projectPath, groupName, apiIdSingular, apiIdPlural, fields) {
const tempFields = [...fields, { name: "actions", type: "string", width: "200px" }];
// component path
const componentFolderPath = path_1.default.join(projectPath, "resources", "vue", "modules", groupName.toLocaleLowerCase(), `${apiIdPlural}`);
// home page
const indexTemplate = `
<script setup lang="ts">
import { ref, onMounted} from "vue";
import {useRouter} from "vue-router";
import {Button} from "ant-design-vue";
import axios from "axios";
import {AxiosResponse} from "axios";
import {Table} from "ant-design-vue";
const router = useRouter();
const isLoading = ref(false);
const data = ref<any[]>([]);
const page = ref(1);
const limit = ref(50);
const columns = ref(${JSON.stringify(tempFields.map((el) => {
return {
title: el.name,
dataIndex: el.name,
key: el.name,
width: el.width
};
}), null, 2)});
// get ${apiIdPlural}
async function get${apiIdPlural.slice(0).toUpperCase()}() {
try {
isLoading.value = true;
const res:AxiosResponse = await axios.get("/api${groupName.toLocaleLowerCase()}/${apiIdPlural}?page=" +page.value + "&limit="+limit.value);
data.value = res.data.data;
isLoading.value = false;
}
catch(e) {
isLoading.value = false;
console.error(e);
}
}
// delete ${apiIdSingular}
async function delete${apiIdSingular.slice(0).toUpperCase()}(id: number) {
try {
isLoading.value = true;
const res: AxiosResponse = await axios.delete("/api${groupName.toLocaleLowerCase()}/${apiIdPlural}/" + id);
get${apiIdPlural.slice(0).toUpperCase()}();
isLoading.value = false;
} catch (e) {
isLoading.value = false;
console.error(e);
}
}
onMounted(() => {
get${apiIdPlural.slice(0).toUpperCase()}();
})
</script>
<template>
<div class="m-2">
<div class="flex justify-end">
<Button
@click="router.push('${groupName.toLocaleLowerCase()}/${apiIdPlural}/create')"
type="primary"
>Create</Button
>
</div>
<Table :loading="isLoading" :columns :dataSource="data">
<template #bodyCell="{ column, text, record }">
<div class="flex items-center gap-1" v-if="column.dataIndex === 'actions'">
<Button @click="router.push('${groupName.toLocaleLowerCase()}/${apiIdPlural}/' + record.id+'/update')" type="primary">Edit</Button>
<Button @click="delete${apiIdSingular.slice(0).toUpperCase()}(record.id)" danger>Delete</Button>
</div>
</template>
</Table>
</div>
</template>
`;
const addOrUpdateTemplate = `
<script setup lang="ts">
import {ref, reactive,onMounted} from "vue";
import type { UnwrapRef } from "vue";
import axios, {AxiosResponse} from "axios";
import { useRouter, useRoute } from "vue-router";
import {Form,FormItem, message,Input,Button} from "ant-design-vue";
import type { Rule } from 'ant-design-vue/es/form';
const router = useRouter();
const route = useRoute();
const isLoading = ref<boolean>(false);
const formRef = ref();
const formState:UnwrapRef<any> = reactive({
${fields.map((el) => {
return `${el.name} : null`;
})}
});
// create ${entityName}
async function create${entityName}() {
try {
isLoading.value = true;
const res:AxiosResponse = await axios.post("/api${groupName.toLocaleLowerCase()}/${apiIdPlural}", formState);
message.success("Успешно добавлено", 3, () => {
router.go(-1)
});
isLoading.value = false;
}
catch(e:any) {
isLoading.value = false;
if (e.status == 422) return message.error(e.response.data.message);
message.error("Произошла ошибка");
}
}
// update ${entityName}
async function update${entityName}() {
try {
isLoading.value = true;
const res:AxiosResponse = await axios.put("/api${groupName.toLocaleLowerCase()}/${apiIdPlural}/" + route.params.id, formState);
message.success("Успешно обновлено", 3, () => {
router.go(-1)
});
isLoading.value = false;
}
catch(e:any) {
isLoading.value = false;
if (e.status == 422) return message.error(e.response.data.message);
message.error("Произошла ошибка");
}
}
// get by id
async function getById() {
if(!route.params.id) return;
try {
isLoading.value = true;
const res:AxiosResponse = await axios.get("/api${groupName.toLocaleLowerCase()}/${apiIdPlural}/"+route.params.id);
for(const key in res.data) {
formState[key] = res.data[key];
}
isLoading.value = false;
}
catch(e:any) {
isLoading.value = false;
console.error(e)
}
}
onMounted(() => {
getById();
})
</script>
<template>
<div class="m-2">
<h1>${entityName}</h1>
<Form @finish="route.params.id ? update${entityName}() : create${entityName}()" ref="formRef" :model="formState" >
<div class="grid grid-cols-12 gap-4 px-5 mt-6 w-full">
${fields.map((el) => {
return `<div class="col-span-4 max-md:max-w-full">
<FormItem ref="${el.name}" name="${el.name}">
<p class="text-sm max-md:max-w-full font-regular capitalize">
${el.name}
</p>
<Input v-model:value="formState.${el.name}" class="mt-2" placeholder=""></Input>
</FormItem>
</div>`;
}).join("")}
</div>
<div class="flex items-center justify-end gap-1">
<Button>Cancel</Button>
<Button :loading="isLoading" html-type="submit" type="primary">{{route.params.id ? "Update" : "Create"}}</Button>
</div>
</Form>
</div>
</template>
`;
const indexComponentPath = path_1.default.join(componentFolderPath, 'Index.vue');
// Ensure the components directory exists
(0, folder_1.ensureDirectoryExists)(indexComponentPath);
fs_1.default.writeFileSync(indexComponentPath, indexTemplate, "utf8");
(0, prettier_1.formatVueFile)(indexComponentPath);
// log to console that component was created successfully with green color
console.log(`\x1b[32m${componentFolderPath}\Index.vue component created successfully!\x1b[0m`);
// add or update page
const addOrUpdateComponentPath = path_1.default.join(componentFolderPath, "AddOrUpdate.vue");
(0, folder_1.ensureDirectoryExists)(addOrUpdateComponentPath);
fs_1.default.writeFileSync(addOrUpdateComponentPath, addOrUpdateTemplate, "utf8");
(0, prettier_1.formatVueFile)(addOrUpdateComponentPath);
// log to console that component was created successfully with green color
console.log(`\x1b[32m${componentFolderPath}\AddOrUpdate.vue component created successfully!\x1b[0m`);
// import ${entityName}AddOrUpdate from "@/modules/${groupName}/${apiIdPlural}/AddOrUpdate.vue";
// generate pages
const pagesIndex = `
<script setup lang="ts">
import ${entityName}Index from "@/modules${groupName}/${apiIdPlural}/Index.vue";
</script>
<template>
<${entityName}Index/>
</template>
`;
(0, folder_1.ensureDirectoryExists)(projectPath + `/resources/vue/pages${groupName.toLocaleLowerCase()}/${apiIdPlural}/Index.vue`);
fs_1.default.writeFileSync(projectPath + `/resources/vue/pages${groupName.toLocaleLowerCase()}/${apiIdPlural}/Index.vue`, pagesIndex, "utf8");
(0, prettier_1.formatVueFile)(projectPath + `/resources/vue/pages${groupName.toLocaleLowerCase()}/${apiIdPlural}/Index.vue`);
const pagesAddOrUpdate = `
<script setup lang="ts">
import ${entityName}AddOrUpdate from "@/modules${groupName}/${apiIdPlural}/AddOrUpdate.vue";
</script>
<template>
<${entityName}AddOrUpdate/>
</template>
`;
(0, folder_1.ensureDirectoryExists)(projectPath + `/resources/vue/pages${groupName.toLocaleLowerCase()}/${apiIdPlural}/AddOrUpdate.vue`);
fs_1.default.writeFileSync(projectPath + `/resources/vue/pages${groupName.toLocaleLowerCase()}/${apiIdPlural}/AddOrUpdate.vue`, pagesAddOrUpdate, "utf8");
(0, prettier_1.formatVueFile)(projectPath + `/resources/vue/pages${groupName.toLocaleLowerCase()}/${apiIdPlural}/AddOrUpdate.vue`);
}