Miss any of our Open RFC calls?Watch the recordings here! »

relay-compiler-plus

1.2.11 • Public • Published

relay-compiler-plus

npm version npm downloads npm npm

Custom relay compiler which supports persisted queries :bowtie:

Installation

npm i -g relay-compiler-plus

Usage

  1. At your project dir, run

    relay-compiler-plus --schema <SCHEMA_FILE_PATH> --src <SRC_DIR_PATH>
    

    where <SCHEMA_FILE_PATH> is the path to your schema.graphql or schema.json file.

    This should generate:

    • root query files (*.graphql.js) containing query ids and null query text.
    • A queryMap.json file under <SRC_DIR_PATH>/queryMap.json. This file can be consumed by the server to map the query ids to actual queries.
  2. On the server, you need map the query ids to actual queries.

    First, add relay-compiler-plus to your project.

    yarn add relay-compiler-plus
    

    Then, use matchQueryMiddleware prior to express-graphql to match the queryIds. Note that queryMap.json is auto-generated by relay-compiler-plus at step 1.

    import Express from 'express';
    import expressGraphl from 'express-graphql';
    import {matchQueryMiddleware} from 'relay-compiler-plus'; // do this
    import queryMapJson from '../queryMap.json'; // do this
     
    const app = Express();
     
    app.use('/graphql',
      matchQueryMiddleware(queryMapJson), // do this
      expressGraphl({
        schema: graphqlSchema,
        graphiql: true,
      }));
  3. On the client, modify your relay network fetch implementation to pass a queryId parameter in the request body instead of a query parameter.

    function fetchQuery(operation, variables,) {
      return fetch('/graphql', {
        method: 'POST',
        headers: {
          'content-type': 'application/json'
        },
        body: JSON.stringify({
          queryId: operation.id, // do this
          variables,
        }),
      }).then(response => {
        return response.json();
      });
    }

Example

Check the example for a fully working demo.