我已经设置了一个基本的应用程序来试验 RBAC、Express 服务器和 API 设计。我已经设置了各种 API 路由,这些路由当前将我从数据库获得的响应返回为 JSON。例如,这是一条返回用户、他们的用户详细信息和他们拥有的所有苹果的路由(苹果是我的虚构资源)。
userProfile: async (req, res) => {
const isLoggedIn = req.isAuthenticated();
if (!isLoggedIn) {
return res.status(401).end('Unauthorized');
};
const userId = req.params.id;
const isAdmin = hasRole(req, 'admin');
if (!isAdmin && !isUser(req, parseInt(userId))) {
return res.status(401).end('Unauthorized');
};
const results = await db.users.getUserProfile(userId);
res.status(200).json(results.rows);
}
我现在得到如下回复:
[{
"user_id": 2,
"user_name": "ben",
"user_role": "user",
"apple_id": 12,
"apple_name": "another apple"
},
{
"user_id": 2,
"user_name": "ben",
"user_role": "user",
"apple_id": 6,
"apple_name": "Granny Smith"
}]
很好,没有问题。现在我想对响应进行建模以确保它符合JSON API 规范
我应该在哪里/如何做到这一点?我应该使用一些中间件吗?或者我应该创建一些工厂或其他东西来接受响应并根据需要对其进行建模?
任何帮助将非常感激!