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] Add EnumFallback decorator #836

Closed
wants to merge 3 commits into from
Closed
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
6 changes: 6 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,12 @@ A package containing overriden class validators.

See [the documentation here](./packages/class-validators).

## NestJS class transformers

A package containing custom class transformers.

See [the documentation here](./packages/class-transformers).

# Contribution

This repository is managed by [Lerna.js](https://lerna.js.org). If you want to contribute, you need to follow these instructions:
Expand Down
41 changes: 37 additions & 4 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

5 changes: 3 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -89,12 +89,13 @@
}
},
"dependencies": {
"@algoan/nestjs-class-transformers": "file:packages/class-transformers",
"@algoan/nestjs-class-validators": "file:packages/class-validators",
"@algoan/nestjs-custom-decorators": "file:packages/custom-decorators",
"@algoan/nestjs-google-pubsub-client": "file:packages/google-pubsub-client",
"@algoan/nestjs-google-pubsub-microservice": "file:packages/google-pubsub-microservice",
"@algoan/nestjs-http-exception-filter": "file:packages/http-exception-filter",
"@algoan/nestjs-logging-interceptor": "file:packages/logging-interceptor",
"@algoan/nestjs-pagination": "file:packages/pagination",
"@algoan/nestjs-class-validators": "file:packages/class-validators"
"@algoan/nestjs-pagination": "file:packages/pagination"
}
}
29 changes: 29 additions & 0 deletions packages/class-transformers/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
# Nestjs class transformers

A set of class transformers

## Installation

```bash
npm install --save @algoan/nestjs-class-validators
```

## EnumFallback


### Usage

```ts
export enum UserRole {
ADMIN = 'ADMIN',
READER = 'READER',
}

class UserDto {
@EnumFallback({
type: UserRole,
fallback: (value: UserRole) => UserRole.READER // if the role is not "ADMIN" or "READER", then the role will be "READER".
})
public role?: UserRole;
}
```
8 changes: 8 additions & 0 deletions packages/class-transformers/jest.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
module.exports = {
...require('../jest.common'),

coverageDirectory: "coverage",
collectCoverageFrom: ["./src/**/*.ts"],

rootDir: ".",
};
26 changes: 26 additions & 0 deletions packages/class-transformers/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
{
"name": "@algoan/nestjs-class-transformers",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"build": "tsc -p .",
"test": "jest"
},
"author": "",
"license": "ISC",
"dependencies": {
"class-transformer": "^0.5.1",
"class-validator": "^0.14.0",
"reflect-metadata": "^0.2.1"
},
"globals": {
"ts-jest": {
"diagnostics": false,
"isolatedModules": true
}
},
"peerDependencies": {
"@nestjs/common": ">=8"
}
}
27 changes: 27 additions & 0 deletions packages/class-transformers/src/enum-fallback.decorator.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
/* eslint-disable @typescript-eslint/no-explicit-any */

import { applyDecorators } from '@nestjs/common';
import { Transform, TransformOptions } from 'class-transformer';

/**
* Checks if a given value is the member of the provided enum and call a fallback function
* if the value is invalid
*/
interface EnumFallbackOptions<T> {
type: unknown;
fallback: (value: T) => T;
}

export function EnumFallback<T>(options: EnumFallbackOptions<T>, transformOptions?: TransformOptions) {
const { type, fallback } = options;

return applyDecorators(
Transform(({ value }) => {
if (value === undefined || !Object.values(type as string[]).includes(value)) {
return fallback(value);
}

return value;
}, transformOptions),
);
}
1 change: 1 addition & 0 deletions packages/class-transformers/src/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export * from './enum-fallback.decorator';
29 changes: 29 additions & 0 deletions packages/class-transformers/test/enum-fallback-decorator.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
import { INestApplication } from '@nestjs/common';
import { FakeAppController, UserRole, createTestAppModule } from './helpers';
import * as request from 'supertest';

describe('EnumFallback Decorator', () => {
let app: INestApplication;
let appController: FakeAppController;

beforeAll(async () => {
app = await createTestAppModule();
await app.init();
});
afterAll(async () => {
await app.close();
});

beforeEach(async () => {
appController = app.get<FakeAppController>(FakeAppController);
});

it('should apply the fallback functions when we have an invalid value', async () => {
const result = appController.createUser({ role: 'WRITER' as UserRole });
expect((result as { role: UserRole }).role).toEqual(UserRole.ADMIN);
});

it('should not apply the fallback function when the value is valid', async () => {
await request(app.getHttpServer()).post('/user').send({ role: 'READER' }).expect(201);
});
});
94 changes: 94 additions & 0 deletions packages/class-transformers/test/helpers.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
import {
Body,
Controller,
ExecutionContext,
INestApplication,
Logger,
Module,
Post,
ValidationPipe,
} from '@nestjs/common';
import { EnumFallback } from '../src';
import { APP_GUARD } from '@nestjs/core';
import { Test, TestingModule } from '@nestjs/testing';

const fakeJWT: string =
'eyJhbGciOiJIUzI1NiIsInR5cCI6IddsqkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c';

export enum UserRole {
ADMIN = 'ADMIN',
READER = 'READER',
}

export class UserDto {
private static readonly logger: Logger = new Logger(UserDto.name);

@EnumFallback({
type: UserRole,
fallback: (value: UserRole) => {
UserDto.logger.error(`Invalid user role ${value}`);
return UserRole.ADMIN;
},
})
public role?: UserRole;
}

/**
* Mock of the AuthGuard class
*/
class AuthGuardMock {
/**
* Check token
*/
public canActivate(context: ExecutionContext): boolean {
const request: { user: { someId: string }; accessTokenJWT: string } = context.switchToHttp().getRequest();
request.user = {
someId: 'id',
};
request.accessTokenJWT = fakeJWT;
return true;
}
}

/**
* Test Controller
*/
@Controller()
export class FakeAppController {
@Post('/user')
public createUser(@Body() user: UserDto): unknown {
console.log('[AL] user', user);
return user;
}
}

/**
* Fake app module
*/
/* eslint-disable */
@Module({
controllers: [FakeAppController],
providers: [
{
provide: APP_GUARD,
useClass: AuthGuardMock,
},
],
})
class AppModule {}
/* eslint-enable */

export async function createTestAppModule(): Promise<INestApplication> {
const moduleFixture: TestingModule = await Test.createTestingModule({
imports: [AppModule],
}).compile();
const app = moduleFixture.createNestApplication({});

app.useGlobalPipes(
new ValidationPipe({
whitelist: true,
}),
);

return app;
}
15 changes: 15 additions & 0 deletions packages/class-transformers/tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
{
"extends": "../tsconfig.base.json",
"compilerOptions": {
"declaration": true,
"experimentalDecorators": true,
"outDir": "dist",
},
"include": [
"./src/**/*",
"./test/**/*.ts"
],
"exclude": [
"node_modules"
]
}
Loading