hrms-api-org/src/controllers/AuthSysController.ts

97 lines
2.9 KiB
TypeScript
Raw Normal View History

2024-06-11 13:19:38 +07:00
import {
Body,
Controller,
Delete,
Get,
Patch,
Path,
Post,
Request,
Route,
Security,
Tags,
} from "tsoa";
import { AppDataSource } from "../database/data-source";
import { RequestWithUser } from "../middlewares/user";
import HttpError from "../interfaces/http-error";
import HttpStatus from "../interfaces/http-status";
import HttpSuccess from "../interfaces/http-success";
import { AuthSys, CreateAuthSys, UpdateAuthSys } from "../entities/AuthSys";
@Route("api/v1/org/auth/authSys")
@Tags("AuthSystem")
@Security("bearerAuth")
export class AuthSysController extends Controller {
private authSysRepo = AppDataSource.getRepository(AuthSys);
@Get("list")
public async listAuthSys(@Request() request: { user: Record<string, any> }) {
const profile = await this.authSysRepo.findOneBy({ id: request.user.sub });
if (!profile) {
throw new HttpError(HttpStatus.BAD_REQUEST, "ไม่พบ profile ดังกล่าว");
}
const getList = await this.authSysRepo.find();
if (!getList || getList.length === 0) {
throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูล");
}
return new HttpSuccess(getList);
}
@Get("{systemId}")
public async detailAuthSys(@Path() systemId: string) {
const getDetail = await this.authSysRepo.findBy({ id: systemId });
if (!getDetail) {
throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูล");
}
return new HttpSuccess(getDetail);
}
@Post()
public async newAuthSys(@Request() req: RequestWithUser, @Body() body: CreateAuthSys) {
if (!body.id) {
throw new HttpError(HttpStatus.BAD_REQUEST, "ไม่พบค่าไอดีที่ส่งมา");
}
const data = new AuthSys();
const meta = {
createdUserId: req.user.sub,
createdFullName: req.user.name,
lastUpdateUserId: req.user.sub,
lastUpdateFullName: req.user.name,
};
Object.assign(data, { ...body, ...meta });
await this.authSysRepo.save(data);
return new HttpSuccess();
}
@Patch("{systemId}")
public async editAuthSys(
@Body() requestBody: UpdateAuthSys,
@Request() req: RequestWithUser,
@Path() systemId: string,
) {
const record = await this.authSysRepo.findOneBy({ id: systemId });
if (!record) throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูล");
Object.assign(record, requestBody);
record.lastUpdateFullName = req.user.name;
await Promise.all([this.authSysRepo.save(record)]);
return new HttpSuccess();
}
@Delete("{systemId}")
public async deleteProfileAbility(@Path() systemId: string) {
const result = await this.authSysRepo.delete({ id: systemId });
if (result.affected == undefined || result.affected <= 0)
throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูล");
return new HttpSuccess();
}
}