UNPKG

@graphql-tools/utils

Version:

Common package containing utils and types for GraphQL tools

58 lines (57 loc) • 1.81 kB
import { GraphQLInputObjectType, GraphQLInterfaceType, GraphQLList, GraphQLNonNull, GraphQLObjectType, GraphQLString, Kind, specifiedScalarTypes, } from 'graphql'; export function createNamedStub(name, type) { let constructor; if (type === 'object') { constructor = GraphQLObjectType; } else if (type === 'interface') { constructor = GraphQLInterfaceType; } else { constructor = GraphQLInputObjectType; } return new constructor({ name, fields: { _fake: { type: GraphQLString, }, }, }); } function getSpecifiedScalar(name) { return specifiedScalarTypes.find(type => type.name === name); } export function createStub(node, type) { switch (node.kind) { case Kind.LIST_TYPE: return new GraphQLList(createStub(node.type, type)); case Kind.NON_NULL_TYPE: // FIXME: graphql@17 type issue return new GraphQLNonNull(createStub(node.type, type)); default: { const specified = getSpecifiedScalar(node.name.value); if (specified) { return specified; } if (type === 'output') { return createNamedStub(node.name.value, 'object'); } return createNamedStub(node.name.value, 'input'); } } } export function isNamedStub(type) { if ('getFields' in type) { const fields = type.getFields(); // eslint-disable-next-line no-unreachable-loop for (const fieldName in fields) { const field = fields[fieldName]; return field.name === '_fake'; } } return false; } export function getBuiltInForStub(type) { return getSpecifiedScalar(type.name) ?? type; }