Skip to content

Instantly share code, notes, and snippets.

@rluvaton
Created August 21, 2022 18:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rluvaton/ffd4697dc729303a2ae62914b33884f2 to your computer and use it in GitHub Desktop.
Save rluvaton/ffd4697dc729303a2ae62914b33884f2 to your computer and use it in GitHub Desktop.
EnumWithSwaggerSupport for TypeBox
import { SchemaOptions, TEnum, Type } from '@sinclair/typebox';
import { EnumValues } from 'enum-values';
function getEnumDescription(e: any, name?: string): string | undefined {
const enumValuesDesc = EnumValues.getNamesAndValues(e)
.map(({ name, value }) => `\`${value}\` - ${name}`)
.join('\n');
if (!name) {
return enumValuesDesc;
}
return `${name}:\n${enumValuesDesc}`;
}
export function EnumWithSwaggerSupport<T extends Record<string, string | number>, ValuesOfEnum extends T[]>(
e: T,
{
disableAutoDescription = false,
enumName,
...options
}: SchemaOptions & {
enumName?: string;
// null meaning no description
disableAutoDescription?: boolean;
}
): TEnum<T> {
const enumValues = EnumValues.getValues(e);
if (enumValues.length === 0) {
return Type.Enum(e);
}
// If enum contain number and string value types, fallback to regular enum
if (new Set([...enumValues.map(v => typeof v)]).size === 2) {
return Type.Enum(e);
}
return Type.Unsafe<ValuesOfEnum[number]>({
type: typeof enumValues[0],
enum: enumValues,
description:
typeof options.description === 'string' || disableAutoDescription
? options.description
: getEnumDescription(e, enumName),
...options,
}) as unknown as TEnum<T>;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment