Skip to content
This repository has been archived by the owner on Aug 20, 2020. It is now read-only.

Add hash_ids flag to override default integer values #35

Open
wants to merge 5 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 9 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ npm install --save persistgraphql
The build tool binary is called `persistgraphql`. Running it with no other arguments should give:

```
Usage: persistgraphql input_file [output file] [--add_typename]
Usage: persistgraphql input_file [output file] [--add_typename] [--hash_ids]
```

It can be called on a file containing GraphQL query definitions with extension `.graphql`:
Expand All @@ -49,6 +49,14 @@ persistgraphql index.ts output.json

It can also take the `--add_typename` flag which will 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.

```
persistgraphql src/ --hash_ids
```

## Using a hash of the query as an ID to allow scaling for multiple clients

Use the optional `hash_ids` flag to substitute a `sha512` hash of the query as the map value rather then the default which is an incremental integer. This will avoid ID collisions for multiple clients using the same server.

```
persistgraphql src/ --add_typename
```
Expand Down
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@
"apollo-client": "^1.1",
"graphql": "^0.9.4",
"graphql-tag": "^2.0.0",
"hasha": "^3.0.0",
"lodash": "^4.17.4",
"whatwg-fetch": "^2.0.3",
"yargs": "^7.1.0"
Expand Down
37 changes: 28 additions & 9 deletions src/ExtractGQL.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

import fs = require('fs');
import path = require('path');
import hasha = require('hasha');

import {
parse,
Expand Down Expand Up @@ -42,11 +43,12 @@ import {
import _ = require('lodash');

export type ExtractGQLOptions = {
extension?: string,
hashIds?: boolean,
inJsCode?: boolean,
inputFilePath: string,
outputFilePath?: string,
queryTransformers?: QueryTransformer[],
extension?: string,
inJsCode?: boolean,
}

export class ExtractGQL {
Expand All @@ -63,6 +65,9 @@ export class ExtractGQL {
// The file extension to load queries from
public extension: string;

// Whether to use a hash of the query as an ID in the query map
public hashIds: boolean = false;

// Whether to look for standalone .graphql files or template literals in JavaScript code
public inJsCode: boolean = false;

Expand Down Expand Up @@ -106,17 +111,19 @@ export class ExtractGQL {
}

constructor({
extension = 'graphql',
hashIds = false,
inJsCode = false,
inputFilePath,
outputFilePath = 'extracted_queries.json',
queryTransformers = [],
extension = 'graphql',
inJsCode = false,
}: ExtractGQLOptions) {
this.extension = extension;
this.hashIds = hashIds;
this.inJsCode = inJsCode;
this.inputFilePath = inputFilePath;
this.outputFilePath = outputFilePath;
this.queryTransformers = queryTransformers;
this.extension = extension;
this.inJsCode = inJsCode;
}

// Add a query transformer to the end of the list of query transformers.
Expand Down Expand Up @@ -153,7 +160,7 @@ export class ExtractGQL {
const transformedQueryWithFragments = this.getQueryFragments(transformedDocument, transformedDefinition);
transformedQueryWithFragments.definitions.unshift(transformedDefinition);
const docQueryKey = this.getQueryDocumentKey(transformedQueryWithFragments);
result[docQueryKey] = this.getQueryId();
result[docQueryKey] = this.hashIds ? hasha(docQueryKey) : this.getQueryId();
});
return result;
}
Expand Down Expand Up @@ -280,12 +287,12 @@ export class ExtractGQL {

return carry;
};

retDocument.definitions = document.definitions.reduce(
reduceQueryDefinitions,
([] as FragmentDefinitionNode[])
).sort(sortFragmentsByName);

return retDocument;
}

Expand Down Expand Up @@ -333,6 +340,7 @@ export const main = (argv: YArgsv) => {
// These are the unhypenated arguments that yargs does not process
// further.
const args: string[] = argv._
let hashIds: boolean = false;
let inputFilePath: string;
let outputFilePath: string;
const queryTransformers: QueryTransformer[] = [];
Expand All @@ -353,7 +361,18 @@ export const main = (argv: YArgsv) => {
queryTransformers.push(addTypenameTransformer);
}

// Check if we are passed "--hash_ids", if we are, we have to
// use a hash of the query as an ID instead of integers.
// The hash_ids flag will use a sha512 hash of the query as the map value
//rather then the default which is an incremental integer
// This will avoid ID collisions for multiple clients using the same server.
if (argv['hash_ids']) {
console.log('Using hash of query as ID.');
hashIds = true;
}

const options: ExtractGQLOptions = {
hashIds,
inputFilePath,
outputFilePath,
queryTransformers,
Expand Down
31 changes: 30 additions & 1 deletion test/network_interface/ApolloNetworkInterface.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import hasha = require('hasha');
import * as chai from 'chai';
const { assert } = chai;

Expand Down Expand Up @@ -90,6 +91,34 @@ describe('PersistedQueryNetworkInterface', () => {
});
});

describe('Using --hash_ids', () => {
const egql = new ExtractGQL({ hashIds: true, inputFilePath: 'nothing' });
const queriesDocument = gql`
query getAuthor {
author {
firstName
lastName
}
}
query getHouse {
house {
address
}
}
`;
const queryMap = egql.createMapFromDocument(queriesDocument);
const keys = Object.keys(queryMap);

it('should use a hash of the query as the value if --hash_ids is true', () => {
assert.equal(queryMap[keys[0]], hasha(keys[0]));
assert.equal(queryMap[keys[1]], hasha(keys[1]));
});

it('should not use an integer as the value if --hash_ids is true', () => {
assert.notEqual(queryMap[keys[0]], 1);
});
});

describe('sending query ids', () => {
const egql = new ExtractGQL({ inputFilePath: 'nothing' });
const queriesDocument = gql`
Expand Down Expand Up @@ -376,7 +405,7 @@ describe('addPersistedQueries', () => {
const networkInterface = new GenericNetworkInterface();
addPersistedQueries(networkInterface, queryMap);
const expectedId = queryMap[getQueryDocumentKey(request.query)];
return networkInterface.query(request).then((persistedQuery: persistedQueryType) => {
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This was giving a TS error.

return networkInterface.query(request).then((persistedQuery: any) => {
const id = persistedQuery.id;
const variables = persistedQuery.variables;
const operationName = persistedQuery.operationName;
Expand Down
5 changes: 5 additions & 0 deletions typings.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,3 +18,8 @@ declare module 'deep-assign' {
function deepAssign(...objects: any[]): any;
export = deepAssign;
}

declare module 'hasha' {
function hasha(...objects: any[]): any;
export = hasha;
}