README
Apollo Persisted GraphQL
apollo-persisted-graphql
is a build tool that generates static persisted queries for GraphQL that can be used in both client and server side.
It reads GraphQL queries from source directory and extracts query documents from .graphql
files. Make sure each file MUST contains only one query document. This tool generates hash ID for each query and merge all the hash-query map to a JSON file. This JSON file can be used as whitelisting map for both client and server side.
Installation
npm install --save apollo-persisted-graphql
Setup and Usage
There's three steps to complete the setup.
- Generate persisted queries
- Client side setup
- Server side setup
Generate persisted queries
The tool has a binary file called apollo-persisted-graphql
. Run the binary as follows. Make sure each file must contain only one query document
apollo-persisted-graphql -s <source_directory> -d <destination_file>
This command will generate a JSON file which can be used in both client and server end.
Client side setup
This package wraps apollo-link-persisted-queries
in the client side and replace the hash with the generated hashId.
import { createPersistedQueries } from "apollo-persisted-graphql";
import { createHttpLink } from "apollo-link-http";
import { InMemoryCache } from "apollo-cache-inmemory";
import ApolloClient from "apollo-client";
const queryMap = require("./your_query_map.json");
const link = createPersistedQueries(queryMap)
.concat(createHttpLink({ uri: "/graphql" }));
const client = new ApolloClient({
cache: new InMemoryCache(),
link: link,
});
Server side setup
This package works as a middleware for apollo-server-express
server.
import * as express from "express";
import { ApolloServer } from "apollo-server-express";
import { mapRequestPersistedQueries } from "apollo-persisted-graphql";
const queryMap = require("./your_query_map.json");
const app = express();
app.use(mapRequestPersistedQueries(queryMap));
const server = new ApolloServer();
server.applyMiddleware({ app });
app.listen({port, host }, () =>
console.log(`🚀 Server ready at ${host}:${port}${server.graphqlPath}`));