Skip to content
This repository was archived by the owner on Sep 3, 2021. It is now read-only.

feat: allow functional directives via schemaTransforms #530

Merged

Conversation

AdrienLemaire
Copy link
Contributor

@AdrienLemaire AdrienLemaire commented Oct 22, 2020

The graphql-tools documentation suggests to write functional directives instead of class-based ones.

This can be done with neo4j-graphql-js by allowing the schemaTransforms key to makeAugmentedSchema:

const schema = makeAugmentedSchema({
  typeDefs,
  schemaTransforms: [canUpdateRoleTransformer],
});
Example of functional directive I could get working with my fork of neo4j-graphql-js
const canUpdateRoleTransformer = (schema: GraphQLSchema): GraphQLSchema =>
  mapSchema(schema, {
    [MapperKind.OBJECT_FIELD]: (fieldConfig) => {
      let directives: DirectiveUseMap;
      try {
        directives = getDirectives(schema, fieldConfig);
      } catch {
        // GraphQLError [Object]: Argument "direction" has invalid value "BOTH".
        // Not sure why but I'm getting this error when getdirectives reads @relation
        return fieldConfig;
      }

      if (directives.canUpdateRole) {
        const { resolve = defaultFieldResolver } = fieldConfig;
        return {
          ...fieldConfig,
          resolve: async (source, args, context, info) => {
            const decoded = verifyAndDecodeToken({ context });

            const isAuthorized = await context.models.User.canUpdateRoleFor(
              args
            );
            if (isAuthorized) {
              return resolve(source, args, { ...context, user: decoded }, info);
            }

            throw new AuthorizationError({
              message: "unauthorized_resource",
            });
          },
        };
      }
      return fieldConfig;
    },
  });

export default canUpdateRoleTransformer;

Verified

This commit was signed with the committer’s verified signature.
AdrienLemaire Adrien Lemaire
@johnymontana johnymontana merged commit a631ebe into neo4j-graphql:master Oct 22, 2020
@michaeldgraham
Copy link
Collaborator

Thank you for catching this!

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

None yet

3 participants