@nestjs/graphql
Version:
GraphQL for NestJS: code-first and schema-first APIs, resolvers as providers, subscriptions, federation and generated SDL, on Apollo or Mercurius.
57 lines (56 loc) • 2.19 kB
JavaScript
import { isUndefined } from '@nestjs/common/utils/shared.utils.js';
import { getEnumMemberKeys } from './get-enum-member-keys.helper.js';
/**
* Normalizes a `defaultValue` declared on an argument / input field whose
* type references a `registerEnumType`-registered enum.
*
* GraphQL serializes enum default values through the enum's internal value
* lookup (see `GraphQLEnumType#serialize`), so the library must pass the
* enum's internal VALUE (not its KEY) as `defaultValue`. When a user writes
* `defaultValue: 'BOOKS'` for `enum Category { BOOKS = 'books' }`, the
* produced SDL fails validation with
* `Enum "Category" cannot represent value: "BOOKS"`.
*
* This helper keeps the value untouched whenever it already matches a
* registered enum value, otherwise it checks whether the supplied string
* matches an enum KEY and translates it to the matching enum value so
* `astFromValue` can emit the correct SDL literal.
*
* See: https://github.com/nestjs/graphql/issues/3618
*/
export function normalizeEnumDefaultValue(defaultValue, typeRef, enumsMetadata) {
if (isUndefined(defaultValue) || defaultValue === null) {
return defaultValue;
}
if (!typeRef || !enumsMetadata?.length) {
return defaultValue;
}
const enumMetadata = enumsMetadata.find((item) => item.ref === typeRef);
if (!enumMetadata) {
return defaultValue;
}
const enumRef = enumMetadata.ref;
if (Array.isArray(defaultValue)) {
return defaultValue.map((item) => translateEnumValue(item, enumRef));
}
return translateEnumValue(defaultValue, enumRef);
}
function translateEnumValue(value, enumRef) {
if (typeof value !== 'string') {
return value;
}
const registeredValues = getEnumMemberValues(enumRef);
if (registeredValues.includes(value)) {
return value;
}
if (Object.prototype.hasOwnProperty.call(enumRef, value)) {
const translated = enumRef[value];
if (registeredValues.includes(translated)) {
return translated;
}
}
return value;
}
function getEnumMemberValues(enumRef) {
return getEnumMemberKeys(enumRef).map((key) => enumRef[key]);
}