Files
apophis-fastify/examples/app/src/routes/users.ts
T

74 lines
1.8 KiB
TypeScript

import type { FastifyInstance } from 'fastify'
export async function userRoutes(fastify: FastifyInstance) {
fastify.post('/users', {
schema: {
body: {
type: 'object',
properties: {
name: { type: 'string' },
email: { type: 'string', format: 'email' },
},
required: ['name', 'email'],
},
response: {
201: {
type: 'object',
properties: {
id: { type: 'string' },
name: { type: 'string' },
email: { type: 'string' },
},
},
},
'x-category': 'constructor',
'x-ensures': [
'status:201',
'response_body(this).id != null',
'response_body(this).name == request_body(this).name',
],
},
}, async (req, reply) => {
const { name, email } = req.body as { name: string; email: string }
const id = `user-${Date.now()}`
const user = { id, name, email }
fastify.db.users.set(id, user)
reply.status(201)
return user
})
fastify.get('/users/:id', {
schema: {
params: {
type: 'object',
properties: {
id: { type: 'string' },
},
required: ['id'],
},
response: {
200: {
type: 'object',
properties: {
id: { type: 'string' },
name: { type: 'string' },
email: { type: 'string' },
},
},
},
'x-category': 'observer',
'x-ensures': [
'status:200',
'response_body(this).id == request_params(this).id',
],
},
}, async (req) => {
const { id } = req.params as { id: string }
const user = fastify.db.users.get(id)
if (!user) {
throw new Error('User not found')
}
return user
})
}