Skip to content

Commit

Permalink
Initial commit
Browse files Browse the repository at this point in the history
  • Loading branch information
leoasis committed Nov 28, 2017
0 parents commit 21d6dcf
Show file tree
Hide file tree
Showing 13 changed files with 3,424 additions and 0 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
node_modules
9 changes: 9 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
MIT License

Copyright (c) 2017 Leonardo Garcia Crespo

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
60 changes: 60 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
# GraphQL Persisted Document Loader

Webpack loader that assigns a documentId to a compiled GraphQL document's AST.

## Why

When dealing with persisted documents in GraphQL, tools like [PersistGraphQL](https://github.com/apollographql/persistgraphql) generate a map from query to id that helps you determine the id for a given document and send that to the server instead of the full query string. This is useful to optimize the payload sent to the server, and also to allow the server to not parse and validate those queries, and also to optimize them particularly since the server now knows which queries the client will send.

However, on the client we still need to load up this map of queries to ids, which may become too big to load in one shot if your app has quite some queries. Moreover, if you are using code splitting, you'll be loading a file that includes queries for sections of your app that may never be executed or loaded.

To solve this problem, this loader works after the [graphql-tag loader](https://github.com/apollographql/graphql-tag) by injecting the document id as a property to the compiled AST, so you can access it directly when importing/requiring the document. This effectively co-locates the id with the query, and you no longer need a big lookup map to get the id for a particular query document.

## Installation and setup

You need to have the [graphql-tag](https://github.com/apollographql/graphql-tag) package installed.

First install this package

```
npm install --save-dev graphql-persisted-document-loader
```

Then in the webpack configuration, add the loader **BEFORE** the `graphql-tag/loader`:

> Note: This loader currently only works for .graphql files. It does not work for `gql` calls within JS files.
```js
module.exports = {
// ...,
module: {
rules: [
{
test: /\.graphql$/, use: [
{ loader: 'graphql-persisted-document-loader' }, // <= Before graphql-tag/loader!
{ loader: 'graphql-tag/loader' }
]
}
]
}
};
```

## Usage

When importing or requiring `.graphql` files, you'll have the `documentId` property accessible from the imported object:

```js
import query from 'query.graphql';
// OR
const query = require('query.graphql');

console.log(query.documentId); // => 5eef6cd6a52ee0d67bfbb0fdc72bbbde4d70331834eeec95787fe71b45f0a491
```

## Loader options

* `generateId`: `function (querySource: string) => string` Function that allows to generate a custom documentId from the query source. This source contains all the dependencies sources concatenated, so it's suitable for hashing. By default it generates the sha256 hash in hexadecimal format. The source is concatenated in the same way as you'd get it from the `persistgraphql` tool, so hashing the queries from the output of that tool should get you the same hash value.
* `addTypename`: `boolean` Apply a query transformation to the query documents, adding the __typename field at every level of the query. You must pass this option if your client code uses this query transformation.


14 changes: 14 additions & 0 deletions example/app.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import query from './query.graphql';
import queryWithDeps from './query-with-deps.graphql';

const el = document.createElement('div');

el.innerHTML = `
<h1>Document id: ${query.documentId}</h1>
<pre>${JSON.stringify(query, null, 4)}</pre>
<hr />
<h1>Document id: ${queryWithDeps.documentId}</h1>
<pre>${JSON.stringify(queryWithDeps, null, 4)}</pre>
`;

document.body.appendChild(el);
6 changes: 6 additions & 0 deletions example/dep.graphql
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
fragment Dep on Foo {
qux {
quix
quaz
}
}
8 changes: 8 additions & 0 deletions example/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
<html>
<head>
<title>Webpack example</title>
</head>
<body>
<script src="./bundle.js"></script>
</body>
</html>
9 changes: 9 additions & 0 deletions example/query-with-deps.graphql
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
#import './dep.graphql'

query SomeQuery {
foo {
bar
baz
...Dep
}
}
10 changes: 10 additions & 0 deletions example/query.graphql
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
query SomeQuery {
foo {
bar
baz
qux {
quix
quaz
}
}
}
31 changes: 31 additions & 0 deletions example/webpack.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
const path = require('path');

module.exports = {
context: __dirname,
entry: './app.js',
output: {
filename: 'bundle.js'
},
devServer: {
contentBase: path.join(__dirname)
},
stats: 'detailed',
module: {
rules: [
{
test: /\.graphql$/, use: [
{
loader: '../index',
options: {
addTypename: true,
// generateId(querySource) {
// return require('crypto').createHash('md5').update(querySource).digest('base64').substring(0, 8);
// }
}
},
{ loader: 'graphql-tag/loader' }
]
}
]
}
};
80 changes: 80 additions & 0 deletions index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
const vm = require('vm');
const os = require('os');
const loaderUtils = require('loader-utils');
const { ExtractGQL } = require('persistgraphql/lib/src/ExtractGQL');
const queryTransformers = require('persistgraphql/lib/src/queryTransformers');
const loadModuleRecursively = require('./load-module-recursively');

module.exports = function graphQLpersistedDocumentLoader(content) {
const deps = [];
const context = this;
const options = loaderUtils.getOptions(this) || {};

const sandbox = {
require(file) {
deps.push(new Promise((resolve, reject) => {
loadModuleRecursively(context, file, (err, source, sourceMap, module) => {
if (err) {
reject(err);
} else {
resolve({ source, sourceMap, module });
}
});
}));
return { definitions: [] };
},
module: {
exports: null
}
};
vm.runInNewContext(content, sandbox);

const doc = sandbox.module.exports;
this._module._graphQLQuerySource = doc.loc.source.body;

if (deps.length === 0) {
content = tryAddDocumentId(options, content, this._module._graphQLQuerySource);
return content;
}

const callback = this.async();

Promise.all(deps).then((modules) => {
modules.forEach((mod, index) => {
this._module._graphQLQuerySource += mod.module._graphQLQuerySource;
});

try {
content = tryAddDocumentId(options, content, this._module._graphQLQuerySource);
} catch (e) {
callback(e);
}

callback(null, content);
}).catch((err) => {
console.log('error', err);
callback(err);
});
};

function tryAddDocumentId(options, content, querySource) {
const queryMap = new ExtractGQL({
queryTransformers: [options.addTypename && queryTransformers.addTypenameTransformer].filter(Boolean)
}).createOutputMapFromString(querySource);

const queries = Object.keys(queryMap);
if (queries.length > 1) {
throw new Error('Only one operation per file is allowed');
} else if (queries.length === 1) {
const queryId = generateIdForQuery(options, Object.keys(queryMap)[0]);
content += `${os.EOL}doc.documentId = ${JSON.stringify(queryId)}`;
}

return content;
}

function generateIdForQuery(options, query) {
if (options.generateId) return options.generateId(query);

return require('crypto').createHash('sha256').update(query).digest('hex');
}
53 changes: 53 additions & 0 deletions load-module-recursively.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
/* eslint-disable */
// This code is copied from Webpack's code and modified so that it can load modules
// recursively, otherwise the loader for persisted queries fails if there are
// queries that depend on other files.

// There's an issue in Webpack that talks about this problem
// https://github.com/webpack/webpack/issues/4959
// Once it's solved, we won't need this file.
// The file copied from is https://github.com/webpack/webpack/blob/master/lib/dependencies/LoaderPlugin.js
const LoaderDependency = require('webpack/lib/dependencies/LoaderDependency');

module.exports = function loadModuleRecursively(loaderContext, request, callback) {
const {
_compilation: compilation,
_module: module
} = loaderContext;
const dep = new LoaderDependency(request);
dep.loc = request;
compilation.addModuleDependencies(module, [
[dep]
], true, "lm", true /* This is _false_ in the original file */, (err) => {
if(err) return callback(err);

if(!dep.module) return callback(new Error("Cannot load the module"));
if(dep.module.building) dep.module.building.push(next);
else next();

function next(err) {
if(err) return callback(err);

if(dep.module.error) return callback(dep.module.error);
if(!dep.module._source) throw new Error("The module created for a LoaderDependency must have a property _source");
let source, map;
const moduleSource = dep.module._source;
if(moduleSource.sourceAndMap) {
const sourceAndMap = moduleSource.sourceAndMap();
map = sourceAndMap.map;
source = sourceAndMap.source;
} else {
map = moduleSource.map();
source = moduleSource.source();
}
if(dep.module.fileDependencies) {
dep.module.fileDependencies.forEach((dep) => loaderContext.addDependency(dep));
}
if(dep.module.contextDependencies) {
dep.module.contextDependencies.forEach((dep) => loaderContext.addContextDependency(dep));
}
return callback(null, source, map, dep.module);
}
});
};
/* eslint-enable */
21 changes: 21 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
{
"name": "graphql-persisted-document-loader",
"version": "1.0.0",
"description": "Webpack loader that adds a documentId to a compiled graphql document, which can be used when persisting/retrieving documents",
"main": "index.js",
"repository": "[email protected]:leoasis/graphql-persisted-document-loader.git",
"author": "Leonardo Andres Garcia Crespo <[email protected]>",
"license": "MIT",
"scripts": {
"start": "webpack-dev-server --config ./example/webpack.config.js"
},
"devDependencies": {
"graphql-tag": "^2.5.0",
"webpack": "^3.8.1",
"webpack-dev-server": "^2.9.5"
},
"dependencies": {
"loader-utils": "^1.1.0",
"persistgraphql": "^0.3.11"
}
}
Loading

0 comments on commit 21d6dcf

Please sign in to comment.