Skip to content

Commit

Permalink
Merge pull request #200 from apollostack/memoize-gql
Browse files Browse the repository at this point in the history
Memoize gql parse results
  • Loading branch information
Sashko Stubailo committed May 11, 2016
2 parents a50182d + e890e07 commit 021ee1f
Show file tree
Hide file tree
Showing 4 changed files with 23 additions and 0 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ Expect active development and potentially significant breaking changes in the `0
### vNEXT

- Improve error message when a dev forgets `gql` to link to docs. [PR #181](https://github.com/apollostack/apollo-client/pull/181)
- Memoize results from `gql`, so that we save time on parsing, and we can use `===` to compare queries for performance. [Issue #199](https://github.com/apollostack/apollo-client/issues/199) [PR #200](https://github.com/apollostack/apollo-client/pull/200)
- ...


Expand Down
8 changes: 8 additions & 0 deletions src/gql.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,21 @@ import {
Document,
} from 'graphql';

const cache: {[queryString: string]: Document} = {};

function parseDocument(doc: string): Document {
if (cache[doc]) {
return cache[doc];
}

const parsed = parse(doc);

if (!parsed || parsed.kind !== 'Document') {
throw new Error('Not a valid GraphQL document.');
}

cache[doc] = parsed;

return parsed as Document;
}

Expand Down
13 changes: 13 additions & 0 deletions test/gql.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import { assert } from 'chai';

import gql from '../src/gql';

describe('gql', () => {
it('parses queries', () => {
assert.equal(gql`{ testQuery }`.kind, 'Document');
});

it('returns the same object for the same query', () => {
assert.isTrue(gql`{ sameQuery }` === gql`{ sameQuery }`);
});
});
1 change: 1 addition & 0 deletions test/tests.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,3 +17,4 @@ import './QueryManager';
import './client';
import './middleware';
import './store';
import './gql';

0 comments on commit 021ee1f

Please sign in to comment.