Created
August 21, 2022 18:26
-
-
Save rluvaton/ffd4697dc729303a2ae62914b33884f2 to your computer and use it in GitHub Desktop.
EnumWithSwaggerSupport for TypeBox
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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