我开始将旧的堆栈服务器迁移到GraphQL,所以我发现阿波罗graphql docs建议您将获取和处理数据的功能放在请求上下文中,如下所示:
export const generateUserModel = ({ user }) => ({
getAll: () => { /* fetching/transform logic for all users */ },
getById: (id) => { /* fetching/transform logic for a single user */ },
getByGroupId: (id) => { /* fetching/transform logic for a group of users */ },
});
context: ({ req }) => {
// get the user token from the headers
const token = req.headers.authentication || '';
// try to retrieve a user with the token
const user = getUser(token);
// optionally block the user
// we could also check user roles/permissions here
if (!user) throw new AuthorizationError('you must be logged in to query this schema');
// add the user to the context
return {
user,
models: {
User: generateUserModel({ user }),
...
}
};
},
但是如果generateUserModel
返回600行代码(函数),又还有generatePostModel
,generateCategoryModel
,...等等怎么办?
不会影响应用程序的内存使用,因为此代码是针对每个请求生成的。
如果以这种方式实现,会更糟吗?
export class UserModel {
constructor(user){
this.user=user
}
getAll=() => { /* fetching/transform logic for all users */ },
getById=(id) => { /* fetching/transform logic for a single user */ },
getByGroupId=(id) => { /* fetching/transform logic for a group of users */ },
}
context: ({ req }) => {
// get the user token from the headers
const token = req.headers.authentication || '';
// try to retrieve a user with the token
const user = getUser(token);
// optionally block the user
// we could also check user roles/permissions here
if (!user) throw new AuthorizationError('you must be logged in to query this schema');
// add the user to the context
return {
user,
models: {
User: new UserModel( user ),
...
}
};
},