forked from goldcaddy77/warthog
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathStringField.ts
70 lines (60 loc) · 2.49 KB
/
StringField.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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
import { MaxLength, MinLength } from 'class-validator';
import { Field } from 'type-graphql';
import { Column } from 'typeorm';
import { FieldType, decoratorDefaults, getMetadataStorage } from '../metadata';
import { composeMethodDecorators, MethodDecoratorFactory } from '../utils';
import { StringColumnType } from '../torm';
interface StringFieldOptions {
dataType?: StringColumnType; // int16, jsonb, etc...
maxLength?: number;
minLength?: number;
filter?: boolean | FieldType;
nullable?: boolean;
sort?: boolean;
unique?: boolean;
editable?: boolean;
}
export function StringField(args: StringFieldOptions = decoratorDefaults): any {
const options = { ...decoratorDefaults, ...args };
const nullableOption = options.nullable === true ? { nullable: true } : {};
const maxLenOption = options.maxLength ? { length: options.maxLength } : {};
const uniqueOption = options.unique ? { unique: true } : {};
const registerWithWarthog = (target: object, propertyKey: string): any => {
// Sorry, I put in some magic that automatically identified columns that end in Id to be ID columns
// that only uses the ID filter (eq and in). This was silly. I've added a workaround here where you
// can explicitly state which filter you want to use. So if you have a field called userId and add filter: 'string'
// this will bypass the magic Id logic below
let fieldType: FieldType = 'string'; // default
const explicitType = typeof args.filter === 'string' ? args.filter : null;
if (explicitType) {
fieldType = explicitType;
}
// V2: remove the auto-ID logic. Need to keep this around as to not introduce a breaking change
else if (propertyKey.match(/Id$/)) {
fieldType = 'id';
}
getMetadataStorage().addField(fieldType, target.constructor.name, propertyKey, options);
};
// These are the 2 required decorators to get type-graphql and typeorm working
const factories = [
registerWithWarthog,
// We explicitly say string here because when we're metaprogramming without
// TS types, Field does not know that this should be a String
Field(() => String, {
...nullableOption
}),
Column({
type: args.dataType || 'varchar',
...maxLenOption,
...nullableOption,
...uniqueOption
}) as MethodDecoratorFactory
];
if (args.minLength) {
factories.push(MinLength(args.minLength));
}
if (args.maxLength) {
factories.push(MaxLength(args.maxLength));
}
return composeMethodDecorators(...factories);
}