graphql-composer
Version:
Create your GraphQL API using composition!
107 lines • 3.53 kB
JavaScript
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.InterfaceType = void 0;
const graphql_1 = require("graphql");
const __1 = require("../../../..");
const GQLObjectType_1 = require("./GQLObjectType");
class InterfaceType extends GQLObjectType_1.GQLObjectType {
constructor(name) {
super(name);
this._possibleTypes = [];
this.setTypeResolver(this.defaultTypeResolver.bind(this));
}
get definitionNode() {
return {
kind: "InterfaceTypeDefinition",
name: {
kind: "Name",
value: this.name,
},
description: {
kind: "StringValue",
value: this.description,
},
fields: this._fields.map((f) => f.definitionNode),
directives: this.directives.map((d) => d.definitionNode),
};
}
static create(nameOrType) {
if (typeof nameOrType === "string") {
return new InterfaceType(nameOrType);
}
else if (nameOrType instanceof __1.GQLType) {
const obj = InterfaceType.create(nameOrType.name)
.setExtensions(nameOrType.extensions)
.setDirectives(...nameOrType.directives)
.setDescription(nameOrType.description);
if (nameOrType instanceof __1.InputType) {
obj.setFields(...nameOrType.fields.map((f) => __1.Field.create(f)));
}
else if (nameOrType instanceof GQLObjectType_1.GQLObjectType) {
obj.setFields(...nameOrType.fields);
}
return obj;
}
else {
const t = InterfaceType.create(nameOrType.name);
t._classType = nameOrType;
return t;
}
}
build() {
const built = new graphql_1.GraphQLInterfaceType({
name: this.name,
description: this.description,
resolveType: this._typeResolver,
fields: () => this.getFields(),
extensions: this.extensions,
});
this._built = built;
return this._built;
}
/**
* Set the type of the field
* @param typeResolver the field resolver
*/
setTypeResolver(typeResolver) {
this._typeResolver = typeResolver;
return this;
}
/**
* Set the possible types of the interface to resolve the __typename
* @param possibleTypes The possible types
*/
setPossibleTypes(...possibleTypes) {
possibleTypes.map((pt) => {
if (this._possibleTypes.indexOf(pt) === -1) {
this._possibleTypes.push(pt);
}
});
return this;
}
/**
* Set the possible types of the interface to resolve the __typename
* @param possibleTypes The possible types
*/
addPossibleTypes(...possibleTypes) {
return this.setPossibleTypes(...this._possibleTypes, ...possibleTypes);
}
/**
* Add a suffix to the name of your type ("Interface" by default)
* @param suffix The suffix to add to the name
*/
suffix(suffix = "Interface") {
return this.setName(this.name + suffix);
}
copy() {
return InterfaceType.create(this);
}
convert(to) {
return to.create(this);
}
defaultTypeResolver(obj) {
return __1.TypeResolver.resolve(obj, this._possibleTypes);
}
}
exports.InterfaceType = InterfaceType;
//# sourceMappingURL=InterfaceType.js.map