fix api service v2 to v1 & fix type & review code
This commit is contained in:
parent
6e0a61bafa
commit
4318a7b631
3 changed files with 485 additions and 431 deletions
|
|
@ -1,3 +1,4 @@
|
||||||
|
import { Position } from "./../entities/Position";
|
||||||
import { ApiKey } from "./../entities/ApiKey";
|
import { ApiKey } from "./../entities/ApiKey";
|
||||||
import { ApiAttribute } from "./../entities/ApiAttribute";
|
import { ApiAttribute } from "./../entities/ApiAttribute";
|
||||||
import { CreateApi } from "./../entities/ApiName";
|
import { CreateApi } from "./../entities/ApiName";
|
||||||
|
|
@ -49,7 +50,7 @@ import HttpError from "../interfaces/http-error";
|
||||||
import { RequestWithUser } from "../middlewares/user";
|
import { RequestWithUser } from "../middlewares/user";
|
||||||
import { ApiName } from "../entities/ApiName";
|
import { ApiName } from "../entities/ApiName";
|
||||||
import { Profile } from "../entities/Profile";
|
import { Profile } from "../entities/Profile";
|
||||||
|
import { SystemDefinition, EntityDefinition, SystemCode } from "./../interfaces/api-type";
|
||||||
@Route("api/v1/org/api-manage")
|
@Route("api/v1/org/api-manage")
|
||||||
@Tags("ApiManage")
|
@Tags("ApiManage")
|
||||||
@Security("bearerAuth")
|
@Security("bearerAuth")
|
||||||
|
|
@ -58,36 +59,37 @@ import { Profile } from "../entities/Profile";
|
||||||
"เกิดข้อผิดพลาด ไม่สามารถแสดงรายการได้ กรุณาลองใหม่ในภายหลัง",
|
"เกิดข้อผิดพลาด ไม่สามารถแสดงรายการได้ กรุณาลองใหม่ในภายหลัง",
|
||||||
)
|
)
|
||||||
export class ApiManageController extends Controller {
|
export class ApiManageController extends Controller {
|
||||||
// private apiNameRepository = AppDataSource.getRepository(ApiName);
|
private readonly profileRepository = AppDataSource.getRepository(Profile);
|
||||||
private profileRepository = AppDataSource.getRepository(Profile);
|
private readonly profileEmployeeRepository = AppDataSource.getRepository(ProfileEmployee);
|
||||||
private profileEmployeeRepository = AppDataSource.getRepository(ProfileEmployee);
|
private readonly profileGovernmentRepository = AppDataSource.getRepository(ProfileGovernment);
|
||||||
private profileGovernmentRepository = AppDataSource.getRepository(ProfileGovernment);
|
private readonly profileProfileSalaryRepository = AppDataSource.getRepository(ProfileSalary);
|
||||||
private profileProfileSalaryRepository = AppDataSource.getRepository(ProfileSalary);
|
private readonly profileAbilityRepository = AppDataSource.getRepository(ProfileAbility);
|
||||||
private profileAbilityRepository = AppDataSource.getRepository(ProfileAbility);
|
private readonly profileAssessmentRepository = AppDataSource.getRepository(ProfileAssessment);
|
||||||
private profileAssessmentRepository = AppDataSource.getRepository(ProfileAssessment);
|
private readonly profileCertificateRepository = AppDataSource.getRepository(ProfileCertificate);
|
||||||
private profileCertificateRepository = AppDataSource.getRepository(ProfileCertificate);
|
private readonly profileHonorRepository = AppDataSource.getRepository(ProfileHonor);
|
||||||
private profileHonorRepository = AppDataSource.getRepository(ProfileHonor);
|
private readonly profileInsigniaRepository = AppDataSource.getRepository(ProfileInsignia);
|
||||||
private profileInsigniaRepository = AppDataSource.getRepository(ProfileInsignia);
|
private readonly profileLeaveRepository = AppDataSource.getRepository(ProfileLeave);
|
||||||
private profileLeaveRepository = AppDataSource.getRepository(ProfileLeave);
|
private readonly profileChangeNameRepository = AppDataSource.getRepository(ProfileChangeName);
|
||||||
private profileChangeNameRepository = AppDataSource.getRepository(ProfileChangeName);
|
private readonly profileDevelopmentRepository = AppDataSource.getRepository(ProfileDevelopment);
|
||||||
private profileDevelopmentRepository = AppDataSource.getRepository(ProfileDevelopment);
|
private readonly profileDisciplineRepository = AppDataSource.getRepository(ProfileDiscipline);
|
||||||
private profileDisciplineRepository = AppDataSource.getRepository(ProfileDiscipline);
|
private readonly profileDutyRepository = AppDataSource.getRepository(ProfileDuty);
|
||||||
private profileDutyRepository = AppDataSource.getRepository(ProfileDuty);
|
private readonly profileEducationRepository = AppDataSource.getRepository(ProfileEducation);
|
||||||
private profileEducationRepository = AppDataSource.getRepository(ProfileEducation);
|
private readonly profileFamilyCoupleRepository = AppDataSource.getRepository(ProfileFamilyCouple);
|
||||||
private profileFamilyCoupleRepository = AppDataSource.getRepository(ProfileFamilyCouple);
|
private readonly profileFamilyFatherRepository = AppDataSource.getRepository(ProfileFamilyFather);
|
||||||
private profileFamilyFatherRepository = AppDataSource.getRepository(ProfileFamilyFather);
|
private readonly profileFamilyMotherRepository = AppDataSource.getRepository(ProfileFamilyMother);
|
||||||
private profileFamilyMotherRepository = AppDataSource.getRepository(ProfileFamilyMother);
|
private readonly profileChildrenRepository = AppDataSource.getRepository(ProfileChildren);
|
||||||
private profileChildrenRepository = AppDataSource.getRepository(ProfileChildren);
|
private readonly profileNopaidRepository = AppDataSource.getRepository(ProfileNopaid);
|
||||||
private profileNopaidRepository = AppDataSource.getRepository(ProfileNopaid);
|
private readonly profileOtherRepository = AppDataSource.getRepository(ProfileOther);
|
||||||
private profileOtherRepository = AppDataSource.getRepository(ProfileOther);
|
private readonly orgRootRepository = AppDataSource.getRepository(OrgRoot);
|
||||||
private orgRootRepository = AppDataSource.getRepository(OrgRoot);
|
private readonly orgChild1Repository = AppDataSource.getRepository(OrgChild1);
|
||||||
private orgChild1Repository = AppDataSource.getRepository(OrgChild1);
|
private readonly orgChild2Repository = AppDataSource.getRepository(OrgChild2);
|
||||||
private orgChild2Repository = AppDataSource.getRepository(OrgChild2);
|
private readonly orgChild3Repository = AppDataSource.getRepository(OrgChild3);
|
||||||
private orgChild3Repository = AppDataSource.getRepository(OrgChild3);
|
private readonly orgChild4Repository = AppDataSource.getRepository(OrgChild4);
|
||||||
private orgChild4Repository = AppDataSource.getRepository(OrgChild4);
|
private readonly posMasterRepository = AppDataSource.getRepository(PosMaster);
|
||||||
private posMasterRepository = AppDataSource.getRepository(PosMaster);
|
private readonly positionRepository = AppDataSource.getRepository(Position);
|
||||||
|
|
||||||
private systems = [
|
// รายการระบบ
|
||||||
|
private readonly systems: SystemDefinition[] = [
|
||||||
{
|
{
|
||||||
code: "registry",
|
code: "registry",
|
||||||
name: "ข้อมูลทะเบียนประวัติข้าราชการ",
|
name: "ข้อมูลทะเบียนประวัติข้าราชการ",
|
||||||
|
|
@ -105,29 +107,9 @@ export class ApiManageController extends Controller {
|
||||||
name: "ข้อมูลโครงสร้างและอัตรากำลัง",
|
name: "ข้อมูลโครงสร้างและอัตรากำลัง",
|
||||||
},
|
},
|
||||||
];
|
];
|
||||||
/**
|
|
||||||
* list systems
|
|
||||||
* @summary รายการ systems
|
|
||||||
*/
|
|
||||||
@Get("/systems")
|
|
||||||
async listSystems() {
|
|
||||||
return new HttpSuccess(this.systems);
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
// รายการเอนทิตีทั้งหมด
|
||||||
* list fields by systems
|
private readonly entities: EntityDefinition[] = [
|
||||||
* @summary รายการ fields ตาม systems
|
|
||||||
*/
|
|
||||||
@Get("/:system/fields")
|
|
||||||
async listAttribute(
|
|
||||||
@Request() req: RequestWithUser,
|
|
||||||
@Path("system") system: "registry" | "registry_emp" | "registry_temp" | "organization",
|
|
||||||
): Promise<HttpSuccess | HttpError> {
|
|
||||||
try {
|
|
||||||
if (!req.user.role.includes("SUPER_ADMIN")) {
|
|
||||||
throw new HttpError(HttpStatusCode.FORBIDDEN, "คุณไม่มีสิทธิ์ในการเข้าถึงข้อมูลนี้");
|
|
||||||
}
|
|
||||||
const entities = [
|
|
||||||
{
|
{
|
||||||
name: "Profile",
|
name: "Profile",
|
||||||
repository: this.profileRepository,
|
repository: this.profileRepository,
|
||||||
|
|
@ -290,25 +272,98 @@ export class ApiManageController extends Controller {
|
||||||
{
|
{
|
||||||
name: "PosMaster",
|
name: "PosMaster",
|
||||||
repository: this.posMasterRepository,
|
repository: this.posMasterRepository,
|
||||||
|
description: "ข้อมูลอัตรากำลัง",
|
||||||
|
isMain: true,
|
||||||
|
system: ["position"],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "position",
|
||||||
|
repository: this.positionRepository,
|
||||||
description: "ข้อมูลตำแหน่ง",
|
description: "ข้อมูลตำแหน่ง",
|
||||||
system: ["organization"],
|
system: ["position"],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "OrgRoot",
|
||||||
|
repository: this.orgRootRepository,
|
||||||
|
description: "ข้อมูลหน่วยงาน",
|
||||||
|
system: ["position"],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "OrgChild1",
|
||||||
|
repository: this.orgChild1Repository,
|
||||||
|
description: "ข้อมูลส่วนราชการ ระดับที่ 1",
|
||||||
|
system: ["position"],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "OrgChild2",
|
||||||
|
repository: this.orgChild2Repository,
|
||||||
|
description: "ข้อมูลส่วนราชการ ระดับที่ 2",
|
||||||
|
system: ["position"],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "OrgChild3",
|
||||||
|
repository: this.orgChild3Repository,
|
||||||
|
description: "ข้อมูลส่วนราชการ ระดับที่ 3",
|
||||||
|
system: ["position"],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "OrgChild4",
|
||||||
|
repository: this.orgChild4Repository,
|
||||||
|
description: "ข้อมูลส่วนราชการ ระดับที่ 4",
|
||||||
|
system: ["position"],
|
||||||
},
|
},
|
||||||
];
|
];
|
||||||
|
|
||||||
const result = entities
|
private readonly DEFAULT_PAGE_SIZE = 10; // ขนาดหน้าเริ่มต้น
|
||||||
.filter((s) => s.system.includes(system))
|
private readonly EXCLUDED_COLUMNS = ["createdUserId", "lastUpdateUserId"]; // ฟิลด์ที่ไม่ต้องการแสดงในผลลัพธ์
|
||||||
|
|
||||||
|
private validateSuperAdminRole(user: any): void {
|
||||||
|
if (!user.role.includes("SUPER_ADMIN")) {
|
||||||
|
throw new HttpError(HttpStatusCode.FORBIDDEN, "คุณไม่มีสิทธิ์ในการเข้าถึงข้อมูลนี้");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private generateApiCode(): string {
|
||||||
|
return Math.random().toString(36).substring(2, 10).toUpperCase();
|
||||||
|
}
|
||||||
|
|
||||||
|
private createApiPath(system: SystemCode = "registry", code: string): string {
|
||||||
|
return `/api/v1/org/api-service/${system}/${code}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* list systems
|
||||||
|
* @summary รายการ systems
|
||||||
|
*/
|
||||||
|
@Get("/systems")
|
||||||
|
async listSystems(): Promise<HttpSuccess> {
|
||||||
|
return new HttpSuccess(this.systems);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* list fields by systems
|
||||||
|
* @summary รายการ fields ตาม systems
|
||||||
|
*/
|
||||||
|
@Get("/:system/fields")
|
||||||
|
async listAttribute(
|
||||||
|
@Request() req: RequestWithUser,
|
||||||
|
@Path("system") system: SystemCode,
|
||||||
|
): Promise<HttpSuccess | HttpError> {
|
||||||
|
try {
|
||||||
|
this.validateSuperAdminRole(req.user);
|
||||||
|
|
||||||
|
const result = this.entities
|
||||||
|
.filter((entity) => entity.system.includes(system))
|
||||||
.map(({ name, repository, description, isMain }) => ({
|
.map(({ name, repository, description, isMain }) => ({
|
||||||
tb: name,
|
tb: name,
|
||||||
description,
|
description,
|
||||||
isMain: isMain || false,
|
isMain: isMain || false,
|
||||||
propertys: repository.metadata.columns
|
propertys: repository.metadata.columns
|
||||||
.filter(
|
.filter(
|
||||||
(column) =>
|
(column: any) =>
|
||||||
!column.isPrimary &&
|
!column.isPrimary && !this.EXCLUDED_COLUMNS.includes(column.propertyName),
|
||||||
column.propertyName !== "createdUserId" &&
|
|
||||||
column.propertyName !== "lastUpdateUserId",
|
|
||||||
)
|
)
|
||||||
.map((column) => ({
|
.map((column: any) => ({
|
||||||
propertyName: column.propertyName,
|
propertyName: column.propertyName,
|
||||||
type: typeof column.type === "string" ? column.type : "string",
|
type: typeof column.type === "string" ? column.type : "string",
|
||||||
comment: column.comment,
|
comment: column.comment,
|
||||||
|
|
@ -334,20 +389,18 @@ export class ApiManageController extends Controller {
|
||||||
async listApi(
|
async listApi(
|
||||||
@Request() req: RequestWithUser,
|
@Request() req: RequestWithUser,
|
||||||
@Query("page") page: number = 1,
|
@Query("page") page: number = 1,
|
||||||
@Query("pageSize") pageSize: number = 10,
|
@Query("pageSize") pageSize: number = this.DEFAULT_PAGE_SIZE,
|
||||||
@Query() keyword: string = "",
|
@Query("keyword") keyword: string = "",
|
||||||
@Query() system: "registry" | "registry_emp" | "registry_temp" | "organization" | "" = "",
|
@Query("system") system: SystemCode | undefined = undefined,
|
||||||
@Query() isActive: boolean = true,
|
@Query("isActive") isActive: boolean = true,
|
||||||
): Promise<HttpSuccess | HttpError> {
|
): Promise<HttpSuccess | HttpError> {
|
||||||
try {
|
try {
|
||||||
if (!req.user.role.includes("SUPER_ADMIN")) {
|
this.validateSuperAdminRole(req.user);
|
||||||
throw new HttpError(HttpStatusCode.FORBIDDEN, "คุณไม่มีสิทธิ์ในการเข้าถึงข้อมูลนี้");
|
|
||||||
}
|
|
||||||
const offset = (page - 1) * pageSize;
|
|
||||||
|
|
||||||
|
const offset = (page - 1) * pageSize;
|
||||||
const queryBuilder = AppDataSource.getRepository(ApiName)
|
const queryBuilder = AppDataSource.getRepository(ApiName)
|
||||||
.createQueryBuilder("apiName")
|
.createQueryBuilder("apiName")
|
||||||
.where("apiName.isActive = :isActive", { isActive: isActive ?? true })
|
.where("apiName.isActive = :isActive", { isActive })
|
||||||
.select([
|
.select([
|
||||||
"apiName.id",
|
"apiName.id",
|
||||||
"apiName.name",
|
"apiName.name",
|
||||||
|
|
@ -370,7 +423,6 @@ export class ApiManageController extends Controller {
|
||||||
if (system) {
|
if (system) {
|
||||||
queryBuilder.andWhere("apiName.system = :system", { system });
|
queryBuilder.andWhere("apiName.system = :system", { system });
|
||||||
}
|
}
|
||||||
// console.log("query ===> ", queryBuilder.getQuery());
|
|
||||||
|
|
||||||
const [apiNames, total] = await queryBuilder
|
const [apiNames, total] = await queryBuilder
|
||||||
.skip(offset)
|
.skip(offset)
|
||||||
|
|
@ -404,27 +456,25 @@ export class ApiManageController extends Controller {
|
||||||
@Request() req: RequestWithUser,
|
@Request() req: RequestWithUser,
|
||||||
@Body() apiData: CreateApi,
|
@Body() apiData: CreateApi,
|
||||||
): Promise<HttpSuccess | HttpError> {
|
): Promise<HttpSuccess | HttpError> {
|
||||||
try {
|
|
||||||
const queryRunner = AppDataSource.createQueryRunner();
|
const queryRunner = AppDataSource.createQueryRunner();
|
||||||
await queryRunner.connect();
|
await queryRunner.connect();
|
||||||
await queryRunner.startTransaction();
|
await queryRunner.startTransaction();
|
||||||
|
|
||||||
try {
|
try {
|
||||||
if (!req.user.role.includes("SUPER_ADMIN")) {
|
this.validateSuperAdminRole(req.user);
|
||||||
throw new HttpError(HttpStatusCode.FORBIDDEN, "คุณไม่มีสิทธิ์ในการเข้าถึงข้อมูลนี้");
|
|
||||||
}
|
|
||||||
|
|
||||||
const code = Math.random().toString(36).substring(2, 10).toUpperCase();
|
const code = this.generateApiCode();
|
||||||
const postData = {
|
const postData = {
|
||||||
name: apiData.name,
|
name: apiData.name,
|
||||||
code,
|
code,
|
||||||
pathApi: `/api/v2/org/api-service/${apiData.system}/${code}`,
|
pathApi: this.createApiPath(apiData.system as SystemCode, code),
|
||||||
methodApi: apiData.methodApi || "GET",
|
methodApi: apiData.methodApi || "GET",
|
||||||
system: apiData.system || "registry",
|
system: apiData.system || "registry",
|
||||||
isActive: apiData.isActive || false,
|
isActive: apiData.isActive || false,
|
||||||
createdUserId: req.user?.sub || undefined,
|
createdUserId: req.user?.sub,
|
||||||
createdFullName: req.user?.name || "",
|
createdFullName: req.user?.name || "",
|
||||||
};
|
};
|
||||||
|
|
||||||
const apiName = await queryRunner.manager.getRepository(ApiName).save(postData);
|
const apiName = await queryRunner.manager.getRepository(ApiName).save(postData);
|
||||||
|
|
||||||
if (apiData.apiAttributes?.length) {
|
if (apiData.apiAttributes?.length) {
|
||||||
|
|
@ -435,7 +485,7 @@ export class ApiManageController extends Controller {
|
||||||
tbName: attr.tbName,
|
tbName: attr.tbName,
|
||||||
propertyKey,
|
propertyKey,
|
||||||
ordering: orderingCounter++,
|
ordering: orderingCounter++,
|
||||||
createdUserId: req.user?.sub || undefined,
|
createdUserId: req.user?.sub,
|
||||||
createdFullName: req.user?.name || "",
|
createdFullName: req.user?.name || "",
|
||||||
})),
|
})),
|
||||||
);
|
);
|
||||||
|
|
@ -445,18 +495,15 @@ export class ApiManageController extends Controller {
|
||||||
|
|
||||||
await queryRunner.commitTransaction();
|
await queryRunner.commitTransaction();
|
||||||
return new HttpSuccess(apiName.id);
|
return new HttpSuccess(apiName.id);
|
||||||
} catch (transactionError) {
|
|
||||||
await queryRunner.rollbackTransaction();
|
|
||||||
throw transactionError;
|
|
||||||
} finally {
|
|
||||||
await queryRunner.release();
|
|
||||||
}
|
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
|
await queryRunner.rollbackTransaction();
|
||||||
throw new HttpError(
|
throw new HttpError(
|
||||||
HttpStatusCode.INTERNAL_SERVER_ERROR,
|
HttpStatusCode.INTERNAL_SERVER_ERROR,
|
||||||
(error instanceof Error ? error.message : String(error)) ||
|
(error instanceof Error ? error.message : String(error)) ||
|
||||||
"เกิดข้อผิดพลาด ไม่สามารถบันทึกข้อมูลได้ กรุณาลองใหม่ในภายหลัง",
|
"เกิดข้อผิดพลาด ไม่สามารถบันทึกข้อมูลได้ กรุณาลองใหม่ในภายหลัง",
|
||||||
);
|
);
|
||||||
|
} finally {
|
||||||
|
await queryRunner.release();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -470,9 +517,7 @@ export class ApiManageController extends Controller {
|
||||||
@Path("id") id: string,
|
@Path("id") id: string,
|
||||||
): Promise<HttpSuccess | HttpError> {
|
): Promise<HttpSuccess | HttpError> {
|
||||||
try {
|
try {
|
||||||
if (!req.user.role.includes("SUPER_ADMIN")) {
|
this.validateSuperAdminRole(req.user);
|
||||||
throw new HttpError(HttpStatusCode.FORBIDDEN, "คุณไม่มีสิทธิ์ในการเข้าถึงข้อมูลนี้");
|
|
||||||
}
|
|
||||||
|
|
||||||
const apiName = await AppDataSource.getRepository(ApiName).findOne({
|
const apiName = await AppDataSource.getRepository(ApiName).findOne({
|
||||||
select: {
|
select: {
|
||||||
|
|
@ -493,6 +538,7 @@ export class ApiManageController extends Controller {
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
if (!apiName) {
|
if (!apiName) {
|
||||||
throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบ API ที่ต้องการแก้ไข");
|
throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบ API ที่ต้องการแก้ไข");
|
||||||
}
|
}
|
||||||
|
|
@ -504,6 +550,7 @@ export class ApiManageController extends Controller {
|
||||||
propertyKey: attr.propertyKey,
|
propertyKey: attr.propertyKey,
|
||||||
})),
|
})),
|
||||||
};
|
};
|
||||||
|
|
||||||
return new HttpSuccess(items);
|
return new HttpSuccess(items);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
throw new HttpError(
|
throw new HttpError(
|
||||||
|
|
@ -524,15 +571,12 @@ export class ApiManageController extends Controller {
|
||||||
@Path("id") id: string,
|
@Path("id") id: string,
|
||||||
@Body() apiData: CreateApi,
|
@Body() apiData: CreateApi,
|
||||||
): Promise<HttpSuccess | HttpError> {
|
): Promise<HttpSuccess | HttpError> {
|
||||||
try {
|
|
||||||
const queryRunner = AppDataSource.createQueryRunner();
|
const queryRunner = AppDataSource.createQueryRunner();
|
||||||
await queryRunner.connect();
|
await queryRunner.connect();
|
||||||
await queryRunner.startTransaction();
|
await queryRunner.startTransaction();
|
||||||
|
|
||||||
try {
|
try {
|
||||||
if (!req.user.role.includes("SUPER_ADMIN")) {
|
this.validateSuperAdminRole(req.user);
|
||||||
throw new HttpError(HttpStatusCode.FORBIDDEN, "คุณไม่มีสิทธิ์ในการเข้าถึงข้อมูลนี้");
|
|
||||||
}
|
|
||||||
|
|
||||||
const apiName = await queryRunner.manager.getRepository(ApiName).findOneBy({ id });
|
const apiName = await queryRunner.manager.getRepository(ApiName).findOneBy({ id });
|
||||||
if (!apiName) {
|
if (!apiName) {
|
||||||
|
|
@ -541,16 +585,17 @@ export class ApiManageController extends Controller {
|
||||||
|
|
||||||
const updateData = {
|
const updateData = {
|
||||||
name: apiData.name,
|
name: apiData.name,
|
||||||
pathApi: `/api/v2/org/api-service/${apiData.system}/${apiName.code}`,
|
pathApi: this.createApiPath(apiData.system as SystemCode, apiName.code),
|
||||||
methodApi: apiData.methodApi || "GET",
|
methodApi: apiData.methodApi || "GET",
|
||||||
system: apiData.system || "registry",
|
system: apiData.system || "registry",
|
||||||
isActive: apiData.isActive || false,
|
isActive: apiData.isActive || false,
|
||||||
lastUpdateUserId: req.user?.sub || undefined,
|
lastUpdateUserId: req.user?.sub,
|
||||||
lastUpdateFullName: req.user?.name || "",
|
lastUpdateFullName: req.user?.name || "",
|
||||||
};
|
};
|
||||||
await queryRunner.manager.getRepository(ApiName).update(id, updateData);
|
|
||||||
|
|
||||||
|
await queryRunner.manager.getRepository(ApiName).update(id, updateData);
|
||||||
await queryRunner.manager.getRepository(ApiAttribute).delete({ apiNameId: id });
|
await queryRunner.manager.getRepository(ApiAttribute).delete({ apiNameId: id });
|
||||||
|
|
||||||
if (apiData.apiAttributes?.length) {
|
if (apiData.apiAttributes?.length) {
|
||||||
let orderingCounter = 0;
|
let orderingCounter = 0;
|
||||||
const attributesToSave = apiData.apiAttributes.flatMap((attr) =>
|
const attributesToSave = apiData.apiAttributes.flatMap((attr) =>
|
||||||
|
|
@ -559,7 +604,7 @@ export class ApiManageController extends Controller {
|
||||||
tbName: attr.tbName,
|
tbName: attr.tbName,
|
||||||
propertyKey,
|
propertyKey,
|
||||||
ordering: orderingCounter++,
|
ordering: orderingCounter++,
|
||||||
lastUpdateUserId: req.user?.sub || undefined,
|
lastUpdateUserId: req.user?.sub,
|
||||||
lastUpdateFullName: req.user?.name || "",
|
lastUpdateFullName: req.user?.name || "",
|
||||||
})),
|
})),
|
||||||
);
|
);
|
||||||
|
|
@ -569,18 +614,15 @@ export class ApiManageController extends Controller {
|
||||||
|
|
||||||
await queryRunner.commitTransaction();
|
await queryRunner.commitTransaction();
|
||||||
return new HttpSuccess();
|
return new HttpSuccess();
|
||||||
} catch (transactionError) {
|
|
||||||
await queryRunner.rollbackTransaction();
|
|
||||||
throw transactionError;
|
|
||||||
} finally {
|
|
||||||
await queryRunner.release();
|
|
||||||
}
|
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
|
await queryRunner.rollbackTransaction();
|
||||||
throw new HttpError(
|
throw new HttpError(
|
||||||
HttpStatusCode.INTERNAL_SERVER_ERROR,
|
HttpStatusCode.INTERNAL_SERVER_ERROR,
|
||||||
(error instanceof Error ? error.message : String(error)) ||
|
(error instanceof Error ? error.message : String(error)) ||
|
||||||
"เกิดข้อผิดพลาด ไม่สามารถบันทึกข้อมูลได้ กรุณาลองใหม่ในภายหลัง",
|
"เกิดข้อผิดพลาด ไม่สามารถบันทึกข้อมูลได้ กรุณาลองใหม่ในภายหลัง",
|
||||||
);
|
);
|
||||||
|
} finally {
|
||||||
|
await queryRunner.release();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -593,15 +635,12 @@ export class ApiManageController extends Controller {
|
||||||
@Request() req: RequestWithUser,
|
@Request() req: RequestWithUser,
|
||||||
@Path("id") id: string,
|
@Path("id") id: string,
|
||||||
): Promise<HttpSuccess | HttpError> {
|
): Promise<HttpSuccess | HttpError> {
|
||||||
try {
|
|
||||||
const queryRunner = AppDataSource.createQueryRunner();
|
const queryRunner = AppDataSource.createQueryRunner();
|
||||||
await queryRunner.connect();
|
await queryRunner.connect();
|
||||||
await queryRunner.startTransaction();
|
await queryRunner.startTransaction();
|
||||||
|
|
||||||
try {
|
try {
|
||||||
if (!req.user.role.includes("SUPER_ADMIN")) {
|
this.validateSuperAdminRole(req.user);
|
||||||
throw new HttpError(HttpStatusCode.FORBIDDEN, "คุณไม่มีสิทธิ์ในการเข้าถึงข้อมูลนี้");
|
|
||||||
}
|
|
||||||
|
|
||||||
const checkUsed = await AppDataSource.getRepository(ApiKey)
|
const checkUsed = await AppDataSource.getRepository(ApiKey)
|
||||||
.createQueryBuilder("apiKey")
|
.createQueryBuilder("apiKey")
|
||||||
|
|
@ -621,18 +660,15 @@ export class ApiManageController extends Controller {
|
||||||
|
|
||||||
await queryRunner.commitTransaction();
|
await queryRunner.commitTransaction();
|
||||||
return new HttpSuccess();
|
return new HttpSuccess();
|
||||||
} catch (transactionError) {
|
|
||||||
await queryRunner.rollbackTransaction();
|
|
||||||
throw transactionError;
|
|
||||||
} finally {
|
|
||||||
await queryRunner.release();
|
|
||||||
}
|
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
|
await queryRunner.rollbackTransaction();
|
||||||
throw new HttpError(
|
throw new HttpError(
|
||||||
HttpStatusCode.INTERNAL_SERVER_ERROR,
|
HttpStatusCode.INTERNAL_SERVER_ERROR,
|
||||||
(error instanceof Error ? error.message : String(error)) ||
|
(error instanceof Error ? error.message : String(error)) ||
|
||||||
"เกิดข้อผิดพลาด ไม่สามารถบันทึกข้อมูลได้ กรุณาลองใหม่ในภายหลัง",
|
"เกิดข้อผิดพลาด ไม่สามารถบันทึกข้อมูลได้ กรุณาลองใหม่ในภายหลัง",
|
||||||
);
|
);
|
||||||
|
} finally {
|
||||||
|
await queryRunner.release();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -641,16 +677,15 @@ export class ApiManageController extends Controller {
|
||||||
* @summary รายการ systems
|
* @summary รายการ systems
|
||||||
*/
|
*/
|
||||||
@Get("/manual/swagger")
|
@Get("/manual/swagger")
|
||||||
async getManualRequestWebService() {
|
async getManualRequestWebService(): Promise<HttpSuccess> {
|
||||||
const json: any = {};
|
const json = {
|
||||||
// create swagger documentation for manual request only ApiWebServiceController
|
openapi: "3.0.0",
|
||||||
json["openapi"] = "3.0.0";
|
info: {
|
||||||
json["info"] = {
|
|
||||||
title: "Request Web Service",
|
title: "Request Web Service",
|
||||||
version: "1.0.0",
|
version: "1.0.0",
|
||||||
description: "This is a manual request web service.",
|
description: "This is a manual request web service.",
|
||||||
};
|
},
|
||||||
json["servers"] = [
|
servers: [
|
||||||
{
|
{
|
||||||
url: process.env.API_URL?.replace("/api/v1", "") || "http://localhost:13009",
|
url: process.env.API_URL?.replace("/api/v1", "") || "http://localhost:13009",
|
||||||
},
|
},
|
||||||
|
|
@ -658,9 +693,9 @@ export class ApiManageController extends Controller {
|
||||||
url: "http://localhost:13009",
|
url: "http://localhost:13009",
|
||||||
description: "Local server",
|
description: "Local server",
|
||||||
},
|
},
|
||||||
];
|
],
|
||||||
json["paths"] = {
|
paths: {
|
||||||
"/api/v2/org/api-service/{system}/{code}": {
|
"/api/v1/org/api-service/{system}/{code}": {
|
||||||
get: {
|
get: {
|
||||||
summary: "Get Registry Data",
|
summary: "Get Registry Data",
|
||||||
parameters: [
|
parameters: [
|
||||||
|
|
@ -670,7 +705,7 @@ export class ApiManageController extends Controller {
|
||||||
required: true,
|
required: true,
|
||||||
schema: {
|
schema: {
|
||||||
type: "string",
|
type: "string",
|
||||||
enum: ["registry", "registry_emp", "registry_temp", "organization"],
|
enum: ["registry", "registry_emp", "registry_temp", "organization", "position"],
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
|
|
@ -713,9 +748,8 @@ export class ApiManageController extends Controller {
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
};
|
},
|
||||||
|
components: {
|
||||||
json["components"] = {
|
|
||||||
securitySchemes: {
|
securitySchemes: {
|
||||||
ApiKeyAuth: {
|
ApiKeyAuth: {
|
||||||
type: "apiKey",
|
type: "apiKey",
|
||||||
|
|
@ -723,12 +757,14 @@ export class ApiManageController extends Controller {
|
||||||
name: "X-API-Key",
|
name: "X-API-Key",
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
};
|
},
|
||||||
json["security"] = [
|
security: [
|
||||||
{
|
{
|
||||||
ApiKeyAuth: [],
|
ApiKeyAuth: [],
|
||||||
},
|
},
|
||||||
];
|
],
|
||||||
|
};
|
||||||
|
|
||||||
return new HttpSuccess(json);
|
return new HttpSuccess(json);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -8,7 +8,8 @@ import { isPermissionRequest } from "../middlewares/authWebService";
|
||||||
import { RequestWithUserWebService } from "../middlewares/user";
|
import { RequestWithUserWebService } from "../middlewares/user";
|
||||||
import { OrgRevision } from "../entities/OrgRevision";
|
import { OrgRevision } from "../entities/OrgRevision";
|
||||||
import { ApiHistory } from "../entities/ApiHistory";
|
import { ApiHistory } from "../entities/ApiHistory";
|
||||||
@Route("api/v2/org/api-service")
|
import { SystemCode } from "./../interfaces/api-type";
|
||||||
|
@Route("api/v1/org/api-service")
|
||||||
@Tags("ApiKey")
|
@Tags("ApiKey")
|
||||||
@Security("webServiceAuth")
|
@Security("webServiceAuth")
|
||||||
@Response(
|
@Response(
|
||||||
|
|
@ -27,7 +28,8 @@ export class ApiWebServiceController extends Controller {
|
||||||
@Get("/:system/:code")
|
@Get("/:system/:code")
|
||||||
async listAttribute(
|
async listAttribute(
|
||||||
@Request() request: RequestWithUserWebService,
|
@Request() request: RequestWithUserWebService,
|
||||||
@Path("system") system: "registry" | "registry_emp" | "registry_temp" | "organization",
|
@Path("system")
|
||||||
|
system: SystemCode,
|
||||||
@Path("code") code: string,
|
@Path("code") code: string,
|
||||||
@Query("page") page: number = 1,
|
@Query("page") page: number = 1,
|
||||||
@Query("pageSize") pageSize: number = 100,
|
@Query("pageSize") pageSize: number = 100,
|
||||||
|
|
@ -50,18 +52,18 @@ export class ApiWebServiceController extends Controller {
|
||||||
const offset = (page - 1) * pageSize;
|
const offset = (page - 1) * pageSize;
|
||||||
const propertyKey = apiName.apiAttributes.map((attr) => `${attr.tbName}.${attr.propertyKey}`);
|
const propertyKey = apiName.apiAttributes.map((attr) => `${attr.tbName}.${attr.propertyKey}`);
|
||||||
|
|
||||||
let Main: string = "";
|
let tbMain: string = "";
|
||||||
let condition: string = "1=1";
|
let condition: string = "1=1";
|
||||||
if (system == "registry") {
|
if (system == "registry") {
|
||||||
Main = "Profile";
|
tbMain = "Profile";
|
||||||
} else if (system == "registry_emp") {
|
} else if (system == "registry_emp") {
|
||||||
Main = "ProfileEmployee";
|
tbMain = "ProfileEmployee";
|
||||||
condition = `ProfileEmployee.employeeClass = "PERM"`;
|
condition = `ProfileEmployee.employeeClass = "PERM"`;
|
||||||
} else if (system == "registry_temp") {
|
} else if (system == "registry_temp") {
|
||||||
Main = "ProfileEmployee";
|
tbMain = "ProfileEmployee";
|
||||||
condition = `ProfileEmployee.employeeClass = "TEMP"`;
|
condition = `ProfileEmployee.employeeClass = "TEMP"`;
|
||||||
} else {
|
} else {
|
||||||
Main = "OrgRoot";
|
tbMain = "OrgRoot";
|
||||||
const revision = await this.orgRevisionRepository.findOne({
|
const revision = await this.orgRevisionRepository.findOne({
|
||||||
select: ["id"],
|
select: ["id"],
|
||||||
where: { orgRevisionIsCurrent: true, orgRevisionIsDraft: false },
|
where: { orgRevisionIsCurrent: true, orgRevisionIsDraft: false },
|
||||||
|
|
@ -69,7 +71,7 @@ export class ApiWebServiceController extends Controller {
|
||||||
condition = `OrgRoot.orgRevisionId = "${revision?.id}"`;
|
condition = `OrgRoot.orgRevisionId = "${revision?.id}"`;
|
||||||
}
|
}
|
||||||
|
|
||||||
const repo = AppDataSource.getRepository(Main);
|
const repo = AppDataSource.getRepository(tbMain);
|
||||||
const metadata = repo.metadata;
|
const metadata = repo.metadata;
|
||||||
|
|
||||||
const relationMap: Record<string, string> = {};
|
const relationMap: Record<string, string> = {};
|
||||||
|
|
@ -80,17 +82,17 @@ export class ApiWebServiceController extends Controller {
|
||||||
// ดึงเฉพาะตารางรอง (ถ้าเลือกไว้)
|
// ดึงเฉพาะตารางรอง (ถ้าเลือกไว้)
|
||||||
let propertyOtherKey: any[] = [];
|
let propertyOtherKey: any[] = [];
|
||||||
propertyOtherKey = [
|
propertyOtherKey = [
|
||||||
...new Set(propertyKey.map((x) => x.split(".")[0]).filter((tb) => tb !== Main)),
|
...new Set(propertyKey.map((x) => x.split(".")[0]).filter((tb) => tb !== tbMain)),
|
||||||
];
|
];
|
||||||
|
|
||||||
const queryBuilder = repo.createQueryBuilder(Main);
|
const queryBuilder = repo.createQueryBuilder(tbMain);
|
||||||
|
|
||||||
// join กับตารารอง
|
// join กับตารารอง
|
||||||
if (propertyOtherKey.length > 0) {
|
if (propertyOtherKey.length > 0) {
|
||||||
propertyOtherKey.forEach((tb) => {
|
propertyOtherKey.forEach((tb) => {
|
||||||
const relationName = relationMap[tb];
|
const relationName = relationMap[tb];
|
||||||
if (relationName) {
|
if (relationName) {
|
||||||
queryBuilder.leftJoin(`${Main}.${relationName}`, tb);
|
queryBuilder.leftJoin(`${tbMain}.${relationName}`, tb);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
@ -105,8 +107,8 @@ export class ApiWebServiceController extends Controller {
|
||||||
const primaryColumns = metadata.primaryColumns;
|
const primaryColumns = metadata.primaryColumns;
|
||||||
primaryColumns.forEach((col) => {
|
primaryColumns.forEach((col) => {
|
||||||
pk = col.propertyName;
|
pk = col.propertyName;
|
||||||
if (!propertyKey.includes(`${Main}.${pk}`)) {
|
if (!propertyKey.includes(`${tbMain}.${pk}`)) {
|
||||||
propertyKey.push(`${Main}.${pk}`);
|
propertyKey.push(`${tbMain}.${pk}`);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|
@ -133,7 +135,7 @@ export class ApiWebServiceController extends Controller {
|
||||||
return x;
|
return x;
|
||||||
});
|
});
|
||||||
|
|
||||||
// console.log("queryBuilder ===> ", queryBuilder.getQuery());
|
console.log("queryBuilder ===> ", queryBuilder.getQuery());
|
||||||
|
|
||||||
// save api history after query success
|
// save api history after query success
|
||||||
const history = {
|
const history = {
|
||||||
|
|
|
||||||
16
src/interfaces/api-type.ts
Normal file
16
src/interfaces/api-type.ts
Normal file
|
|
@ -0,0 +1,16 @@
|
||||||
|
type SystemCode = "registry" | "registry_emp" | "registry_temp" | "organization" | "position";
|
||||||
|
|
||||||
|
interface SystemDefinition {
|
||||||
|
code: SystemCode;
|
||||||
|
name: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface EntityDefinition {
|
||||||
|
name: string;
|
||||||
|
repository: any;
|
||||||
|
description: string;
|
||||||
|
isMain?: boolean;
|
||||||
|
system: SystemCode[];
|
||||||
|
}
|
||||||
|
|
||||||
|
export { SystemCode, SystemDefinition, EntityDefinition };
|
||||||
Loading…
Add table
Add a link
Reference in a new issue