gqlpq
Version:
Utility to parse GraphQL files from your client and generate list of persisted queries.
95 lines • 3.41 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.Parser = void 0;
const graphql_1 = require("graphql");
const apollo_link_persisted_queries_1 = require("apollo-link-persisted-queries");
const operationFilter = (doc) => {
return doc.definitions.filter(definition => definition.kind === 'OperationDefinition');
};
const fragmentFilter = (doc) => {
return doc.definitions.filter(definition => definition.kind === 'FragmentDefinition');
};
class Parser {
constructor() {
this.operations = new Map();
this.fragments = new Map();
this.transformers = [];
this.idGenerator = apollo_link_persisted_queries_1.defaultGenerateHash;
}
addTransformer(transformer) {
this.transformers.push(transformer);
}
setIdGenerator(generator) {
this.idGenerator = generator;
}
parse(data) {
let doc;
try {
doc = graphql_1.parse(data.toString('utf-8'));
}
catch (err) {
throw new Error(`parsing graphql file: ${err.message}`);
}
operationFilter(doc).forEach(operation => {
if (!operation.name) {
throw Error(`operation shoud have name: ${graphql_1.print(operation)}`);
}
else if (this.operations.has(operation.name.value)) {
throw Error(`duplicated operation name: ${operation.name.value}`);
}
else {
this.operations.set(operation.name.value, operation);
}
});
fragmentFilter(doc).forEach(fragment => {
if (!fragment.name) {
throw Error(`fragment shoud have name: ${graphql_1.print(fragment)}`);
}
else if (this.fragments.get(fragment.name.value)) {
throw Error(`duplicated fragment name: ${fragment.name.value}`);
}
else {
this.fragments.set(fragment.name.value, fragment);
}
});
}
getQueries() {
const queries = {};
this.operations.forEach(operation => {
let queryString = graphql_1.print(operation);
this.getQueryFragments(operation).forEach(fragment => {
queryString += '\n\n' + graphql_1.print(fragment);
});
let doc = graphql_1.parse(queryString);
this.transformers.forEach(transformer => doc = transformer(doc));
queries[this.idGenerator(doc)] = graphql_1.print(doc);
});
return queries;
}
getQueryFragments(query) {
const fragments = new Set();
this.recQueryFragments(query, fragments);
return [...fragments];
}
;
recQueryFragments(query, fragments) {
const that = this;
graphql_1.visit(query, {
FragmentSpread(node) {
const fragment = that.fragments.get(node.name.value);
if (!fragment) {
throw Error(`fragment definition not found: ${node.name.value}`);
}
else {
fragments.add(fragment);
}
const next = that.operations.get(node.name.value);
if (next) {
that.recQueryFragments(next, fragments);
}
},
});
}
}
exports.Parser = Parser;
//# sourceMappingURL=pq.js.map