Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(query-graphql): add type helpers #1427

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
74,582 changes: 51,020 additions & 23,562 deletions package-lock.json

Large diffs are not rendered by default.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -38,8 +38,8 @@
"eslint-plugin-tsdoc": "0.2.14",
"husky": "7.0.4",
"jest": "27.3.1",
"jest-snapshot-serializer-raw": "1.2.0",
"jest-extended": "0.11.5",
"jest-snapshot-serializer-raw": "1.2.0",
"lerna": "4.0.0",
"prettier": "2.4.1",
"ts-jest": "27.0.7",
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
import { Directive, Extensions, Field, ObjectType } from '@nestjs/graphql';
import { getFieldsAndDecoratorForType } from '@nestjs/graphql/dist/schema-builder/utils/get-fields-and-decorator.util';
import { FilterableField, IntersectionType } from '../../src';
import { METADATA_FACTORY_NAME } from '@nestjs/graphql/dist/plugin/plugin-constants';
import { getFilterableFields } from '../../src/decorators';

describe('IntersectionType', () => {
@ObjectType()
class ClassA {
@Field({ nullable: true })
@Directive('@upper')
@Extensions({ extension: true })
login!: string;

@FilterableField()
password!: string;
}

@ObjectType()
class ClassB {
@FilterableField()
@Directive('@upper')
@Extensions({ extension: true })
lastName!: string;

firstName?: string;

static [METADATA_FACTORY_NAME]() {
return {
firstName: { nullable: true, type: () => String },
};
}
}

class UpdateUserDto extends IntersectionType(ClassA, ClassB) {}

it('should inherit all fields from two types', () => {
const prototype = Object.getPrototypeOf(UpdateUserDto);
const { fields } = getFieldsAndDecoratorForType(prototype);
const filterableFields = getFilterableFields(UpdateUserDto);
expect(filterableFields).toHaveLength(2);
expect(filterableFields[0].propertyName).toEqual('password');
expect(filterableFields[1].propertyName).toEqual('lastName');
expect(fields).toHaveLength(4);
expect(fields[0].name).toEqual('login');
expect(fields[1].name).toEqual('password');
expect(fields[2].name).toEqual('lastName');
expect(fields[3].name).toEqual('firstName');
expect(fields[0].directives?.length).toEqual(1);
expect(fields[0].directives).toContainEqual({
fieldName: 'login',
sdl: '@upper',
target: prototype,
});
expect(fields[0].extensions).toEqual({
extension: true,
});
expect(fields[2].directives?.length).toEqual(1);
expect(fields[2].directives).toContainEqual({
fieldName: 'lastName',
sdl: '@upper',
target: prototype,
});
expect(fields[2].extensions).toEqual({
extension: true,
});
});
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
import { Transform } from 'class-transformer';
import { MinLength } from 'class-validator';
import { Directive, Extensions, Field, ObjectType } from '@nestjs/graphql';
import { getFieldsAndDecoratorForType } from '@nestjs/graphql/dist/schema-builder/utils/get-fields-and-decorator.util';
import { FilterableField, OmitType } from '../../src';
import { getFilterableFields } from '../../src/decorators';

describe('OmitType', () => {
@ObjectType()
class CreateUserDto {
@MinLength(10)
@FilterableField({ nullable: true })
login!: string;

@Transform((str) => `${str.key}_transformed`)
@MinLength(10)
@FilterableField({ nullable: true })
@Directive('@upper')
@Extensions({ extension: true })
password!: string;

@Field({ name: 'id' })
_id!: string;
}

class UpdateUserDto extends OmitType(CreateUserDto, ['login', '_id']) {}

it('should inherit all fields except for "login" and "_id"', () => {
const prototype = Object.getPrototypeOf(UpdateUserDto);
const { fields } = getFieldsAndDecoratorForType(prototype);
const filterableFields = getFilterableFields(UpdateUserDto);
expect(filterableFields).toHaveLength(1);
expect(filterableFields[0].propertyName).toEqual('password');
expect(filterableFields[0].advancedOptions).toMatchObject({ nullable: true });
expect(fields).toHaveLength(1);
expect(fields[0].name).toEqual('password');
expect(fields[0].directives?.length).toEqual(1);
expect(fields[0].directives).toContainEqual({
fieldName: 'password',
sdl: '@upper',
target: prototype,
});
expect(fields[0].extensions).toEqual({
extension: true,
});
});
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
import { Expose, Transform } from 'class-transformer';
import { IsString } from 'class-validator';
import { Directive, Extensions, Field, ObjectType } from '@nestjs/graphql';
import { getFieldsAndDecoratorForType } from '@nestjs/graphql/dist/schema-builder/utils/get-fields-and-decorator.util';
import { FilterableField, PartialType } from '../../src';
import { getFilterableFields } from '../../src/decorators';

describe('PartialType', () => {
@ObjectType({ isAbstract: true })
abstract class BaseType {
@FilterableField()
@Directive('@upper')
@Extensions({ extension: true })
id!: string;

@Field()
createdAt!: Date;

@FilterableField()
updatedAt!: Date;
}

@ObjectType()
class CreateUserDto extends BaseType {
@FilterableField({ nullable: true })
login!: string;

@Expose()
@Transform((str) => `${str.key}_transformed`)
@IsString()
@Field()
password!: string;
}

class UpdateUserDto extends PartialType(CreateUserDto) {}

it('should inherit all fields and set "nullable" to true', () => {
const prototype = Object.getPrototypeOf(UpdateUserDto);
const { fields } = getFieldsAndDecoratorForType(prototype);
const filterableFields = getFilterableFields(UpdateUserDto);
expect(filterableFields).toHaveLength(3);
expect(filterableFields).toEqual(
expect.arrayContaining([
expect.objectContaining({
propertyName: 'id',
advancedOptions: { nullable: true },
}),
expect.objectContaining({
propertyName: 'updatedAt',
advancedOptions: { nullable: true },
}),
expect.objectContaining({
propertyName: 'login',
advancedOptions: { nullable: true },
}),
]),
);
expect(fields).toHaveLength(5);
expect(fields).toEqual(
expect.arrayContaining([
expect.objectContaining({
name: 'id',
options: { nullable: true },
}),
expect.objectContaining({
name: 'createdAt',
options: { nullable: true },
}),
expect.objectContaining({
name: 'updatedAt',
options: { nullable: true },
}),
expect.objectContaining({
name: 'login',
options: { nullable: true },
}),
expect.objectContaining({
name: 'password',
options: { nullable: true },
}),
]),
);
expect(fields[0].directives?.length).toEqual(1);
expect(fields[0].directives).toContainEqual({
fieldName: 'id',
sdl: '@upper',
target: prototype,
});
expect(fields[0].extensions).toEqual({
extension: true,
});
});
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
import { Transform } from 'class-transformer';
import { MinLength } from 'class-validator';
import { GraphQLString } from 'graphql';
import { ArgsType, Directive, Extensions, Field, ObjectType } from '@nestjs/graphql';
import { getFieldsAndDecoratorForType } from '@nestjs/graphql/dist/schema-builder/utils/get-fields-and-decorator.util';
import { FilterableField, PickType } from '../../src';
import { getFilterableFields } from '../../src/decorators';

describe('PickType', () => {
@ObjectType()
class CreateUserDto {
@Transform((str) => `${str.key}_transformed`)
@MinLength(10)
@Field({ nullable: true })
@Directive('@upper')
login!: string;

@MinLength(10)
@Field()
password!: string;

@Field({ name: 'id' })
@Extensions({ extension: true })
_id!: string;
}

class UpdateUserDto extends PickType(CreateUserDto, ['login']) {}

class UpdateUserWithIdDto extends PickType(CreateUserDto, ['_id']) {}

it('should inherit "login" field', () => {
const prototype = Object.getPrototypeOf(UpdateUserDto);
const { fields } = getFieldsAndDecoratorForType(prototype);
expect(fields).toHaveLength(1);
expect(fields[0].name).toEqual('login');
expect(fields[0].directives?.length).toEqual(1);
expect(fields[0].directives).toContainEqual({
fieldName: 'login',
sdl: '@upper',
target: prototype,
});
});

it('should inherit renamed "_id" field', () => {
const { fields } = getFieldsAndDecoratorForType(Object.getPrototypeOf(UpdateUserWithIdDto));
expect(fields).toHaveLength(1);
expect(fields[0].name).toEqual('_id');
expect(fields[0].extensions).toEqual({ extension: true });
});

@ArgsType()
class ArgsType1 {
@Field() a!: string;

@FilterableField() b!: string;

@Field() c!: string;

@FilterableField() d!: string;

@Field() e!: string;

@FilterableField() f!: string;

@Field(() => GraphQLString) g!: string;

@Field() h!: string;
}

@ObjectType()
class PickArgsTest1 extends PickType(ArgsType1, ['a', 'c', 'f', 'g', 'h']) {}

it('should inherit: a, c, f, g, h fields', () => {
const { fields } = getFieldsAndDecoratorForType(Object.getPrototypeOf(PickArgsTest1));
const filterableFields = getFilterableFields(PickArgsTest1);
expect(fields).toHaveLength(5);
expect(filterableFields).toHaveLength(2);
expect(filterableFields[0].propertyName).toEqual('f');
expect(filterableFields[1].propertyName).toEqual('g');
expect(fields[0].name).toEqual('a');
expect(fields[1].name).toEqual('c');
expect(fields[2].name).toEqual('f');
expect(fields[3].name).toEqual('g');
expect(fields[4].name).toEqual('h');
});
});
1 change: 1 addition & 0 deletions packages/query-graphql/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@
},
"dependencies": {
"@nestjs-query/core": "0.30.0",
"@nestjs/mapped-types": "1.0.0",
"graphql-fields": "^2.0.3",
"lodash.omit": "^4.5.0",
"lower-case-first": "^2.0.1",
Expand Down
1 change: 1 addition & 0 deletions packages/query-graphql/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -57,3 +57,4 @@ export {
BeforeFindOneHook,
} from './hooks';
export { AuthorizerInterceptor, AuthorizerContext, HookInterceptor, HookContext } from './interceptors';
export * from './type-helpers';
4 changes: 4 additions & 0 deletions packages/query-graphql/src/type-helpers/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
export { IntersectionType } from './intersection-type.helper';
export { OmitType } from './omit-type.helper';
export { PartialType } from './partial-type.helper';
export { PickType } from './pick-type.helper';
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
import { Type } from '@nestjs/common';
import { Field } from '@nestjs/graphql';
import {
inheritPropertyInitializers,
inheritTransformationMetadata,
inheritValidationMetadata,
} from '@nestjs/mapped-types';
import { ClassDecoratorFactory } from '@nestjs/graphql/dist/interfaces/class-decorator-factory.interface';
import { getFieldsAndDecoratorForType } from '@nestjs/graphql/dist/schema-builder/utils/get-fields-and-decorator.util';
import { applyFieldDecorators } from '@nestjs/graphql/dist/type-helpers/type-helpers.utils';
import { FilterableField, getFilterableFields } from '../decorators';

export function IntersectionType<A, B>(
classARef: Type<A>,
classBRef: Type<B>,
decorator?: ClassDecoratorFactory,
): Type<A & B> {
const { decoratorFactory, fields: fieldsA } = getFieldsAndDecoratorForType(classARef);
const filterableFieldsA = getFilterableFields(classARef);

const { fields: fieldsB } = getFieldsAndDecoratorForType(classBRef);
const filterableFieldsB = getFilterableFields(classBRef);
const fields = [...fieldsA, ...fieldsB];
const filterableFields = [...filterableFieldsA, ...filterableFieldsB];

abstract class IntersectionObjectType {
constructor() {
inheritPropertyInitializers(this, classARef);
inheritPropertyInitializers(this, classBRef);
}
}
if (decorator) {
decorator({ isAbstract: true })(IntersectionObjectType);
} else {
decoratorFactory({ isAbstract: true })(IntersectionObjectType);
}

inheritValidationMetadata(classARef, IntersectionObjectType);
inheritTransformationMetadata(classARef, IntersectionObjectType);
inheritValidationMetadata(classBRef, IntersectionObjectType);
inheritTransformationMetadata(classBRef, IntersectionObjectType);

fields.forEach((item) => {
const filterableField = filterableFields.find((f) => f.propertyName === item.name);
if (filterableField) {
FilterableField(item.typeFn, { ...filterableField.advancedOptions })(IntersectionObjectType.prototype, item.name);
} else {
Field(item.typeFn, { ...item.options })(IntersectionObjectType.prototype, item.name);
}
applyFieldDecorators(IntersectionObjectType, item);
});

Object.defineProperty(IntersectionObjectType, 'name', {
value: `Intersection${classARef.name}${classBRef.name}`,
});
return IntersectionObjectType as Type<A & B>;
}
Loading