[英]How to organize routing in fastify?
请原谅我这些异端言论,但我认为从开发人员体验的角度来看,express 是最好的 api 构建库。 但是阻止我在任何地方使用它的是每个人都一直在说(并通过基准测试确认)它很慢。
我试图为自己选择一个替代方案,但我找不到适合我的。
例如使用 express 我可以简单地组织以下结构:
userAuthMiddleware.js
export const userAuthMiddleware = (req, res, next) => {
console.log('user auth');
next();
};
adminAuthMiddleware.js
export const adminAuthMiddleware = (req, res, next) => {
console.log('admin auth');
next();
};
设置用户路由.js
export const setUserRoutes = (router) => {
router.get('/news', (req, res) => res.send(['news1', 'news2']));
router.get('/news/:id', (req, res) => res.send(`news${req.params.id}`));
};
setAdminRoutes.js
export const setAdminRoutes = (router) => {
router.post('/news', (req, res) => res.send('created'));
router.put('/news/:id', (req, res) => res.send('uodated'));
};
userApi.js
imports...
const userApi = express.Router();
userApi.use(userAuthMiddleware);
// add handlers for '/movies', '/currency-rates', '/whatever'
setUserRoutes(userApi);
export default userApi;
服务器.js
imports...
const app = express();
app.use(bodyparser); // an example of middleware which will handle all requests at all. too lazy to come up with a custom
app.use('/user', userApi);
app.use('/admin', adminApi);
app.listen(3333, () => {
console.info(`Express server listening...`);
});
现在我很容易将处理程序添加到不同的“区域”,这些处理程序将通过必要的中间件。 (例如,用户和管理员授权遵循根本不同的逻辑)。 但是这个中间件我在一个地方添加,不再考虑它,它只是工作。
在这里,我试图在fastify
上组织一个类似的灵活路由结构。 到目前为止,我还没有成功。 要么文档很吝啬,要么我不够专心。
通过“use”添加的 Fastify 中间件从 http 库而不是从 fastify 库获取 req 和 res 对象。 因此,使用它们不是很方便 - 将某些东西从身体中拉出,这将是一个完整的故事。
请举一个比官方文档详细一点的fastify路由示例。 例如,类似于我在 express 上使用 user 和 admin 的示例。
我像这样组织我的路线:
fastify.register(
function(api, opts, done) {
api.addHook('preHandler', async (req, res) => {
//do something on api routes
if (res.sent) return //stop on error (like user authentication)
})
api.get('/hi', async () => {
return { hello: 'world' }
})
// only for authenticated users with role.
api.register(async role => {
role.addHook('preHandler', async (req, res) => {
// check role for all role routes
if (res.sent) return //stop on error
})
role.get('/my_profile', async () => {
return { hello: 'world' }
})
})
done()
},
{
prefix: '/api'
}
)
现在所有对 api/* 的请求都将由 fastify 处理。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.