diff --git a/src/v2/services/index.ts b/src/v2/services/index.ts index 90041bf..3e0b62c 100644 --- a/src/v2/services/index.ts +++ b/src/v2/services/index.ts @@ -1,10 +1,17 @@ import { Hono } from "hono"; -import { adminServiceValidation, parseSearchParams } from "@/utils/server-helpers"; import { db } from "@/config/db"; +import { createDbId } from "@/utils/db"; +import { adminServiceValidation, parseSearchParams } from "@/utils/server-helpers"; +import { services as servicesTable } from "@/config/db/schema"; import type { ServerContext } from "@/types/hono"; -import { getServiceFiltersSchema, getServicesOutputSchema } from "./schemas"; +import { + createServiceInputSchema, + createServiceOutputSchema, + getServiceFiltersSchema, + getServicesOutputSchema, +} from "./schemas"; const app = new Hono(); @@ -32,4 +39,42 @@ app.get("/", adminServiceValidation, async (c) => { return c.json(getServicesOutputSchema.parse(services)); }); +/** + * @private + * Create a new service, only accessible by admins + */ +app.post("/", adminServiceValidation, async (c) => { + const body = await c.req.json(); + const bodyResult = createServiceInputSchema.safeParse(body); + + if (!bodyResult.success) { + c.status(400); + return c.json({ success: false, message: bodyResult.error.message }); + } + + const input = bodyResult.data; + + const serviceId = createDbId("service"); + const service = await db + .insert(servicesTable) + .values({ + id: serviceId, + name: input.name, + isPersisted: input.isPersisted, + isAdmin: input.isAdmin, + isActive: true, + }) + .returning({ + id: servicesTable.id, + name: servicesTable.name, + isPersisted: servicesTable.isPersisted, + isAdmin: servicesTable.isAdmin, + isActive: servicesTable.isActive, + createdAt: servicesTable.createdAt, + }) + .execute(); + + return c.json(createServiceOutputSchema.parse(service[0])); +}); + export default app; diff --git a/src/v2/services/schemas.ts b/src/v2/services/schemas.ts index a77914d..17b9e4c 100644 --- a/src/v2/services/schemas.ts +++ b/src/v2/services/schemas.ts @@ -29,5 +29,11 @@ const serviceOutput = z.object({ }); export const getServicesOutputSchema = z.array(serviceOutput); + +export const createServiceInputSchema = z.object({ + name: z.string(), + isPersisted: z.boolean(), + isAdmin: z.boolean(), +}); export const createServiceOutputSchema = serviceOutput; export const getServiceOutputSchema = serviceOutput;