UNPKG

1.59 kBJavaScriptView Raw
1const Asset = require('../Asset');
2const localRequire = require('../utils/localRequire');
3const Resolver = require('../Resolver');
4const fs = require('@parcel/fs');
5const os = require('os');
6
7const IMPORT_RE = /^# *import +['"](.*)['"] *;? *$/;
8
9class GraphqlAsset extends Asset {
10 constructor(name, options) {
11 super(name, options);
12 this.type = 'js';
13
14 this.gqlMap = new Map();
15 this.gqlResolver = new Resolver(
16 Object.assign({}, this.options, {
17 extensions: ['.gql', '.graphql']
18 })
19 );
20 }
21
22 async traverseImports(name, code) {
23 this.gqlMap.set(name, code);
24
25 await Promise.all(
26 code
27 .split(/\r\n?|\n/)
28 .map(line => line.match(IMPORT_RE))
29 .filter(match => !!match)
30 .map(async ([, importName]) => {
31 let {path: resolved} = await this.gqlResolver.resolve(
32 importName,
33 name
34 );
35
36 if (this.gqlMap.has(resolved)) {
37 return;
38 }
39
40 let code = await fs.readFile(resolved, 'utf8');
41 await this.traverseImports(resolved, code);
42 })
43 );
44 }
45
46 collectDependencies() {
47 for (let [path] of this.gqlMap) {
48 this.addDependency(path, {includedInParent: true});
49 }
50 }
51
52 async parse(code) {
53 let gql = await localRequire('graphql-tag', this.name);
54
55 await this.traverseImports(this.name, code);
56
57 const allCodes = [...this.gqlMap.values()].join(os.EOL);
58
59 return gql(allCodes);
60 }
61
62 generate() {
63 return `module.exports=${JSON.stringify(this.ast, null, 2)};`;
64 }
65}
66
67module.exports = GraphqlAsset;