import { Type, type FastifyPluginCallbackTypebox } from '@fastify/type-provider-typebox' import emitter from '../../lib/emitter.ts' import knex from '../../lib/knex.ts' import Queries from '../../services/admissions/queries.ts' import { RoleSchema } from './roles.ts' export const AdmissionSchema = Type.Object({ id: Type.Number(), regex: Type.String(), roles: Type.Array(RoleSchema), createdAt: Type.String({ format: 'date-time' }), createdById: { type: 'integer' }, createdBy: { type: 'object', properties: { id: { type: 'integer' }, email: { type: 'string' } } }, modifiedAt: [Type.String({ format: 'date-time' }), Type.Null()], modifiedById: [Type.Number, Type.Null()], }) export const AdmissionVariableSchema = Type.Object({ regex: Type.String(), roles: Type.Array(Type.Number()), createdById: Type.Optional(Type.Number()), modifiedById: Type.Optional(Type.Number()), }) const admissionsPlugin: FastifyPluginCallbackTypebox = (fastify, _options, done) => { const queries = Queries({ emitter, knex }) fastify.addHook('onRequest', fastify.auth) fastify.route({ url: '/', method: 'GET', schema: { response: { 200: { type: 'array', items: { $ref: 'admission' } }, }, }, handler(request) { return queries.find(request.query) }, }) fastify.route({ url: '/', method: 'POST', schema: { body: AdmissionVariableSchema, response: { 201: AdmissionSchema, }, }, async handler(request, reply) { let body = request.body if (request.session?.userId) { body = { ...request.body, createdById: request.session.userId, } } return queries.create(body).then((row) => { return reply.header('Location', `${request.url}/${row.id}`).status(201).send(row) }) }, }) fastify.route({ url: '/:id', method: 'DELETE', schema: { params: Type.Object({ id: Type.Number(), }), response: { 204: {}, 404: {}, }, }, handler(request, reply) { return queries.removeById(request.params.id).then((count) => reply.status(count > 0 ? 204 : 404).send()) }, }) fastify.route({ url: '/:id', method: 'PATCH', schema: { params: Type.Object({ id: Type.Number(), }), body: AdmissionVariableSchema, response: { 204: {}, }, }, async handler(request) { let body = request.body if (request.session.userId) { body = { ...request.body, modifiedById: request.session.userId, } } return queries.update(request.params.id, body) }, }) done() } export default admissionsPlugin