Fastify 的路由就是中枢里的分拣入口。
import Fastify from 'fastify'
const fastify = Fastify({ logger: true })
fastify.get('/shipments', async function () {
return [{ id: 'S1001' }, { id: 'S1002' }]
})
fastify.get('/shipments/:id', async function (request) {
const { id } = request.params
return { id, status: 'sorting' }
})
fastify.post('/shipments', async function (request, reply) {
reply.code(201)
return { created: true, shipmentId: 'S1003' }
})你可以把它理解成:
高速物流中枢
├── GET /shipments -> 查所有包裹
├── GET /shipments/:id -> 查单个包裹
└── POST /shipments -> 新建包裹运单如果你想写完整配置,而不是只用快捷方法,可以写成 route:
fastify.route({
method: 'GET',
url: '/shipments/:id',
handler: async function (request) {
return { id: request.params.id }
}
})route 的好处是:后面你要挂 schema、局部 hooks、config,都更集中。