GraphQL лучшая практика - PullRequest
       5

GraphQL лучшая практика

0 голосов
/ 04 марта 2019

Я начинаю миграцию старого сервера стека mern на GraphQL, поэтому я обнаружил, что apollo 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 ),
            ...
        }
    };
},
...