Graphql-yoga: Add example for using custom directives

Created on 26 Jan 2018  ยท  7Comments  ยท  Source: dotansimha/graphql-yoga

@fabien0102 pointed out a library to use custom directives, that integrates very well with graphql-yoga. It would be great if that could be added to howtographql as a recipe: https://github.com/smooth-code/graphql-directive.

@fabien0102 feel free to share a code snippet in this issue. ๐Ÿ™

arereadme statupr-welcome

Most helpful comment

I open PR to allow passing directiveResolvers as a prop. ๐Ÿ˜„
https://github.com/graphcool/graphql-yoga/pull/152

All 7 comments

This is my diff :wink:

diff --git a/src/index.js b/src/index.js
index 6f5527c..ca1ad08 100644
--- a/src/index.js
+++ b/src/index.js
@@ -1,4 +1,5 @@
 const { GraphQLServer } = require("graphql-yoga");
+const { addDirectiveResolveFunctionsToSchema } = require("graphql-directive");
 const { MongoClient } = require("mongodb");
 const config = require("config");
 const jwt = require("express-jwt");
@@ -61,6 +62,15 @@ const start = async () => {
       }
     });

+    addDirectiveResolveFunctionsToSchema(server.executableSchema, {
+      async auth(resolve, source, { permission }, { user }) {
+      if (!user.permissions.includes(permission)) {
+          throw Error("Not authorized");
+        }
+        return resolve();
+      }
+    });
+
     // Health route
     server.express.get("/health", (req, res) => res.json({ ok: true }));

diff --git a/src/schema.graphql b/src/schema.graphql
index 4824fc0..d22f080 100644
--- a/src/schema.graphql
+++ b/src/schema.graphql

+# Require to have particular permission auth
+directive @auth(permission: String) on FIELD_DEFINITION
+
@@ -76,7 +80,7 @@ type Query {
-  allQuestionnaires: [Questionnaire!]!
+  allQuestionnaires: [Questionnaire!]! @auth(permission: "admin")

Just for clarify, { user } come from to the context and { permission } from the directive argument.

Hum, you can try the implements inside graphql-tools, by passing directiveResolvers to makeExecutableSchema.

@giautm Sure, it was my first try, but with this simple solution I don't need to import graphql-tools and dealing with the schema import (so use the actual implementation of graphql-yoga instead of re-implement all the makeExecutableSchema parsing part (fs, dealing with #import โ€ฆ) ) :wink:

I think graphql-yoga should allow to passing directiveResolvers to makeExecutableSchema as an option. ๐Ÿ˜„

I open PR to allow passing directiveResolvers as a prop. ๐Ÿ˜„
https://github.com/graphcool/graphql-yoga/pull/152

Was this page helpful?
0 / 5 - 0 ratings