@@ -4,6 +4,9 @@ const GQL = require('fastify-gql')
44const JWT = require ( 'fastify-jwt' )
55
66function plugin ( instance , options , next ) {
7+ /**
8+ * Authentication settings
9+ */
710 instance . register ( JWT , {
811 secret : 'supersecret'
912 } )
@@ -16,42 +19,46 @@ function plugin (instance, options, next) {
1619
1720 instance . decorate ( 'authenticate' , async function ( request , reply ) {
1821 try {
22+ // Autorization logic
1923 await request . jwtVerify ( )
2024 } catch ( err ) {
2125 reply . send ( err )
2226 }
2327 } )
2428
29+ instance . addHook ( 'onRoute' , ( routeOptions ) => {
30+ if ( routeOptions . url === '/graphql' ) {
31+ routeOptions . preValidation = [ instance . authenticate ]
32+ }
33+ } )
34+
35+ /**
36+ * GraphQL Stuff
37+ */
2538 const schema = `
26- type Query {
27- add(x: Int, y: Int): Int
28- }
29- `
39+ type Query {
40+ add(x: Int, y: Int): Int
41+ }
42+ `
3043
3144 const resolvers = {
3245 Query : {
3346 add : async ( _ , { x, y } ) => x + y
3447 }
3548 }
3649
50+ // A protected /graphql endpoint is exposed
3751 instance . register ( GQL , {
3852 schema,
3953 resolvers
4054 } )
4155
56+ // I can use the graphql also without authentication
4257 instance . get ( '/public' , async function ( req , reply ) {
4358 const query = '{ add(x: 2, y: 2) }'
4459 return reply . graphql ( query )
4560 } )
4661
47- instance . get ( '/private' ,
48- {
49- preValidation : [ instance . authenticate ]
50- } , async function ( req , reply ) {
51- const query = '{ add(x: 5, y: 5) }'
52- return reply . graphql ( query )
53- } )
54-
5562 next ( )
5663}
5764
0 commit comments