-
Notifications
You must be signed in to change notification settings - Fork 38
/
EnumField.ts
44 lines (36 loc) · 1.55 KB
/
EnumField.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
const caller = require('caller'); // eslint-disable-line @typescript-eslint/no-var-requires
import * as path from 'path';
import { Field, registerEnumType } from 'type-graphql';
import { Column } from 'typeorm';
import { getMetadataStorage, DecoratorCommonOptions } from '../metadata';
import { composeMethodDecorators, generatedFolderPath, MethodDecoratorFactory } from '../utils';
import { EnumWhereOperator } from '../torm';
interface EnumFieldOptions extends DecoratorCommonOptions {
default?: any;
filter?: boolean | EnumWhereOperator[];
}
export function EnumField(name: string, enumeration: object, options: EnumFieldOptions = {}): any {
// Register enum with TypeGraphQL so that it lands in generated schema
registerEnumType(enumeration, { name });
// In order to use the enums in the generated classes file, we need to
// save their locations and import them in the generated file
const decoratorSourceFile = caller();
// Use relative paths in the source files so that they can be used on different machines
const relativeFilePath = path.relative(generatedFolderPath(), decoratorSourceFile);
const registerWithWarthog = (target: object, propertyKey: string): any => {
getMetadataStorage().addEnum(
target.constructor.name,
propertyKey,
name,
enumeration,
relativeFilePath,
options
);
};
const factories = [
registerWithWarthog,
Field(() => enumeration, options),
Column({ enum: enumeration, ...options }) as MethodDecoratorFactory
];
return composeMethodDecorators(...factories);
}