@therobot/api-schema-directives

0.0.2 • Public • Published

@therobot/api-schema-directives

I am not sure if storing directives in separate package is a good idea.

There is not much docs on using directives in apollo-federation, so i am useing them like this, in every federated endpoint i need them

Usage

const { ApolloServer, gql } = require('apollo-server-cloud-functions')
const { buildFederatedSchema } = require('@apollo/federation')
const { attachDirectiveResolvers } = require('graphql-tools')

const typeDefs = gql`
  directive @auth on FIELD_DEFINITION
  extend type Query {
    me: Account @auth
  }
`

const resolvers = { Query: { me: () => 'secure' } }
const jwtHandler = require('@therobot/jwt-handler')
const context = ({ req }) => {
  const jwt = jwtHandler(req.headers['authorization'])
  return { jwt }
}

const directiveResolvers = require('@therobot/api-schema-directives')
const schema = buildFederatedSchema([{ typeDefs, resolvers }])
attachDirectiveResolvers(schema, directiveResolvers)

const server = new ApolloServer({
  schema,
  playground: true,
  introspection: true,
  context,
})

exports.handler = server.createHandler()

Auth, custom handlers

Define directive with some arguments

# `role` argument is defined as array
directive @auth(role: [String]) on FIELD_DEFINITION

extend type Query {
  # brakets can be ommited
  me: Account @auth(role: "account")
}

And make a handler in context

const context = ({ req }) => {
  const jwt = jwtHandler(req.headers['authorization'])
  return {
    jwt,
    onAuthRole: (jwtRole, directiveRole) => {
      return directiveRole.includes(jwtRole)
    },
  }
}

field will not be resolved if JWT have no field that matches argumentName directive was called with.

@auth(argumentName: "value")

field will not be resolved if handler is not defined,

onAuthArgumentName: () => true


telegram

Readme

Keywords

none

Package Sidebar

Install

npm i @therobot/api-schema-directives

Weekly Downloads

4

Version

0.0.2

License

ISC

Unpacked Size

3.04 kB

Total Files

4

Last publish

Collaborators

  • gcoda