forked from apollographql/graphql-tag
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathloader.js
More file actions
52 lines (46 loc) · 1.44 KB
/
loader.js
File metadata and controls
52 lines (46 loc) · 1.44 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
"use strict";
const os = require('os');
const gql = require('./src');
// Takes `source` (the source GraphQL query string)
// and `doc` (the parsed GraphQL document) and tacks on
// the imported definitions.
function expandImports(source, doc) {
const lines = source.split(/\r\n|\r|\n/);
let outputCode = `
var names = {};
function unique(defs) {
return defs.filter(
function(def) {
if (def.kind !== 'FragmentDefinition') return true;
var name = def.name.value
if (names[name]) {
return false;
} else {
names[name] = true;
return true;
}
}
)
}
`;
lines.some((line) => {
if (line[0] === '#' && line.slice(1).split(' ')[0] === 'import') {
const importFile = line.slice(1).split(' ')[1];
const parseDocument = `require(${importFile})`;
const appendDef = `doc.definitions = doc.definitions.concat(unique(${parseDocument}.definitions));`;
outputCode += appendDef + os.EOL;
}
return (line.length !== 0 && line[0] !== '#');
});
return outputCode;
}
module.exports = function(source) {
this.cacheable();
const doc = gql`${source}`;
const outputCode = `
var doc = ${JSON.stringify(doc)};
doc.loc.source = ${JSON.stringify(doc.loc.source)};
`;
const importOutputCode = expandImports(source, doc);
return outputCode + os.EOL + importOutputCode + os.EOL + `module.exports = doc;`;
};