如何在 Fastify 中组织路由?

7

请原谅我的异端言论,但是从开发者体验的角度来看,我认为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();
};

setUserRoutes.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;

server.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 库获取 req 和 res 对象,而不是从 fastify 库获取。因此,使用它们不是非常方便 - 从主体中拉出某些东西将是一个完整的故事。
请给一个比官方文档更详细的 fastify 路由示例。例如与我的 express 用户和管理员示例类似。
1个回答

9

我会按照如下方式组织我的路由:

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 处理。

1
@muturgan 当然,你可以像这样从分离的文件中注册路由:api.register(require('./routes/users'))。在此处了解更多信息:https://www.fastify.io/docs/latest/Routes/ - ZiiMakc

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接