@graphql-tools/graphql
Version:
Fork of GraphQL.js
840 lines (839 loc) • 27.5 kB
JavaScript
var _a, _b, _c, _d, _e, _f, _g, _h;
import { devAssert } from '../jsutils/devAssert.js';
import { didYouMean } from '../jsutils/didYouMean.js';
import { identityFunc } from '../jsutils/identityFunc.js';
import { inspect } from '../jsutils/inspect.js';
import { keyMap } from '../jsutils/keyMap.js';
import { keyValMap } from '../jsutils/keyValMap.js';
import { mapValue } from '../jsutils/mapValue.js';
import { suggestionList } from '../jsutils/suggestionList.js';
import { toObjMap } from '../jsutils/toObjMap.js';
import { GraphQLError } from '../error/GraphQLError.js';
import { Kind } from '../language/kinds.js';
import { print } from '../language/printer.js';
import { valueFromASTUntyped } from '../utilities/valueFromASTUntyped.js';
import { assertEnumValueName, assertName } from './assertName.js';
export function isType(type) {
return (isScalarType(type) ||
isObjectType(type) ||
isInterfaceType(type) ||
isUnionType(type) ||
isEnumType(type) ||
isInputObjectType(type) ||
isListType(type) ||
isNonNullType(type));
}
export function assertType(type) {
if (!isType(type)) {
throw new Error(`Expected ${inspect(type)} to be a GraphQL type.`);
}
return type;
}
const isGraphQLScalarTypeSymbol = Symbol.for('GraphQLScalarType');
/**
* There are predicates for each kind of GraphQL type.
*/
export function isScalarType(type) {
return typeof type === 'object' && type != null && isGraphQLScalarTypeSymbol in type;
}
export function assertScalarType(type) {
if (!isScalarType(type)) {
throw new Error(`Expected ${inspect(type)} to be a GraphQL Scalar type.`);
}
return type;
}
const isGraphQLObjectTypeSymbol = Symbol.for('GraphQLObjectType');
export function isObjectType(type) {
return typeof type === 'object' && type != null && isGraphQLObjectTypeSymbol in type;
}
export function assertObjectType(type) {
if (!isObjectType(type)) {
throw new Error(`Expected ${inspect(type)} to be a GraphQL Object type.`);
}
return type;
}
const isGraphQLInterfaceTypeSymbol = Symbol.for('GraphQLInterfaceType');
export function isInterfaceType(type) {
return typeof type === 'object' && type != null && isGraphQLInterfaceTypeSymbol in type;
}
export function assertInterfaceType(type) {
if (!isInterfaceType(type)) {
throw new Error(`Expected ${inspect(type)} to be a GraphQL Interface type.`);
}
return type;
}
const isGraphQLUnionTypeSymbol = Symbol.for('GraphQLUnionType');
export function isUnionType(type) {
return typeof type === 'object' && type != null && isGraphQLUnionTypeSymbol in type;
}
export function assertUnionType(type) {
if (!isUnionType(type)) {
throw new Error(`Expected ${inspect(type)} to be a GraphQL Union type.`);
}
return type;
}
const isGraphQLEnumTypeSymbol = Symbol.for('GraphQLEnumType');
export function isEnumType(type) {
return typeof type === 'object' && type != null && isGraphQLEnumTypeSymbol in type;
}
export function assertEnumType(type) {
if (!isEnumType(type)) {
throw new Error(`Expected ${inspect(type)} to be a GraphQL Enum type.`);
}
return type;
}
const isGraphQLInputObjectTypeSymbol = Symbol.for('GraphQLInputObjectType');
export function isInputObjectType(type) {
return typeof type === 'object' && type != null && isGraphQLInputObjectTypeSymbol in type;
}
export function assertInputObjectType(type) {
if (!isInputObjectType(type)) {
throw new Error(`Expected ${inspect(type)} to be a GraphQL Input Object type.`);
}
return type;
}
const isGraphQLListTypeSymbol = Symbol.for('GraphQLListType');
export function isListType(type) {
return typeof type === 'object' && type != null && isGraphQLListTypeSymbol in type;
}
export function assertListType(type) {
if (!isListType(type)) {
throw new Error(`Expected ${inspect(type)} to be a GraphQL List type.`);
}
return type;
}
const isGraphQLNonNullTypeSymbol = Symbol.for('GraphQLNonNullType');
export function isNonNullType(type) {
return typeof type === 'object' && type != null && isGraphQLNonNullTypeSymbol in type;
}
export function assertNonNullType(type) {
if (!isNonNullType(type)) {
throw new Error(`Expected ${inspect(type)} to be a GraphQL Non-Null type.`);
}
return type;
}
export function isInputType(type) {
return (isScalarType(type) ||
isEnumType(type) ||
isInputObjectType(type) ||
(isWrappingType(type) && isInputType(type.ofType)));
}
export function assertInputType(type) {
if (!isInputType(type)) {
throw new Error(`Expected ${inspect(type)} to be a GraphQL input type.`);
}
return type;
}
export function isOutputType(type) {
return (isScalarType(type) ||
isObjectType(type) ||
isInterfaceType(type) ||
isUnionType(type) ||
isEnumType(type) ||
(isWrappingType(type) && isOutputType(type.ofType)));
}
export function assertOutputType(type) {
if (!isOutputType(type)) {
throw new Error(`Expected ${inspect(type)} to be a GraphQL output type.`);
}
return type;
}
export function isLeafType(type) {
return isScalarType(type) || isEnumType(type);
}
export function assertLeafType(type) {
if (!isLeafType(type)) {
throw new Error(`Expected ${inspect(type)} to be a GraphQL leaf type.`);
}
return type;
}
export function isCompositeType(type) {
return isObjectType(type) || isInterfaceType(type) || isUnionType(type);
}
export function assertCompositeType(type) {
if (!isCompositeType(type)) {
throw new Error(`Expected ${inspect(type)} to be a GraphQL composite type.`);
}
return type;
}
export function isAbstractType(type) {
return isInterfaceType(type) || isUnionType(type);
}
export function assertAbstractType(type) {
if (!isAbstractType(type)) {
throw new Error(`Expected ${inspect(type)} to be a GraphQL abstract type.`);
}
return type;
}
/**
* List Type Wrapper
*
* A list is a wrapping type which points to another type.
* Lists are often created within the context of defining the fields of
* an object type.
*
* Example:
*
* ```ts
* const PersonType = new GraphQLObjectType({
* name: 'Person',
* fields: () => ({
* parents: { type: new GraphQLList(PersonType) },
* children: { type: new GraphQLList(PersonType) },
* })
* })
* ```
*/
export class GraphQLList {
constructor(ofType) {
this[_a] = true;
this.ofType = ofType;
}
get [(_a = isGraphQLListTypeSymbol, Symbol.toStringTag)]() {
return 'GraphQLList';
}
toString() {
return '[' + String(this.ofType) + ']';
}
toJSON() {
return this.toString();
}
}
/**
* Non-Null Type Wrapper
*
* A non-null is a wrapping type which points to another type.
* Non-null types enforce that their values are never null and can ensure
* an error is raised if this ever occurs during a request. It is useful for
* fields which you can make a strong guarantee on non-nullability, for example
* usually the id field of a database row will never be null.
*
* Example:
*
* ```ts
* const RowType = new GraphQLObjectType({
* name: 'Row',
* fields: () => ({
* id: { type: new GraphQLNonNull(GraphQLString) },
* })
* })
* ```
* Note: the enforcement of non-nullability occurs within the executor.
*/
export class GraphQLNonNull {
constructor(ofType) {
this[_b] = true;
this.ofType = ofType;
}
get [(_b = isGraphQLNonNullTypeSymbol, Symbol.toStringTag)]() {
return 'GraphQLNonNull';
}
toString() {
return String(this.ofType) + '!';
}
toJSON() {
return this.toString();
}
}
export function isWrappingType(type) {
return isListType(type) || isNonNullType(type);
}
export function assertWrappingType(type) {
if (!isWrappingType(type)) {
throw new Error(`Expected ${inspect(type)} to be a GraphQL wrapping type.`);
}
return type;
}
export function isNullableType(type) {
return isType(type) && !isNonNullType(type);
}
export function assertNullableType(type) {
if (!isNullableType(type)) {
throw new Error(`Expected ${inspect(type)} to be a GraphQL nullable type.`);
}
return type;
}
export function getNullableType(type) {
if (type) {
return isNonNullType(type) ? type.ofType : type;
}
return undefined;
}
export function isNamedType(type) {
return (isScalarType(type) ||
isObjectType(type) ||
isInterfaceType(type) ||
isUnionType(type) ||
isEnumType(type) ||
isInputObjectType(type));
}
export function assertNamedType(type) {
if (!isNamedType(type)) {
throw new Error(`Expected ${inspect(type)} to be a GraphQL named type.`);
}
return type;
}
export function getNamedType(type) {
if (type) {
let unwrappedType = type;
while (isWrappingType(unwrappedType)) {
unwrappedType = unwrappedType.ofType;
}
return unwrappedType;
}
return undefined;
}
export function resolveReadonlyArrayThunk(thunk) {
return typeof thunk === 'function' ? thunk() : thunk;
}
export function resolveObjMapThunk(thunk) {
return typeof thunk === 'function' ? thunk() : thunk;
}
/**
* Scalar Type Definition
*
* The leaf values of any request and input values to arguments are
* Scalars (or Enums) and are defined with a name and a series of functions
* used to parse input from ast or variables and to ensure validity.
*
* If a type's serialize function returns `null` or does not return a value
* (i.e. it returns `undefined`) then an error will be raised and a `null`
* value will be returned in the response. It is always better to validate
*
* Example:
*
* ```ts
* const OddType = new GraphQLScalarType({
* name: 'Odd',
* serialize(value) {
* if (!Number.isFinite(value)) {
* throw new Error(
* `Scalar "Odd" cannot represent "${value}" since it is not a finite number.`,
* );
* }
*
* if (value % 2 === 0) {
* throw new Error(`Scalar "Odd" cannot represent "${value}" since it is even.`);
* }
* return value;
* }
* });
* ```
*/
export class GraphQLScalarType {
constructor(config) {
var _j, _k, _l, _m;
this[_c] = true;
const parseValue = (_j = config.parseValue) !== null && _j !== void 0 ? _j : identityFunc;
this.name = assertName(config.name);
this.description = config.description;
this.specifiedByURL = config.specifiedByURL;
this.serialize = (_k = config.serialize) !== null && _k !== void 0 ? _k : identityFunc;
this.parseValue = parseValue;
this.parseLiteral = (_l = config.parseLiteral) !== null && _l !== void 0 ? _l : ((node, variables) => parseValue(valueFromASTUntyped(node, variables)));
this.extensions = toObjMap(config.extensions);
this.astNode = config.astNode;
this.extensionASTNodes = (_m = config.extensionASTNodes) !== null && _m !== void 0 ? _m : [];
if (config.parseLiteral) {
devAssert(typeof config.parseValue === 'function' && typeof config.parseLiteral === 'function', `${this.name} must provide both "parseValue" and "parseLiteral" functions.`);
}
}
get [(_c = isGraphQLScalarTypeSymbol, Symbol.toStringTag)]() {
return 'GraphQLScalarType';
}
toConfig() {
return {
name: this.name,
description: this.description,
specifiedByURL: this.specifiedByURL,
serialize: this.serialize,
parseValue: this.parseValue,
parseLiteral: this.parseLiteral,
extensions: this.extensions,
astNode: this.astNode,
extensionASTNodes: this.extensionASTNodes,
};
}
toString() {
return this.name;
}
toJSON() {
return this.toString();
}
}
/**
* Object Type Definition
*
* Almost all of the GraphQL types you define will be object types. Object types
* have a name, but most importantly describe their fields.
*
* Example:
*
* ```ts
* const AddressType = new GraphQLObjectType({
* name: 'Address',
* fields: {
* street: { type: GraphQLString },
* number: { type: GraphQLInt },
* formatted: {
* type: GraphQLString,
* resolve(obj) {
* return obj.number + ' ' + obj.street
* }
* }
* }
* });
* ```
*
* When two types need to refer to each other, or a type needs to refer to
* itself in a field, you can use a function expression (aka a closure or a
* thunk) to supply the fields lazily.
*
* Example:
*
* ```ts
* const PersonType = new GraphQLObjectType({
* name: 'Person',
* fields: () => ({
* name: { type: GraphQLString },
* bestFriend: { type: PersonType },
* })
* });
* ```
*/
export class GraphQLObjectType {
constructor(config) {
var _j;
this[_d] = true;
this.name = assertName(config.name);
this.description = config.description;
this.isTypeOf = config.isTypeOf;
this.extensions = toObjMap(config.extensions);
this.astNode = config.astNode;
this.extensionASTNodes = (_j = config.extensionASTNodes) !== null && _j !== void 0 ? _j : [];
this._fields = () => defineFieldMap(config);
this._interfaces = () => defineInterfaces(config);
}
get [(_d = isGraphQLObjectTypeSymbol, Symbol.toStringTag)]() {
return 'GraphQLObjectType';
}
getFields() {
if (typeof this._fields === 'function') {
this._fields = this._fields();
}
return this._fields;
}
getInterfaces() {
if (typeof this._interfaces === 'function') {
this._interfaces = this._interfaces();
}
return this._interfaces;
}
toConfig() {
return {
name: this.name,
description: this.description,
interfaces: this.getInterfaces(),
fields: fieldsToFieldsConfig(this.getFields()),
isTypeOf: this.isTypeOf,
extensions: this.extensions,
astNode: this.astNode,
extensionASTNodes: this.extensionASTNodes,
};
}
toString() {
return this.name;
}
toJSON() {
return this.toString();
}
}
function defineInterfaces(config) {
var _j;
return resolveReadonlyArrayThunk((_j = config.interfaces) !== null && _j !== void 0 ? _j : []);
}
function defineFieldMap(config) {
const fieldMap = resolveObjMapThunk(config.fields);
return mapValue(fieldMap, (fieldConfig, fieldName) => {
var _j;
const argsConfig = (_j = fieldConfig.args) !== null && _j !== void 0 ? _j : {};
return {
name: assertName(fieldName),
description: fieldConfig.description,
type: fieldConfig.type,
args: defineArguments(argsConfig),
resolve: fieldConfig.resolve,
subscribe: fieldConfig.subscribe,
deprecationReason: fieldConfig.deprecationReason,
extensions: toObjMap(fieldConfig.extensions),
astNode: fieldConfig.astNode,
};
});
}
export function defineArguments(config) {
return Object.entries(config).map(([argName, argConfig]) => ({
name: assertName(argName),
description: argConfig.description,
type: argConfig.type,
defaultValue: argConfig.defaultValue,
deprecationReason: argConfig.deprecationReason,
extensions: toObjMap(argConfig.extensions),
astNode: argConfig.astNode,
}));
}
function fieldsToFieldsConfig(fields) {
return mapValue(fields, field => ({
description: field.description,
type: field.type,
args: argsToArgsConfig(field.args),
resolve: field.resolve,
subscribe: field.subscribe,
deprecationReason: field.deprecationReason,
extensions: field.extensions,
astNode: field.astNode,
}));
}
/**
* @internal
*/
export function argsToArgsConfig(args) {
return keyValMap(args, arg => arg.name, arg => ({
description: arg.description,
type: arg.type,
defaultValue: arg.defaultValue,
deprecationReason: arg.deprecationReason,
extensions: arg.extensions,
astNode: arg.astNode,
}));
}
export function isRequiredArgument(arg) {
return isNonNullType(arg.type) && arg.defaultValue === undefined;
}
/**
* Interface Type Definition
*
* When a field can return one of a heterogeneous set of types, a Interface type
* is used to describe what types are possible, what fields are in common across
* all types, as well as a function to determine which type is actually used
* when the field is resolved.
*
* Example:
*
* ```ts
* const EntityType = new GraphQLInterfaceType({
* name: 'Entity',
* fields: {
* name: { type: GraphQLString }
* }
* });
* ```
*/
export class GraphQLInterfaceType {
constructor(config) {
var _j;
this[_e] = true;
this.name = assertName(config.name);
this.description = config.description;
this.resolveType = config.resolveType;
this.extensions = toObjMap(config.extensions);
this.astNode = config.astNode;
this.extensionASTNodes = (_j = config.extensionASTNodes) !== null && _j !== void 0 ? _j : [];
this._fields = defineFieldMap.bind(undefined, config);
this._interfaces = defineInterfaces.bind(undefined, config);
}
get [(_e = isGraphQLInterfaceTypeSymbol, Symbol.toStringTag)]() {
return 'GraphQLInterfaceType';
}
getFields() {
if (typeof this._fields === 'function') {
this._fields = this._fields();
}
return this._fields;
}
getInterfaces() {
if (typeof this._interfaces === 'function') {
this._interfaces = this._interfaces();
}
return this._interfaces;
}
toConfig() {
return {
name: this.name,
description: this.description,
interfaces: this.getInterfaces(),
fields: fieldsToFieldsConfig(this.getFields()),
resolveType: this.resolveType,
extensions: this.extensions,
astNode: this.astNode,
extensionASTNodes: this.extensionASTNodes,
};
}
toString() {
return this.name;
}
toJSON() {
return this.toString();
}
}
/**
* Union Type Definition
*
* When a field can return one of a heterogeneous set of types, a Union type
* is used to describe what types are possible as well as providing a function
* to determine which type is actually used when the field is resolved.
*
* Example:
*
* ```ts
* const PetType = new GraphQLUnionType({
* name: 'Pet',
* types: [ DogType, CatType ],
* resolveType(value) {
* if (value instanceof Dog) {
* return DogType;
* }
* if (value instanceof Cat) {
* return CatType;
* }
* }
* });
* ```
*/
export class GraphQLUnionType {
constructor(config) {
var _j;
this[_f] = true;
this.name = assertName(config.name);
this.description = config.description;
this.resolveType = config.resolveType;
this.extensions = toObjMap(config.extensions);
this.astNode = config.astNode;
this.extensionASTNodes = (_j = config.extensionASTNodes) !== null && _j !== void 0 ? _j : [];
this._types = defineTypes.bind(undefined, config);
}
get [(_f = isGraphQLUnionTypeSymbol, Symbol.toStringTag)]() {
return 'GraphQLUnionType';
}
getTypes() {
if (typeof this._types === 'function') {
this._types = this._types();
}
return this._types;
}
toConfig() {
return {
name: this.name,
description: this.description,
types: this.getTypes(),
resolveType: this.resolveType,
extensions: this.extensions,
astNode: this.astNode,
extensionASTNodes: this.extensionASTNodes,
};
}
toString() {
return this.name;
}
toJSON() {
return this.toString();
}
}
function defineTypes(config) {
return resolveReadonlyArrayThunk(config.types);
}
/**
* Enum Type Definition
*
* Some leaf values of requests and input values are Enums. GraphQL serializes
* Enum values as strings, however internally Enums can be represented by any
* kind of type, often integers.
*
* Example:
*
* ```ts
* const RGBType = new GraphQLEnumType({
* name: 'RGB',
* values: {
* RED: { value: 0 },
* GREEN: { value: 1 },
* BLUE: { value: 2 }
* }
* });
* ```
*
* Note: If a value is not provided in a definition, the name of the enum value
* will be used as its internal value.
*/
export class GraphQLEnumType /* <T> */ {
constructor(config) {
var _j;
this[_g] = true;
this.name = assertName(config.name);
this.description = config.description;
this.extensions = toObjMap(config.extensions);
this.astNode = config.astNode;
this.extensionASTNodes = (_j = config.extensionASTNodes) !== null && _j !== void 0 ? _j : [];
this._values = Object.entries(config.values).map(([valueName, valueConfig]) => ({
name: assertEnumValueName(valueName),
description: valueConfig.description,
value: valueConfig.value !== undefined ? valueConfig.value : valueName,
deprecationReason: valueConfig.deprecationReason,
extensions: toObjMap(valueConfig.extensions),
astNode: valueConfig.astNode,
}));
this._valueLookup = new Map(this._values.map(enumValue => [enumValue.value, enumValue]));
this._nameLookup = keyMap(this._values, value => value.name);
}
get [(_g = isGraphQLEnumTypeSymbol, Symbol.toStringTag)]() {
return 'GraphQLEnumType';
}
getValues() {
return this._values;
}
getValue(name) {
return this._nameLookup[name];
}
serialize(outputValue /* T */) {
const enumValue = this._valueLookup.get(outputValue);
if (enumValue === undefined) {
throw new GraphQLError(`Enum "${this.name}" cannot represent value: ${inspect(outputValue)}`);
}
return enumValue.name;
}
parseValue(inputValue) {
if (typeof inputValue !== 'string') {
const valueStr = inspect(inputValue);
throw new GraphQLError(`Enum "${this.name}" cannot represent non-string value: ${valueStr}.` + didYouMeanEnumValue(this, valueStr));
}
const enumValue = this.getValue(inputValue);
if (enumValue == null) {
throw new GraphQLError(`Value "${inputValue}" does not exist in "${this.name}" enum.` + didYouMeanEnumValue(this, inputValue));
}
return enumValue.value;
}
parseLiteral(valueNode, _variables) {
// Note: variables will be resolved to a value before calling this function.
if (valueNode.kind !== Kind.ENUM) {
const valueStr = print(valueNode);
throw new GraphQLError(`Enum "${this.name}" cannot represent non-enum value: ${valueStr}.` + didYouMeanEnumValue(this, valueStr), { nodes: valueNode });
}
const enumValue = this.getValue(valueNode.value);
if (enumValue == null) {
const valueStr = print(valueNode);
throw new GraphQLError(`Value "${valueStr}" does not exist in "${this.name}" enum.` + didYouMeanEnumValue(this, valueStr), { nodes: valueNode });
}
return enumValue.value;
}
toConfig() {
const values = keyValMap(this.getValues(), value => value.name, value => ({
description: value.description,
value: value.value,
deprecationReason: value.deprecationReason,
extensions: value.extensions,
astNode: value.astNode,
}));
return {
name: this.name,
description: this.description,
values,
extensions: this.extensions,
astNode: this.astNode,
extensionASTNodes: this.extensionASTNodes,
};
}
toString() {
return this.name;
}
toJSON() {
return this.toString();
}
}
function didYouMeanEnumValue(enumType, unknownValueStr) {
const allNames = enumType.getValues().map(value => value.name);
const suggestedValues = suggestionList(unknownValueStr, allNames);
return didYouMean('the enum value', suggestedValues);
}
/**
* Input Object Type Definition
*
* An input object defines a structured collection of fields which may be
* supplied to a field argument.
*
* Using `NonNull` will ensure that a value must be provided by the query
*
* Example:
*
* ```ts
* const GeoPoint = new GraphQLInputObjectType({
* name: 'GeoPoint',
* fields: {
* lat: { type: new GraphQLNonNull(GraphQLFloat) },
* lon: { type: new GraphQLNonNull(GraphQLFloat) },
* alt: { type: GraphQLFloat, defaultValue: 0 },
* }
* });
* ```
*/
export class GraphQLInputObjectType {
constructor(config) {
var _j;
this[_h] = true;
this.name = assertName(config.name);
this.description = config.description;
this.extensions = toObjMap(config.extensions);
this.astNode = config.astNode;
this.extensionASTNodes = (_j = config.extensionASTNodes) !== null && _j !== void 0 ? _j : [];
this._fields = defineInputFieldMap.bind(undefined, config);
}
get [(_h = isGraphQLInputObjectTypeSymbol, Symbol.toStringTag)]() {
return 'GraphQLInputObjectType';
}
getFields() {
if (typeof this._fields === 'function') {
this._fields = this._fields();
}
return this._fields;
}
toConfig() {
const fields = mapValue(this.getFields(), field => ({
description: field.description,
type: field.type,
defaultValue: field.defaultValue,
deprecationReason: field.deprecationReason,
extensions: field.extensions,
astNode: field.astNode,
}));
return {
name: this.name,
description: this.description,
fields,
extensions: this.extensions,
astNode: this.astNode,
extensionASTNodes: this.extensionASTNodes,
};
}
toString() {
return this.name;
}
toJSON() {
return this.toString();
}
}
function defineInputFieldMap(config) {
const fieldMap = resolveObjMapThunk(config.fields);
return mapValue(fieldMap, (fieldConfig, fieldName) => {
devAssert(!('resolve' in fieldConfig), `${config.name}.${fieldName} field has a resolve property, but Input Types cannot define resolvers.`);
return {
name: assertName(fieldName),
description: fieldConfig.description,
type: fieldConfig.type,
defaultValue: fieldConfig.defaultValue,
deprecationReason: fieldConfig.deprecationReason,
extensions: toObjMap(fieldConfig.extensions),
astNode: fieldConfig.astNode,
};
});
}
export function isRequiredInputField(field) {
return isNonNullType(field.type) && field.defaultValue === undefined;
}