จักการ API

This commit is contained in:
DESKTOP-1R2VSQH\Lenovo ThinkPad E490 2025-08-07 18:09:18 +07:00
parent 45945de06f
commit 07dceb0f45
5 changed files with 649 additions and 150 deletions

View file

@ -1,7 +1,9 @@
import env from "../index";
const apiKey = `${env.API_URI}/org/apiKey`;
const apiManage = `${env.API_URI}/org/api-manage/`;
export default {
apiKeyMain: apiKey,
apiManage: apiManage,
};

View file

@ -0,0 +1,420 @@
<script setup lang="ts">
import { computed, reactive, ref, toRefs, watch } from "vue";
import { useQuasar } from "quasar";
import { useCounterMixin } from "@/stores/mixin";
import { useDataStoreManage } from "@/modules/06_webservices/stores/manage";
import type { DataOption } from "@/modules/06_webservices/interface/index/Main";
/** importComponents*/
import DialogHeader from "@/components/DialogHeader.vue";
import http from "@/plugins/http";
import config from "@/app.config";
const $q = useQuasar();
const { systemList, methodOptions } = toRefs(useDataStoreManage());
const {
showLoader,
hideLoader,
dialogConfirm,
success,
dialogMessageNotify,
messageError,
} = useCounterMixin();
const modal = defineModel<boolean>("modal", { required: true });
const isEdit = defineModel<boolean>("isEdit", { default: false });
const apiId = defineModel<string>("apiId", { default: "" });
const props = defineProps({
fetchData: {
type: Function,
required: true,
},
});
const titleName = computed(() => {
return isEdit.value ? "แก้ไข API" : "เพิ่ม API";
});
const options = computed<DataOption[]>(() => {
return systemList.value.filter((e) => e.id !== "all") ?? [];
});
const mainFields = computed(() => {
return availableFields.value.filter((field) => field.isMain === true);
});
const systemOptions = ref<DataOption[]>(options.value); // Default to first option
const apiPath = ref<string>("");
// Form data
const formData = reactive({
name: "",
methodApi: "GET",
system: "",
isActive: true,
});
// state fields attributes
const availableFields = ref<any[]>([]);
const selectedAttributes = ref<Record<string, Record<string, boolean>>>({});
const loading = ref(false);
const validationErrors = ref<string[]>([]);
async function fetchData(system: string) {
availableFields.value = [];
loading.value = true;
try {
const res = await http.get(`${config.API.apiManage}${system}/fields`);
availableFields.value = res.data.result || [];
// Reset selected attributes system
selectedAttributes.value = {};
// properties
availableFields.value.forEach((field) => {
// group field ()
selectedAttributes.value[field.tb] = {};
if (field.propertys && field.propertys.length > 0) {
field.propertys.forEach((prop: any) => {
// properties group
selectedAttributes.value[field.tb][prop.propertyName] = false;
});
}
});
} catch (error) {
console.error("Error fetching fields:", error);
availableFields.value = [];
} finally {
loading.value = false;
}
}
async function fetchDataId(id: string) {
try {
const res = await http.get(`${config.API.apiManage}${id}`);
const data = res.data.result;
formData.name = data.name;
formData.methodApi = data.methodApi;
formData.system = data.system;
formData.isActive = data.isActive;
apiPath.value = data.pathApi;
// fields attributes
await fetchData(data.system);
console.log(data.apiAttributes);
// selectedAttributes
if (data.apiAttributes?.length > 0) {
data.apiAttributes.forEach(
({ tbName, propertyKey }: { tbName: string; propertyKey: string }) => {
if (selectedAttributes.value[tbName]?.[propertyKey] !== undefined) {
selectedAttributes.value[tbName][propertyKey] = true;
}
}
);
}
} catch (error) {
console.error("Error fetching API by ID:", error);
}
}
async function onSelectSystem(value: string) {
await fetchData(value);
console.log("value", value);
}
// validation
function validateSelection(): boolean {
validationErrors.value = [];
// isMain: true
mainFields.value.forEach((field) => {
const selectedPropsCount = Object.keys(
selectedAttributes.value[field.tb] || {}
).filter(
(propKey) => selectedAttributes.value[field.tb][propKey] === true
).length;
if (selectedPropsCount === 0) {
validationErrors.value.push(
`จำเป็นต้องเลือกข้อมูลในหมวด "${field.description}" อย่างน้อย 1 รายการ`
);
}
});
return validationErrors.value.length === 0;
}
function onSubmit() {
if (!validateSelection()) {
validationErrors.value.forEach((error) => {
dialogMessageNotify($q, error);
});
return;
}
dialogConfirm($q, async () => {
showLoader();
// apiAttributes array
const apiAttributes: Array<{
tbName: string;
propertyKey: string[];
}> = [];
// selectedAttributes apiAttributes
Object.keys(selectedAttributes.value).forEach((fieldKey) => {
const selectedProps: string[] = [];
// property (true)
Object.keys(selectedAttributes.value[fieldKey]).forEach((propKey) => {
if (selectedAttributes.value[fieldKey][propKey]) {
selectedProps.push(propKey);
}
});
// property apiAttributes
if (selectedProps.length > 0) {
apiAttributes.push({
tbName: fieldKey,
propertyKey: selectedProps,
});
}
});
// API
const payload = {
...formData,
apiAttributes: apiAttributes,
};
const method = isEdit.value ? http.put : http.post;
const pathAPI = isEdit.value
? `${config.API.apiManage}${apiId.value}`
: config.API.apiManage;
try {
await method(pathAPI, payload);
await props.fetchData(); // fetchData parent component
success($q, "บันทึกข้อมูลสำเร็จ");
onCloseDialog();
} catch (error) {
messageError($q, error);
return;
} finally {
hideLoader();
}
});
}
/**
* function นหาคำใน select
* @param val คำคนหา
* @param update function
*/
function filterSelector(val: string, update: Function) {
update(() => {
const newVal = val.toLowerCase();
systemOptions.value = options.value.filter(
(v: DataOption) => v.name.toLowerCase().indexOf(newVal) > -1
);
});
}
function onCloseDialog() {
modal.value = false;
formData.name = "";
formData.methodApi = "GET";
formData.system = "";
formData.isActive = false;
apiPath.value = "";
availableFields.value = [];
selectedAttributes.value = {};
validationErrors.value = [];
}
watch(modal, (newVal) => {
if (newVal && isEdit.value) {
systemOptions.value = options.value; // dialog
fetchDataId(apiId.value);
}
});
</script>
<template>
<q-dialog v-model="modal" full-height>
<q-card style="min-width: 90%">
<q-form
class="column full-height"
greedy
@submit.prevent
@validation-success="onSubmit"
>
<DialogHeader :tittle="titleName" :close="onCloseDialog" />
<q-separator />
<q-card-section class="col q-pt-none scroll">
<div class="q-pa-md">
<div class="row q-col-gutter-md q-mb-lg">
<div class="col-12 col-md-4">
<q-input
v-model="formData.name"
label="API Name"
outlined
dense
hide-bottom-space
lazy-rules
:rules="[(val:string) => !!val || 'กรุณากรอก API Name']"
/>
</div>
<div class="col-12 col-md-4">
<q-select
v-model="formData.methodApi"
label="Method"
:options="methodOptions"
outlined
dense
hide-bottom-space
disable
/>
</div>
<div class="col-12 col-md-4">
<q-input
v-model="apiPath"
outlined
dense
hide-bottom-space
placeholder="Auto generate"
disable
/>
</div>
</div>
<!-- System Selection -->
<div class="row q-mb-lg">
<div class="col-12 col-md-4">
<div class="text-subtitle2 q-mb-sm">เลอกระบบขอม</div>
<q-select
dense
hide-bottom-space
outlined
option-label="name"
option-value="id"
emit-value
map-options
v-model="formData.system"
:options="systemOptions"
use-input
hide-selected
fill-input
lazy-rules
:rules="[(val:string) => !!val || 'กรุณาเลือกระบบข้อมูล']"
@update:model-value="onSelectSystem"
@filter="(inputValue: string,doneFn: Function) => filterSelector(inputValue, doneFn )"
>
<template v-slot:no-option>
<q-item>
<q-item-section class="text-grey">
ไมอม
</q-item-section>
</q-item>
</template>
</q-select>
</div>
</div>
<!-- Attributes Section -->
<div
class="q-mb-lg"
v-if="formData.system !== '' && availableFields.length > 0"
>
<div class="text-subtitle2 q-mb-md">
Attribute องการใหการเชอมโยงขอมลแบบท
</div>
<div class="row q-col-gutter-md">
<!-- Loop through available fields -->
<div
v-for="field in availableFields"
:key="field.tb"
class="col-xs-6 col-md-3"
>
<!-- วขอหมวดหม - ไมสามารถเลอกได -->
<div class="text-subtitle1 border-bottom">
{{ field.description }}
</div>
<!-- Properties สามารถเลอกได -->
<div
v-if="field.propertys && field.propertys.length > 0"
v-for="property in field.propertys"
:key="property.propertyName"
>
<q-item tag="label" v-ripple>
<q-item-section avatar>
<q-checkbox
v-model="
selectedAttributes[field.tb][property.propertyName]
"
/>
</q-item-section>
<q-item-section>
<q-item-label>{{ property.comment }}</q-item-label>
<q-item-label caption>
{{ property.propertyName }} ({{ property.type }})
</q-item-label>
</q-item-section>
</q-item>
</div>
<!-- าไม properties แสดงขอความวาง -->
<div v-else class="q-ml-md text-grey-6 text-caption q-mb-sm">
ไม attributes อยสำหรบหมวดน
</div>
</div>
</div>
</div>
<!-- Loading state -->
<div v-else-if="loading" class="text-center q-pa-md">
<q-spinner-dots size="40px" color="primary" />
<div class="q-mt-sm">กำลงโหลดขอม...</div>
</div>
<!-- Empty state -->
<div
v-else-if="
formData.system !== '' &&
availableFields.length === 0 &&
!loading
"
class="text-center q-pa-md"
>
<q-icon name="info" size="40px" color="grey" />
<div class="q-mt-sm text-grey">
ไมอม Attributes สำหรบระบบน
</div>
</div>
</div>
</q-card-section>
<q-separator />
<q-card-actions align="right">
<q-btn unelevated label="บันทึก" color="public" type="submit" />
</q-card-actions>
</q-form>
</q-card>
</q-dialog>
</template>
<style scoped>
.scroll {
overflow-y: auto;
}
</style>

View file

@ -0,0 +1,14 @@
import { defineStore } from "pinia";
import { ref } from "vue";
import type { DataOption } from "@/modules/06_webservices/interface/index/Main";
export const useDataStoreManage = defineStore("webservicesManage", () => {
const systemList = ref<DataOption[]>([{ id: "all", name: "ระบบทั้งหมด" }]);
const methodOptions = ["GET", "POST", "PUT", "DELETE"];
return {
systemList,
methodOptions,
};
});

View file

@ -36,8 +36,7 @@ const tabs = ref<string>("list");
<q-tab-panel name="list"> <ListView /> </q-tab-panel>
<q-tab-panel name="log"> <LogView /> </q-tab-panel>
<q-tab-panel name="manage">
<div style="min-height: 50em"></div>
<!-- <ManageWebServices /> -->
<ManageWebServices />
</q-tab-panel>
</q-tab-panels>
</q-card>

View file

@ -1,22 +1,24 @@
<script setup lang="ts">
import { onMounted, ref } from "vue";
import { onMounted, ref, toRefs } from "vue";
import { useQuasar } from "quasar";
import { useCounterMixin } from "@/stores/mixin";
import { useDataStoreManage } from "@/modules/06_webservices/stores/manage";
import http from "@/plugins/http";
import config from "@/app.config";
/** importType*/
import type { QTableProps } from "quasar";
import type { DataOption } from "@/modules/06_webservices/interface/index/Main";
import type { ListWebServices } from "@/modules/06_webservices/interface/index/Main";
import type { ResApiName } from "@/modules/06_webservices/interface/response/Main";
/** importComponents*/
import DialogApiKey from "@/modules/06_webservices/components/DialogApiKey.vue"; // API Key
import DialogUsability from "@/modules/06_webservices/components/DialogUsability.vue"; //
import DialogApi from "@/modules/06_webservices/components/DialogApi.vue";
/** use*/
const $q = useQuasar();
const { systemList } = toRefs(useDataStoreManage());
const {
dialogRemove,
showLoader,
@ -24,188 +26,242 @@ const {
messageError,
success,
date2Thai,
onSearchDataTable,
} = useCounterMixin();
const systemOptions = ref<DataOption[]>(systemList.value);
/** Table*/
const rows = ref<ListWebServices[]>([]); // webservices
const rowsMain = ref<ListWebServices[]>([]); // webservices
const page = ref<number>(1); //
const pageSize = ref<number>(10); //
const rows = ref<any[]>([]); // webservices
const keyword = ref<string>(""); // webservices
const systemfilter = ref<string>("all"); //
const visibleColumns = ref<string[]>([
"system",
"name",
"apiNames",
"amount",
"createdAt",
"createdFullName",
"methodApi",
"pathApi",
"lastUpdatedAt",
]);
const columns = ref<QTableProps["columns"]>([
{
name: "system",
align: "left",
label: "System",
sortable: true,
field: "system",
headerStyle: "font-size: 14px",
style: "font-size: 14px",
},
{
name: "name",
align: "left",
label: "ชื่อ-คำอธิบาย",
label: "API Name",
sortable: true,
field: "name",
headerStyle: "font-size: 14px",
style: "font-size: 14px",
},
{
name: "apiNames",
name: "methodApi",
align: "left",
label: "API ที่เข้าถึง",
label: "Method",
sortable: true,
field: "apiNames",
headerStyle: "font-size: 14px",
style: "font-size: 14px",
format(val) {
return val
.map((e: ResApiName) => `<div class='q-mt-sm'>-${e.name}</div>`)
.join("");
},
},
{
name: "amount",
align: "left",
label: "สถิติ ",
sortable: true,
field: "amount",
field: "methodApi",
headerStyle: "font-size: 14px",
style: "font-size: 14px",
},
{
name: "createdAt",
name: "pathApi",
align: "left",
label: "วันที่สร้าง",
label: "API Path",
sortable: true,
field: "createdAt",
field: "pathApi",
headerStyle: "font-size: 14px",
style: "font-size: 14px",
},
{
name: "lastUpdatedAt",
align: "left",
label: "updatedAt",
sortable: true,
field: "lastUpdatedAt",
headerStyle: "font-size: 14px",
style: "font-size: 14px",
format(val) {
return date2Thai(val, false, true);
},
headerStyle: "font-size: 14px",
style: "font-size: 14px",
},
{
name: "createdFullName",
align: "left",
label: "ผู้ดำเนินการ",
sortable: true,
field: "createdFullName",
headerStyle: "font-size: 14px",
style: "font-size: 14px",
},
]);
/** API Key*/
const modalApiKey = ref<boolean>(false); //popup API Key
const modalDialog = ref<boolean>(false); // dialog
const isEditData = ref<boolean>(false); //
const apiId = ref<string>(""); // id api
/** usability*/
const modalUsability = ref<boolean>(false); //popup
/** ฟังก์ชันเรียกข้อมูลรายการ Web services*/
async function fetchListWebServices() {
showLoader();
await http
.get(config.API.apiKeyMain + "/list")
.then(async (res) => {
const data = await res.data.result;
rows.value = data;
rowsMain.value = data;
})
.catch((err) => {
messageError($q, err);
})
.finally(() => {
hideLoader();
});
async function fetchSystemData() {
if (systemList.value.length > 1) return; //
try {
const res = await http.get(`${config.API.apiManage}systems`);
const data = res.data.result;
const systemData = data.map((item: any) => ({
id: item.code,
name: item.name,
}));
systemList.value.push(...systemData);
} catch (error) {
messageError(error);
}
}
async function fetchData() {
try {
const queryParams = {
page: page.value,
pageSize: pageSize.value,
keyword: keyword.value,
systems: systemfilter.value === "all" ? "" : systemfilter.value,
};
const res = await http.get(`${config.API.apiManage}lists`, {
params: queryParams,
});
const result = res.data.result;
rows.value = result.data;
} catch (error) {
messageError(error);
}
}
/**
* งก ลบขอมลรายการ Web services
* @param id รายการ Web services องการลบ
* เมอสำเรจจะเรยกฟงก 'fetchListWebServices' มาเรยกขอมลรายการ web servcice ใหม
*/
function onDeleteData(id: string) {
dialogRemove($q, () => {
showLoader();
http
.delete(config.API.apiKeyMain + `/${id}`)
.then(async () => {
// web servcice
await fetchListWebServices();
success($q, "ลบข้อมูลสำเร็จ");
})
.catch((err) => {
messageError($q, err);
})
.finally(() => {
hideLoader();
});
dialogRemove($q, async () => {
try {
showLoader();
await http.delete(`${config.API.apiManage}${id}`);
await fetchData();
success($q, "ลบข้อมูลสำเร็จ");
} catch (error) {
messageError($q, error);
} finally {
hideLoader();
}
});
}
function serchDataTable() {
rows.value = onSearchDataTable(
keyword.value,
rowsMain.value,
columns.value ? columns.value : []
);
function onEditData(id: string) {
isEditData.value = true;
modalDialog.value = true;
apiId.value = id; // id api
}
/** hook เมื่อเรียก Components จะเรียกฟังก์ชัน 'fetchListWebServices' เรียกข้อมูลรายการ webservices*/
onMounted(() => {
fetchListWebServices();
function onSearchDataTable() {
page.value = 1; // 1
fetchData();
}
/**
* function นหาคำใน select
* @param val คำคนหา
* @param update function
*/
function filterSelector(val: string, update: Function) {
update(() => {
const newVal = val.toLowerCase();
systemOptions.value = systemList.value.filter(
(v: DataOption) => v.name.toLowerCase().indexOf(newVal) > -1
);
});
}
onMounted(async () => {
try {
showLoader();
await fetchSystemData();
await fetchData();
} catch (error) {
messageError(error);
} finally {
hideLoader();
}
});
</script>
<template>
<div class="row items-center">
<q-space />
<q-btn
flat
color="public"
label="วิธีการใช้งาน"
@click.pervent="modalUsability = true"
/>
</div>
<div class="items-center col-12 row q-col-gutter-sm">
<q-btn
class="q-ml-sm"
flat
round
dense
color="primary"
icon="add"
@click.pervent="modalApiKey = true"
>
<q-tooltip>สราง API Key </q-tooltip>
</q-btn>
<div class="items-center row q-col-gutter-sm col-xs-12 col-sm-auto">
<div class="col-xs-12 col-sm-auto">
<q-select
dense
hide-bottom-space
outlined
option-label="name"
option-value="id"
emit-value
map-options
v-model="systemfilter"
:options="systemOptions"
label="ระบบ"
use-input
hide-selected
fill-input
:clearable="systemfilter !== 'all'"
@clear="systemfilter = 'all'"
@filter="(inputValue: string,doneFn: Function) => filterSelector(inputValue, doneFn )"
@update:model-value="onSearchDataTable"
>
<template v-slot:no-option>
<q-item>
<q-item-section class="text-grey"> ไมอม </q-item-section>
</q-item>
</template>
</q-select>
</div>
<div class="col-xs-12 col-sm-auto">
<q-btn
flat
round
dense
color="primary"
icon="add"
@click="(modalDialog = true), (isEditData = false)"
>
<q-tooltip>สราง API Key </q-tooltip>
</q-btn>
</div>
</div>
<q-space />
<q-input
borderless
dense
outlined
v-model="keyword"
placeholder="ค้นหา"
@keydown.enter.prevent="serchDataTable"
>
<template v-slot:append>
<q-icon name="search" />
</template>
</q-input>
<q-select
v-model="visibleColumns"
multiple
outlined
dense
options-dense
:display-value="$q.lang.table.columns"
emit-value
map-options
:options="columns"
option-value="name"
style="min-width: 140px"
/>
<div class="row q-col-gutter-sm col-xs-12 col-sm-auto">
<div class="col-xs-12 col-sm-auto">
<q-input
borderless
dense
outlined
v-model="keyword"
placeholder="ค้นหา"
@keydown.enter.prevent="onSearchDataTable"
>
<template v-slot:append>
<q-icon name="search" />
</template>
</q-input>
</div>
<div class="col-xs-12 col-sm-auto">
<q-select
v-model="visibleColumns"
multiple
outlined
dense
options-dense
:display-value="$q.lang.table.columns"
emit-value
map-options
:options="columns"
option-value="name"
style="min-width: 140px"
/>
</div>
</div>
</div>
<!-- Table -->
@ -233,6 +289,16 @@ onMounted(() => {
<template v-slot:body="props">
<q-tr :props="props">
<q-td auto-width>
<q-btn
dense
flat
round
color="edit"
@click="onEditData(props.row.id)"
icon="mdi-square-edit-outline"
>
<q-tooltip>แกไขขอม</q-tooltip>
</q-btn>
<q-btn
dense
flat
@ -242,8 +308,8 @@ onMounted(() => {
icon="delete"
>
<q-tooltip>ลบขอม</q-tooltip>
</q-btn></q-td
>
</q-btn>
</q-td>
<q-td v-for="col in props.cols" :key="col.name" :props="props">
<div v-html="col.value ? col.value : '-'"></div>
@ -254,14 +320,12 @@ onMounted(() => {
</d-table>
</div>
<!-- สราง API Key -->
<DialogApiKey
v-model:modal="modalApiKey"
:fetch-data="fetchListWebServices"
<DialogApi
v-model:modal="modalDialog"
:is-edit="isEditData"
:api-id="apiId"
:fetch-data="fetchData"
/>
<!-- การใชงาน -->
<DialogUsability v-model:modal="modalUsability" />
</template>
<style scoped></style>