graphile-utils
Version:
Utilities to help with building graphile-build plugins
76 lines • 2.79 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.gql = exports.embed = exports.isEmbed = void 0;
const graphql_1 = require("graphql");
const $$embed = Symbol("graphile-embed");
function isEmbed(obj) {
return obj && obj[$$embed] === true;
}
exports.isEmbed = isEmbed;
function embed(value) {
return {
[$$embed]: true,
kind: "GraphileEmbed",
value,
};
}
exports.embed = embed;
function isGraphQLDocument(input) {
return (input &&
typeof input === "object" &&
input.kind === "Document" &&
Array.isArray(input.definitions));
}
function gql(strings, ...interpolatedValues) {
const gqlStrings = [];
const placeholders = {};
const additionalDefinitions = [];
const createPlaceholderFor = (value) => {
const rand = String(Math.random());
placeholders[rand] = value;
return `"${rand}"`;
};
for (let idx = 0, length = strings.length; idx < length; idx++) {
gqlStrings.push(strings[idx]);
if (idx === length - 1) {
// NOOP: last string, so no matching interpolatedValue.
}
else {
const interpolatedValue = interpolatedValues[idx];
if (isEmbed(interpolatedValue)) {
gqlStrings.push(createPlaceholderFor(interpolatedValue));
}
else {
if (typeof interpolatedValue === "string") {
gqlStrings.push(String(interpolatedValue));
}
else if (isGraphQLDocument(interpolatedValue)) {
additionalDefinitions.push(...interpolatedValue.definitions);
}
else {
throw new Error(`Placeholder ${idx + 1} is invalid - expected string or GraphQL AST, but received '${typeof interpolatedValue}'. Happened after '${gqlStrings.join("")}'`);
}
}
}
}
const ast = (0, graphql_1.parse)(gqlStrings.join(""));
const visitor = {
enter: (node) => {
if (node.kind === "Document") {
return Object.assign(Object.assign({}, node), { definitions: [...node.definitions, ...additionalDefinitions] });
}
else if (node.kind === "Argument") {
if (node.value.kind === "StringValue") {
if (placeholders[node.value.value]) {
return Object.assign(Object.assign({}, node), { value: placeholders[node.value.value] });
}
}
}
return undefined;
},
};
const astWithPlaceholdersReplaced = (0, graphql_1.visit)(ast, visitor);
return astWithPlaceholdersReplaced;
}
exports.gql = gql;
//# sourceMappingURL=gql.js.map