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 2 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
3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,7 @@
"@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-class-validators": "file:packages/class-validators",
"@algoan/nestjs-class-transformers": "file:packages/class-transformers"
}
}
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: ".",
};
23 changes: 23 additions & 0 deletions packages/class-transformers/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
{
"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
}
}
}
34 changes: 34 additions & 0 deletions packages/class-transformers/src/enum-fallback.decorator.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
/* eslint-disable @typescript-eslint/no-explicit-any */

import { ValidationArguments, ValidationOptions, registerDecorator } from 'class-validator';

/**
* Checks if a given value is the member of the provided enum and call a fallback function
* if the value is invalid
*/
export function EnumFallback(enumType: any, fallback: (value: any) => any, validationOptions?: ValidationOptions) {
return function (object: Record<string, any>, propertyName: string) {
registerDecorator({
name: 'enumFallback',
target: object.constructor,
propertyName,
constraints: [enumType, fallback],
options: validationOptions,
validator: {
validate(value: any, args: ValidationArguments) {
const [enumTypeValue, fallbackFn] = args.constraints;
if (value === undefined || !Object.values(enumTypeValue).includes(value)) {
// eslint-disable-next-line
const updatedObject = Object.assign({}, args.object, {
[propertyName]: fallbackFn(value),
});
// eslint-disable-next-line
Object.assign(args.object, updatedObject);
}

return true;
},
},
});
};
}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You implemented the solution described in #833 which has been rejected in favour of #834. Sorry, my investigation may not be clear enough.

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';
44 changes: 44 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,44 @@
import { EnumFallback } from '../src';
import { ArgumentMetadata, ValidationPipe } from '@nestjs/common';

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

class UserDto {
@EnumFallback(UserRole, (_value: UserRole) => UserRole.READER)
public role?: UserRole;
}

describe('EnumFallback Decorator', () => {
it('should apply the fallback functions when we have an invalid value', async () => {
const userDto = new UserDto();
userDto.role = 'WRITER' as UserRole;

let target: ValidationPipe = new ValidationPipe({ transform: true, whitelist: true });
const metadata: ArgumentMetadata = {
type: 'body',
metatype: UserDto,
data: '',
};
const result = await target.transform(userDto, metadata);

expect(result.role).toEqual(UserRole.READER);
});

it('should not apply the fallback function when the value is valid', async () => {
const userDto = new UserDto();
userDto.role = UserRole.ADMIN;

let target: ValidationPipe = new ValidationPipe({ transform: true, whitelist: true });
const metadata: ArgumentMetadata = {
type: 'body',
metatype: UserDto,
data: '',
};
const result = await target.transform(userDto, metadata);

expect(result.role).toBe(UserRole.ADMIN);
});
});
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"
]
}