graphql-composer
Version:
Create your GraphQL API using composition!
110 lines • 3.16 kB
JavaScript
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.Request = void 0;
const __1 = require("..");
const definition_1 = require("../definition");
class Request {
constructor(type, name, args) {
this._variables = [];
this._type = type;
this._name = name;
this._args = args;
}
get source() {
return `
${this.type} ${this.name}${this.parseVariables()} {
${this.name}(${this.parseArgs(this._args)}) ${this.parseSelections(this.selections)}
}
`;
}
get name() {
return this._name;
}
get selections() {
return this._selections;
}
get args() {
return this._args;
}
get type() {
return this._type;
}
get variables() {
return this._variables;
}
static create(type, name, args) {
return new Request(type, name, args);
}
select(selections) {
this._selections = selections;
return this;
}
setVariables(...variables) {
this._variables = variables;
return this;
}
parseVariables() {
if (this.variables.length > 0) {
this.variables.reduce((prev, variable, index) => {
prev += `$${variable.name}: ${this.parseType(variable.type)}`;
if (index < this.variables.length - 1) {
prev += ",";
}
return prev;
}, "(") + ")";
}
return "";
}
parseArgs(obj) {
const keys = Object.keys(obj);
if (keys.length > 0) {
return keys.reduce((prev, key, index) => {
let value = obj[key];
switch (typeof value) {
case "object":
value = `{ ${this.parseArgs(value)} }`;
break;
case "string":
value = `"${value}"`;
}
prev += `${key}: ${value}`;
if (index < keys.length - 1) {
prev += ", ";
}
return prev;
}, "");
}
return "";
}
parseType(type) {
if (Array.isArray(type)) {
return this.parseType(type[0]);
}
switch (type) {
case String:
return "String";
case Number:
return "Float";
case Boolean:
return "Bool";
}
if (type instanceof __1.GQLAnyType) {
return type.name;
}
if (type instanceof definition_1.RequiredType) {
return this.parseType(type.type) + "!";
}
}
parseSelections(selections) {
return (selections.properties.reduce((prev, property) => {
prev += property;
if (selections.properties.length === 1 && selections.selections) {
prev += this.parseSelections(selections.selections);
}
prev += "\n";
return prev;
}, "{\n") + "}");
}
}
exports.Request = Request;
//# sourceMappingURL=Request.js.map