Skip to content

Commit

Permalink
Merge pull request #9 from gajus/feature/strip-loc
Browse files Browse the repository at this point in the history
Strip loc from GraphQL AST
  • Loading branch information
Sashko Stubailo authored Sep 17, 2016
2 parents 14205fb + 5cf5f41 commit ca22d51
Show file tree
Hide file tree
Showing 3 changed files with 38 additions and 20 deletions.
36 changes: 36 additions & 0 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,40 @@ var parse = require('./parser').parse;

var cache = {};

function stripLoc (doc) {
var docType = Object.prototype.toString.call(doc);

if (docType === '[object Array]') {
return doc.map(stripLoc);
}

if (docType !== '[object Object]') {
throw new Error('Unexpected input.');
}

if (doc.loc) {
delete doc.loc;
}

var keys = Object.keys(doc);
var key;
var value;
var valueType;

for (key in keys) {
if (keys.hasOwnProperty(key)) {
value = doc[keys[key]];
valueType = Object.prototype.toString.call(value);

if (valueType === '[object Object]' || valueType === '[object Array]') {
doc[keys[key]] = stripLoc(value);
}
}
}

return doc;
}

function parseDocument(doc) {
if (cache[doc]) {
return cache[doc];
Expand All @@ -13,6 +47,8 @@ function parseDocument(doc) {
throw new Error('Not a valid GraphQL document.');
}

parsed = stripLoc(parsed);

cache[doc] = parsed;

return parsed;
Expand Down
1 change: 0 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,6 @@
"babel-register": "^6.9.0",
"chai": "^3.5.0",
"graphql": "^0.6.0",
"lodash": "^4.13.1",
"mocha": "^2.5.3",
"webpack": "^1.13.1"
}
Expand Down
21 changes: 2 additions & 19 deletions test.js
Original file line number Diff line number Diff line change
@@ -1,23 +1,6 @@
var gqlRequire = require('./index');
var gqlDefault = require('./index').default;
import { assert } from 'chai';
import _ from 'lodash';

function stripLoc(obj) {
if (_.isArray(obj)) {
return obj.map(stripLoc);
}

if (! _.isObject(obj)) {
return obj;
}

const omitted = _.omit(obj, ['loc']);

return _.mapValues(omitted, (value) => {
return stripLoc(value);
});
}

[gqlRequire, gqlDefault].forEach((gql, i) => {
describe(`gql ${i}`, () => {
Expand All @@ -30,14 +13,14 @@ function stripLoc(obj) {
});

it('is correct for a simple query', () => {
const ast = stripLoc(gql`
const ast = gql`
{
user(id: 5) {
firstName
lastName
}
}
`);
`;

assert.deepEqual(ast, {
"kind": "Document",
Expand Down

0 comments on commit ca22d51

Please sign in to comment.