graphql-kit / graphql-lodash

🛠 Data manipulation for GraphQL queries with lodash syntax
https://apis.guru/graphql-lodash/
MIT License
1.23k stars 48 forks source link

express-graphql / graphqlHTTP implementation example #51

Open bouviervj opened 1 year ago

bouviervj commented 1 year ago

Thank you for you great job - I was looking to implement the server version on the express-graphql stack here is my implementation as an example - not perfect but works:

     // schema is the initial schema you wanted to deploy

     schema = extendSchema(
      schema,
      lodashDirectiveAST,
    );

    app.use('/graphql', (...args) => {

      graphqlHTTP({
        schema: schema,
        graphiql: true,
        customParseFn : (source) => {

          // get the query from the body
          let body = source.body;

          // Process the lodash parsing
          let { query, transform } = graphqlLodash(body);

          // Replace the body in the Source instance
          source.body = query;

          // Use the standard parse method
          let documentAST = graphql.parse(source);

          // store the transform in the document, an element conveyed in customExecuteFn
          documentAST.transform = transform;

          return documentAST;

        },
        customExecuteFn : async ( { document, ...args } ) => {

          // Execut first
          let result = await graphql.execute( { document: document, ...args });

          // Then back transform the query.
          result.data = document.transform(result.data);

          // Return the result
          return result;

        }
      })(...args);

    });