-
Notifications
You must be signed in to change notification settings - Fork 4
/
filter-field.ts
34 lines (33 loc) · 1.05 KB
/
filter-field.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
import { applyDecorators } from '@nestjs/common';
import { Field } from '@nestjs/graphql';
import { Transform, Type } from 'class-transformer';
import { ValidateNested } from 'class-validator';
import { HasRequiredKeys } from 'type-fest';
import { DefaultValue } from './default-value';
import { AbstractClassType } from './types';
/**
* A field that is a filter object probably for input on a list query.
*/
export const FilterField = <T extends object>(
type: HasRequiredKeys<T> extends true ? never : AbstractClassType<T>,
options?: {
/**
* There are no external fields on the filter, so don't expose to GQL.
*/
internal?: boolean;
}
): PropertyDecorator =>
applyDecorators(
...(options?.internal
? []
: [
Field(() => type, {
nullable: true,
defaultValue: {}, // Only for GQL schema & not always applied in TS
}),
]),
Type(() => type),
ValidateNested(),
DefaultValue.Set({}), // Default when omitted
Transform(({ value }) => value || {}) // null -> {}
);