简体   繁体   中英

GraphQL (Apollo): Can you access directives within resolve function?

I'd like to make every field private, unless otherwise notated with a directive. Is it possible to get this information within a resolve function?

const typeDefs = gql`
  directive @public on FIELD_DEFINITION

  type Query {
    viewer: User @public
    secret: String
  }

  type User {
    id: ID!
  }
`

const schema = makeExecutableSchema({
  typeDefs,
  resolvers,
});

addSchemaLevelResolveFunction(schema, (parent, args, params, info) => {
  // Not possible
  if (info.fieldName.directive === 'public') {
    return parent;
  }

  throw new Error('Authentication required...');
});

const server = new ApolloServer({ schema });

While there is a directives property on FieldNode object in the fieldNodes array, as far as I'm aware it's not populated with the directives that apply to that specific field.

Directives aren't really meant to be used as a flag for something that can be referenced in a resolver (schema level or otherwise). You may consider moving your logic inside the directive's visitFieldDefinition function:

const { defaultFieldResolver } = require('graphql')
const { SchemaDirectiveVisitor } = require('graphql-tools')

class PublicDirective extends SchemaDirectiveVisitor {
  visitFieldDefinition(field) {
    const { resolve = defaultFieldResolver } = field
    field.resolve = async function (source, args, context, info) {
      if (someCondition) {
        throw new SomeError()
      }
      return resolve.apply(this, [source, args, context, info])
    }
  }
}

const schema = makeExecutableSchema({
  typeDefs,
  resolvers,
  schemaResolvers: {
    public: PublicDirective,
  },
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM