graphql-directives-middlewares
GraphQL directives as middlewares
install
yarn add graphql-directives-middlewares
You need to have
graphql
andgraphql-tools
installed on your project.
why
We create this library because we needed our directives to be sorted at runtime.
We were on the case we needed to execute our @auth
directive BEFORE our @api
directive take place.
With graphql-directives-middlewares
you just have to declare, in your schema, the directives in order you want them to take place.
With this declaration:
type Query { users: [User] @auth(requires: ADMIN) @api(name: "users")}
Your @auth
directive will be called BEFORE the @api
one.
If you invert @auth
and @api
, then @api
directive will be called BEFORE the @auth
, without changing your implementation!
API
createVisitFieldDefinition
createVisitFieldDefinition(name: string, impl: (params, next) -> (...args))
name
: the directive name you use in yourgql
schemaimpl
: is a function that takeparams
andnext
and return a function that is your graphql custom resolverparams
are your directives argumentsnext
is the next resolver to call, like in a middleware engine
createVisitObject
createVisitObject(name: string, impl: (params, next) -> (...args))
name
: the directive name you use in yourgql
schemaimpl
: is a function that takeparams
andnext
and return a function that is your graphql custom resolverparams
are your directives argumentsnext
is the next resolver to call, like in a middleware engine
usage
Example with a @auth
directive
- define your directive in the schema
` enum Role { ADMIN USER VIEWER } directive @auth(requires: Role = ADMIN) on FIELD_DEFINITION`
- create your directive implementation
'auth' async { const requires: requiredRole = params if !requiredRole return const context definition = args const role = context if !role if definitionreturnType instanceof GraphQLList return throw 'Unauthorized' return }
- bind your directives implementation to your schema
{ const resolvers = Query: id: 'fabien-juif-1' fullName: 'Fabien JUIF' return }
- use your directives
` type Query { users: [User] @auth(requires: ADMIN) }`