lecoffre-back/src/app/api/admin/OfficesController.ts
2023-10-25 10:52:27 +02:00

86 lines
2.6 KiB
TypeScript

import { Response, Request } from "express";
import { Controller, Get } from "@ControllerPattern/index";
import ApiController from "@Common/system/controller-pattern/ApiController";
import OfficesService from "@Services/admin/OfficesService/OfficesService";
import { Service } from "typedi";
import { Offices, Prisma } from "@prisma/client";
import { Office as OfficeResource } from "le-coffre-resources/dist/Admin";
import ruleHandler from "@App/middlewares/RulesHandler";
import authHandler from "@App/middlewares/AuthHandler";
import roleHandler from "@App/middlewares/RolesHandler";
@Controller()
@Service()
export default class OfficesController extends ApiController {
constructor(private officesService: OfficesService) {
super();
}
/**
* @description Get all offices
*/
@Get("/api/v1/admin/offices", [authHandler, roleHandler, ruleHandler])
protected async get(req: Request, response: Response) {
try {
//get query
let query: Prisma.OfficesFindManyArgs = {};
if (req.query["q"]) {
query = JSON.parse(req.query["q"] as string);
if (query.where?.uid) {
this.httpBadRequest(response, "You can't filter by uid");
return;
}
}
if(query.where?.office_folders) delete query.where.office_folders;
if(query.include?.office_folders) {
this.httpForbidden(response, "You can't include office_folders");
return;
};
//call service to get prisma entity
const officesEntities: Offices[] = await this.officesService.get(query);
//Hydrate ressource with prisma entity
const offices = OfficeResource.hydrateArray<OfficeResource>(officesEntities, { strategy: "excludeAll" });
//success
this.httpSuccess(response, offices);
} catch (error) {
this.httpInternalError(response, error);
return;
}
}
/**
* @description Get a specific office by uid
*/
@Get("/api/v1/admin/offices/:uid", [authHandler, roleHandler, ruleHandler])
protected async getOneByUid(req: Request, response: Response) {
try {
const uid = req.params["uid"];
if (!uid) {
this.httpBadRequest(response, "No uid provided");
return;
}
//get query
let query;
if (req.query["q"]) {
query = JSON.parse(req.query["q"] as string);
}
const officeEntity = await this.officesService.getByUid(uid, query);
if (!officeEntity) {
this.httpNotFoundRequest(response, "office not found");
return;
}
//Hydrate ressource with prisma entity
const office = OfficeResource.hydrate<OfficeResource>(officeEntity, { strategy: "excludeAll" });
//success
this.httpSuccess(response, office);
} catch (error) {
this.httpInternalError(response, error);
return;
}
}
}