UNPKG

@nestjs/graphql

Version:

Nest - modern, fast, powerful node.js web framework (@graphql)

65 lines (64 loc) 2.87 kB
import { __decorate } from "tslib"; import { Injectable } from '@nestjs/common'; import { isUndefined } from '@nestjs/common/utils/shared.utils.js'; import { GraphQLBoolean, GraphQLFloat, GraphQLInt, GraphQLList, GraphQLNonNull, GraphQLScalarType, GraphQLString, } from 'graphql'; import { GraphQLISODateTime, GraphQLTimestamp } from '../../scalars/index.js'; import { DefaultNullableConflictError } from '../errors/default-nullable-conflict.error.js'; import { InvalidNullableOptionError } from '../errors/invalid-nullable-option.error.js'; let TypeMapperService = class TypeMapperService { mapToScalarType(typeRef, scalarsMap = [], dateScalarMode = 'isoDate', numberScalarMode = 'float') { if (typeRef instanceof GraphQLScalarType) { return typeRef; } const scalarHost = scalarsMap.find((item) => item.type === typeRef); if (scalarHost) { return scalarHost.scalar; } const dateScalar = dateScalarMode === 'timestamp' ? GraphQLTimestamp : GraphQLISODateTime; const numberScalar = numberScalarMode === 'float' ? GraphQLFloat : GraphQLInt; const typeScalarMapping = new Map([ [String, GraphQLString], [Number, numberScalar], [Boolean, GraphQLBoolean], [Date, dateScalar], ]); return typeScalarMapping.get(typeRef); } mapToGqlType(hostType, typeRef, options) { this.validateTypeOptions(hostType, options); let graphqlType = typeRef; if (options.isArray) { graphqlType = this.mapToGqlList(graphqlType, options.arrayDepth, this.hasArrayOptions(options)); } const isNotNullable = !options.nullable || options.nullable === 'items'; return isNotNullable ? new GraphQLNonNull(graphqlType) : graphqlType; } validateTypeOptions(hostType, options) { if (!options.isArray && this.hasArrayOptions(options)) { throw new InvalidNullableOptionError(hostType, options.nullable); } const isNotNullable = options.nullable === 'items'; if (!isUndefined(options.defaultValue) && isNotNullable) { throw new DefaultNullableConflictError(hostType, options.defaultValue, options.nullable); } return true; } mapToGqlList(targetType, depth, nullable) { const targetTypeNonNull = nullable ? targetType : new GraphQLNonNull(targetType); if (depth === 0) { return targetType; } return this.mapToGqlList(new GraphQLList(targetTypeNonNull), depth - 1, nullable); } hasArrayOptions(options) { return options.nullable === 'items' || options.nullable === 'itemsAndList'; } }; TypeMapperService = __decorate([ Injectable() ], TypeMapperService); export { TypeMapperService };