|
1 | 1 | const vm = require('vm'); |
2 | 2 | const os = require('os'); |
3 | 3 | const loaderUtils = require('loader-utils'); |
4 | | -const { ExtractGQL } = require('persistgraphql/lib/src/ExtractGQL'); |
5 | | -const queryTransformers = require('persistgraphql/lib/src/queryTransformers'); |
| 4 | +const { print, parse, separateOperations } = require('graphql'); |
| 5 | +const { addTypenameToDocument } = require('apollo-utilities'); |
6 | 6 |
|
7 | 7 | module.exports = function graphQLPersistedDocumentLoader(content) { |
8 | 8 | const deps = []; |
@@ -73,31 +73,27 @@ module.exports = function graphQLPersistedDocumentLoader(content) { |
73 | 73 | }; |
74 | 74 |
|
75 | 75 | function tryAddDocumentId(options, content, querySource) { |
76 | | - const queryMap = new ExtractGQL({ |
77 | | - queryTransformers: [options.addTypename && queryTransformers.addTypenameTransformer].filter(Boolean) |
78 | | - }).createOutputMapFromString(querySource); |
| 76 | + // Every file may contain multiple operations |
| 77 | + const operations = separateOperations(parse(querySource)); |
79 | 78 |
|
80 | | - const queries = Object.keys(queryMap); |
81 | | - if (queries.length > 1) { |
82 | | - queries |
83 | | - .map(query => { |
84 | | - const matched = query.match(/^(mutation|query)\ ([^\ \(\{]*)/) |
85 | | - if (!matched) { |
86 | | - return false |
87 | | - } |
88 | | - return { |
89 | | - operationName: matched[2], |
90 | | - id: generateIdForQuery(options, query) |
91 | | - } |
92 | | - }) |
93 | | - .filter(isValid => !!isValid) |
94 | | - .forEach(({ id, operationName }) => { |
95 | | - content += `${os.EOL}module.exports["${operationName}"].documentId = ${JSON.stringify(id)};` |
96 | | - }) |
97 | | - } else if (queries.length === 1) { |
98 | | - const queryId = generateIdForQuery(options, Object.keys(queryMap)[0]); |
99 | | - content += `${os.EOL}doc.documentId = ${JSON.stringify(queryId)}`; |
100 | | - } |
| 79 | + Object.keys(operations).map((operation) => { |
| 80 | + const document = options.addTypename |
| 81 | + ? addTypenameToDocument(operations[operation]) |
| 82 | + : operations[operation]; |
| 83 | + const query = print(document); |
| 84 | + |
| 85 | + const queryId = generateIdForQuery(options, query); |
| 86 | + |
| 87 | + // Add them as exports to the final file |
| 88 | + // If there is only one operation, it will be the default export |
| 89 | + if (Object.keys(operations).length > 1) { |
| 90 | + content += `${ |
| 91 | + os.EOL |
| 92 | + }module.exports["${operation}"].documentId = ${JSON.stringify(queryId)};`; |
| 93 | + } else { |
| 94 | + content += `${os.EOL}doc.documentId = ${JSON.stringify(queryId)}`; |
| 95 | + } |
| 96 | + }); |
101 | 97 |
|
102 | 98 | return content; |
103 | 99 | } |
|
0 commit comments