105 lines
2.3 KiB
TypeScript
105 lines
2.3 KiB
TypeScript
import { Type, type FastifyPluginCallbackTypebox } from '@fastify/type-provider-typebox'
|
|
import knex from '../../lib/knex.ts'
|
|
import Queries from '../../services/roles/queries.ts'
|
|
|
|
export const RoleFullSchema = Type.Object({
|
|
id: Type.Number(),
|
|
name: Type.String(),
|
|
createdAt: Type.String(),
|
|
createdById: Type.Number(),
|
|
modifiedAt: Type.String(),
|
|
modifiedById: Type.Number(),
|
|
})
|
|
|
|
export const RoleSchema = Type.Pick(RoleFullSchema, ['id', 'name'])
|
|
|
|
export const RoleVariableSchema = Type.Pick(RoleFullSchema, ['name', 'createdById'])
|
|
|
|
const rolesPlugin: FastifyPluginCallbackTypebox = (fastify, _options, done) => {
|
|
const queries = Queries({ knex })
|
|
|
|
fastify.addHook('onRequest', fastify.auth)
|
|
|
|
fastify.route({
|
|
url: '/',
|
|
method: 'GET',
|
|
schema: {
|
|
querystring: RoleFullSchema,
|
|
response: {
|
|
200: Type.Array(RoleFullSchema),
|
|
},
|
|
},
|
|
handler(request) {
|
|
return queries.find(request.query)
|
|
},
|
|
})
|
|
|
|
fastify.route({
|
|
url: '/',
|
|
method: 'POST',
|
|
schema: {
|
|
body: RoleVariableSchema,
|
|
response: {
|
|
201: RoleFullSchema,
|
|
},
|
|
},
|
|
async handler(request, reply) {
|
|
const newRole = request.session.userId
|
|
? {
|
|
...request.body,
|
|
createdById: request.session.userId,
|
|
}
|
|
: request.body
|
|
|
|
return queries.create(newRole).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: RoleVariableSchema,
|
|
response: {
|
|
204: {},
|
|
},
|
|
},
|
|
async handler(request) {
|
|
const patch = request.session.userId
|
|
? {
|
|
...request.body,
|
|
modifiedById: request.session.userId,
|
|
}
|
|
: request.body
|
|
|
|
return queries.update(request.params.id, patch)
|
|
},
|
|
})
|
|
|
|
done()
|
|
}
|
|
|
|
export default rolesPlugin
|