Skip to content

Commit

Permalink
Work around not having the default empty object value from TS constru…
Browse files Browse the repository at this point in the history
…ctor anymore
  • Loading branch information
CarsonF committed Dec 20, 2022
1 parent d50f080 commit 8ef713f
Show file tree
Hide file tree
Showing 3 changed files with 23 additions and 3 deletions.
17 changes: 17 additions & 0 deletions src/common/default-value.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
const get = (type: any) => Reflect.getMetadata(key, type) ?? {};

const set =
(value: any): PropertyDecorator =>
({ constructor: type }, propertyKey) =>
Reflect.defineMetadata(key, { ...get(type), [propertyKey]: value }, type);

/**
* A helper to get/set default values for classes.
* Usage of this is discouraged in favor or more common practices.
* This is mostly useful with abstractions.
* Note that the defaults aren't automatically applied, this just holds
* a container for them - They need to be fetched explicitly.
*/
export const DefaultValue = { Get: get, Set: set };

const key = 'DefaultValue';
6 changes: 4 additions & 2 deletions src/common/filter-field.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ 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';

/**
Expand All @@ -23,10 +24,11 @@ export const FilterField = <T extends object>(
: [
Field(() => type, {
nullable: true,
defaultValue: {},
defaultValue: {}, // Only for GQL schema & not always applied in TS
}),
]),
Type(() => type),
ValidateNested(),
Transform(({ value }) => value || {})
DefaultValue.Set({}), // Default when omitted
Transform(({ value }) => value || {}) // null -> {}
);
3 changes: 2 additions & 1 deletion src/common/pagination.input.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { Args, ArgsOptions, Field, InputType, Int } from '@nestjs/graphql';
import { Matches, Max, Min } from 'class-validator';
import { stripIndent } from 'common-tags';
import { DataObject } from './data-object';
import { DefaultValue } from './default-value';
import { Order } from './order.enum';
import { AbstractClassType } from './types';

Expand Down Expand Up @@ -106,7 +107,7 @@ export const ListArg = <T extends PaginationInput>(
name: 'input',
type: () => input,
nullable: true,
defaultValue: DataObject.defaultValue(input),
defaultValue: DataObject.defaultValue(input, DefaultValue.Get(input)),
...opts,
},
...pipes
Expand Down

0 comments on commit 8ef713f

Please sign in to comment.