@backland/schema
Version:
TypeScript schema declaration and validation library with static type inference
221 lines (216 loc) • 9.17 kB
JavaScript
function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } }
function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; }
function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return typeof key === "symbol" ? key : String(key); }
function _toPrimitive(input, hint) { if (typeof input !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (typeof res !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); }
import { createStore, inspectObject, isBrowser, RuntimeError } from '@backland/utils';
import { CircularDeps } from '../CircularDeps';
import { createObjectType, parseField } from '../ObjectType';
import { extendObjectDefinition } from '../extendObjectDefinition';
import { extendType } from '../extendType';
import { initGraphType } from './initGraphType';
export class GraphType {
get id() {
if (this.optionalId) return this.optionalId;
throw new RuntimeError(['The method you are trying to execute needs the graphType used to be identified.' + ' Use ``myType.identify("name")`` and try again.', 'You can also read that information from ``myType.optionalId.``', '', ''].join('\n'), this.__lazyGetter.definitionInput);
}
get optionalId() {
return this._optionalId;
}
constructor() {
var _this = this;
_defineProperty(this, "__isGraphType", true);
_defineProperty(this, "definition", void 0);
_defineProperty(this, "_optionalId", undefined);
_defineProperty(this, "__lazyGetter", void 0);
_defineProperty(this, "touched", false);
_defineProperty(this, "__hidden", false);
_defineProperty(this, "identify", name => {
this._optionalId = name;
if (GraphType.register.has(name)) {
//
} else {
if (!isBrowser()) {
var _CircularDeps$typesWr;
(_CircularDeps$typesWr = CircularDeps.typesWriter) === null || _CircularDeps$typesWr === void 0 ? void 0 : _CircularDeps$typesWr.BacklandWatchTypesPubSub.emit('created', {
graphType: this
});
}
GraphType.register.set(name, this);
}
});
_defineProperty(this, "parse", (input, options) => {
var field = this.__lazyGetter.field;
try {
var _options = typeof options === 'object' ? options : {};
var {
includeHidden = true
} = _options;
if (this.__hidden && !includeHidden) return undefined;
return field.parse(input, _options);
} catch (e) {
var message = e.message;
if (field.list) {
message = "\u27A4 ".concat(message);
} else {
message = "\u27A4 ".concat(this.optionalId || '', " ").concat(e.message);
}
e.message = message;
throw e;
}
});
_defineProperty(this, "_toGraphQL", () => {
// @ts-ignore
return CircularDeps.GraphQLParser.fieldToGraphQL({
field: this.__lazyGetter.field,
fieldName: this.id,
parentName: this.id,
path: ["Type_".concat(this.id)]
});
});
_defineProperty(this, "graphQLType", function () {
return _this._toGraphQL().type(...arguments);
});
_defineProperty(this, "graphQLInputType", function () {
return _this._toGraphQL().inputType(...arguments);
});
_defineProperty(this, "graphQLInterface", function () {
if (!_this.__lazyGetter.objectType) {
throw new Error('graphQLInterface is only available for object type');
}
// @ts-ignore
return CircularDeps.GraphQLParser.objectToGraphQL({
object: _this.__lazyGetter.objectType
}).interfaceType(...arguments);
});
_defineProperty(this, "beforeInitialize", []);
_defineProperty(this, "print", () => {
var type = this.graphQLType();
var inputType = this.graphQLInputType();
// @ts-ignore circular
var {
GraphQLSchema,
printSchema
} = CircularDeps.graphql;
var object = new GraphQLSchema({
// @ts-ignore
types: [type, inputType]
});
return printSchema(object).split('\n');
});
_defineProperty(this, "typescriptPrint", options => {
var name = (options === null || options === void 0 ? void 0 : options.name) || this.id;
// @ts-ignore
var object = this.__lazyGetter.objectType || createObjectType({
[name]: this.definition
});
// @ts-ignore circular
return CircularDeps.objectToTypescript(name, object, options);
});
_defineProperty(this, "optionalType", name => {
var _id = name || this.optionalId;
_id = _id ? "".concat(_id, "Optional") : undefined;
return this.override(it => it.optional()).graphType(_id);
});
_defineProperty(this, "requiredType", name => {
var _id = name || this.optionalId;
_id = _id ? "".concat(_id, "NotNull") : undefined;
return this.override(it => it.required()).graphType(_id);
});
_defineProperty(this, "listType", name => {
var _id = name || this.optionalId;
_id = _id ? "".concat(_id, "List") : undefined;
return this.override(it => it.list()).graphType(_id);
});
_defineProperty(this, "singleType", name => {
var _id = name || this.optionalId;
_id = _id ? "".concat(_id, "Item") : undefined;
return this.override(it => it.single()).graphType(_id);
});
for (var _len = arguments.length, _args = new Array(_len), _key = 0; _key < _len; _key++) {
_args[_key] = arguments[_key];
}
initGraphType(this, _args);
}
// used to lazy process input definition to improve circular dependency in types
touch() {
// just dispatch lazy loader getters
this.__lazyGetter.id;
return this;
}
set hidden(value) {
this.__lazyGetter.field.hidden = value;
this.__hidden = value;
}
get hidden() {
return this.__hidden;
}
clone(handler) {
var parsed = parseField(this.definition);
var input = extendObjectDefinition(parsed);
return handler(input);
}
override(handler) {
var input = extendType(this.definition);
return handler(input);
}
mutateFields(callback) {
if (this.touched) {
throw new Error("Called \"mutateFields\" after type \"".concat(this.optionalId || '', "\" was touched."));
}
if (this.optionalId) {
// ObjectType.register.remove(this.optionalId); // FIXME
}
this.beforeInitialize.push(payload => {
if (payload.definition.type !== 'object') {
throw new Error("mutateFields can only be used with object types.");
}
try {
var _input = extendObjectDefinition(payload.definition);
payload.definition.def = callback(_input);
payload.objectType = createObjectType({
[this.id]: this.definition
});
payload.field.utils.object = payload.objectType;
return payload;
} catch (e) {
e.message = "Failed to execute mutateFields with the result from callback: ".concat(inspectObject({
callback
}));
throw e;
}
});
return this;
}
static is(input) {
return (input === null || input === void 0 ? void 0 : input.__isGraphType) === true;
}
static isTypeDefinition(input) {
var _input$type;
return (input === null || input === void 0 ? void 0 : (_input$type = input.type) === null || _input$type === void 0 ? void 0 : _input$type.__isGraphType) === true;
}
}
_defineProperty(GraphType, "__isGraphType", true);
_defineProperty(GraphType, "register", createStore());
_defineProperty(GraphType, "resolvers", createStore());
_defineProperty(GraphType, "reset", /*#__PURE__*/_asyncToGenerator(function* () {
GraphType.resolvers.clear();
GraphType.register.clear();
}));
_defineProperty(GraphType, "getOrSet", (id, def) => {
var existing = GraphType.register.has(id) && GraphType.register.get(id);
if (existing) return existing;
return new GraphType(id, def);
});
export function createType() {
for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
args[_key2] = arguments[_key2];
}
return new GraphType(
// @ts-ignore
...args);
}
export function getType(name) {
return GraphType.register.get(name);
}
//# sourceMappingURL=GraphType.js.map