Search code examples
relayjs

How to access rootValue or context for nodedefination


We could check rootValue or context to determine request's role permission for graphql request. How do we check permission for nodeDefination (request thru 'node' ) when using graphql-relay-js ?


Solution

  • You should be able to access your permissions with either context or a value from rootValue, as both are made available to the resolver function:

    export const {nodeField, nodeInterface} = nodeDefinitions(
      function resolveObjectFromID(globalId, context, {rootValue}) {
        const {type, id} = fromGlobalId(globalId);
    
        // Optionally perform auth logic here with either context or rootValue...
    
        // Then proceed with loading as usually; here, for example, using
        // DataLoader.
        const loader = rootValue.loaders[type];
        return (loader && loader.load(id)) || null;
      },
      function resolveGraphQLTypeFromObject(object) {
        return registeredTypes[object.constructor.name] || null;
      },
    );
    

    Note that the context param was added in graphql v0.5.0; prior to that you could only use rootValue. Also note that you can perform permission checks at any level within in the query, not just at the node level, because context and rootValue both get propagated down all the way.