graphql-middleware icon indicating copy to clipboard operation
graphql-middleware copied to clipboard

bind middleware to return types

Open milad2golnia opened this issue 2 years ago • 0 comments

Problem

Is it possible to assign my middleware to a specific return type? Let's elaborate it using an example.

Example

I'm defining my schema in SDL (Schema Definition Language):

let schema = buildschema(`
    schema {
        query: RootQuery,
        mutation: RootMutation
    }
    type service{...}
    type notservice{...}
    type RootQuery {
        query1:    service
        query2:    service
        query3:    notservice
    }
    type RootMutation{...}
`);

I want to execute my middleware when a service is returned, How can I do it?

Current Solution

The current way is to apply middleware one by one to every query which is returning service as result:

    let newSchema = applyMiddleware(querySchema, {
         RootQuery: {
             query1:     myMiddleware,
             query2:     myMiddleware
         }
    })

But this solution is not maintainable because if I later add another query(e.g. query4) with the same return type (i.e. service), I should again modify my code:

    let newSchema = applyMiddleware(querySchema, {
         RootQuery: {
             query1:     myMiddleware,
             query2:     myMiddleware,
             query4:     myMiddleware
         }
    })

milad2golnia avatar Aug 21 '22 14:08 milad2golnia