@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. ๐
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
Most helpful comment
I open PR to allow passing
directiveResolversas a prop. ๐https://github.com/graphcool/graphql-yoga/pull/152