Files
optima/api/src/api/companies/[id]/fetch.ts
T

69 lines
2.4 KiB
TypeScript

import { Hono } from "hono/tiny";
import { createRoute } from "../../../modules/api-utils/createRoute";
import { companies } from "../../../managers/companies";
import { apiResponse } from "../../../modules/api-utils/apiResponse";
import { ContentfulStatusCode } from "hono/utils/http-status";
import { authMiddleware } from "../../middleware/authorization";
import GenericError from "../../../Errors/GenericError";
import { processObjectValuePerms } from "../../../modules/permission-utils/processObjectPermissions";
/* /v1/company/companies/[id] */
export default createRoute(
"get",
["/companies/:identifier"],
async (c) => {
const company = await companies.fetch(c.req.param("identifier") as string);
const includeAddress = c.req.query("includeAddress") === "true";
const includePrimaryContact =
c.req.query("includePrimaryContact") === "true";
const includeAllContacts = c.req.query("includeAllContacts") === "true";
const includeAllAddresses = c.req.query("includeAllAddresses") === "true";
console.log(company.toJson({ includeAddress, includePrimaryContact, includeAllContacts }));
// Check for address-specific permission if includeAddress is requested
if (includeAddress) {
const user = c.get("user");
if (!user || !(await user.hasPermission("company.fetch.address"))) {
throw new GenericError({
name: "InsufficientPermission",
message: "You do not have permission to view company addresses.",
status: 403,
});
}
}
// Check for contacts permission if includeAllContacts is requested
if (includeAllContacts) {
const user = c.get("user");
if (!user || !(await user.hasPermission("company.fetch.contacts"))) {
throw new GenericError({
name: "InsufficientPermission",
message: "You do not have permission to view company contacts.",
status: 403,
});
}
}
const companyData = company.toJson({
includeAddress,
includePrimaryContact,
includeAllContacts,
includeAllAddresses,
});
const gatedData = await processObjectValuePerms(
companyData,
"obj.company",
c.get("user"),
);
const response = apiResponse.successful(
"Company Fetched Successfully!",
gatedData,
);
return c.json(response, response.status as ContentfulStatusCode);
},
authMiddleware({ permissions: ["company.fetch"] }),
);