Skip to content

Commit

Permalink
feat: init project nestjs response
Browse files Browse the repository at this point in the history
  • Loading branch information
nguyentiendung-dev committed Mar 23, 2023
0 parents commit 5a704c4
Show file tree
Hide file tree
Showing 27 changed files with 17,295 additions and 0 deletions.
8 changes: 8 additions & 0 deletions .auto-changelog
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
{
"output": "CHANGELOG.md",
"template": "keepachangelog",
"unreleased": true,
"ignoreCommitPattern": "^(?!(feat|fix|\\[feat\\]|\\[fix\\]))(.*)$",
"commitLimit": false,
"commitUrl": "https://github.com/hodfords-solutions/nestjs-storage/commit/{id}"
}
24 changes: 24 additions & 0 deletions .eslintrc.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
module.exports = {
parser: '@typescript-eslint/parser',
parserOptions: {
project: 'tsconfig.json',
sourceType: 'module',
},
plugins: ['@typescript-eslint/eslint-plugin'],
extends: [
'plugin:@typescript-eslint/recommended',
'plugin:prettier/recommended',
],
root: true,
env: {
node: true,
jest: true,
},
ignorePatterns: ['.eslintrc.js'],
rules: {
'@typescript-eslint/interface-name-prefix': 'off',
'@typescript-eslint/explicit-function-return-type': 'off',
'@typescript-eslint/explicit-module-boundary-types': 'off',
'@typescript-eslint/no-explicit-any': 'off',
},
};
20 changes: 20 additions & 0 deletions .github/workflows/publish.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
name: Publish Package to npmjs
on:
push:
branch:
- main
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- uses: actions/setup-node@v3
with:
node-version: '16.x'
registry-url: 'https://registry.npmjs.org'
- run: npm install
- run: npm run build
- run: cp package.json dist/libs/package.json
- run: cd dist/libs && npm publish --access public
env:
NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
35 changes: 35 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
# compiled output
/dist
/node_modules

# Logs
logs
*.log
npm-debug.log*
pnpm-debug.log*
yarn-debug.log*
yarn-error.log*
lerna-debug.log*

# OS
.DS_Store

# Tests
/coverage
/.nyc_output

# IDEs and editors
/.idea
.project
.classpath
.c9/
*.launch
.settings/
*.sublime-workspace

# IDE - VSCode
.vscode/*
!.vscode/settings.json
!.vscode/tasks.json
!.vscode/launch.json
!.vscode/extensions.json
4 changes: 4 additions & 0 deletions .husky/pre-commit
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
#!/usr/bin/env sh
. "$(dirname -- "$0")/_/husky.sh"

npx --no-install lint-staged
3 changes: 3 additions & 0 deletions .lintstagedrc.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
{
"libs/**/*.ts": ["prettier --write"]
}
3 changes: 3 additions & 0 deletions .npmrc
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
//registry.npmjs.org/:_authToken=${NODE_AUTH_TOKEN}
registry=https://registry.npmjs.org/
always-auth=true
12 changes: 12 additions & 0 deletions .prettierrc
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
{
"singleQuote": true,
"printWidth": 120,
"proseWrap": "always",
"tabWidth": 4,
"useTabs": false,
"trailingComma": "none",
"bracketSpacing": true,
"jsxBracketSameLine": false,
"semi": true,
"endOfLine": "auto"
}
71 changes: 71 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
<p align="center">
<a href="http://nestjs.com/" target="blank"><img src="https://nestjs.com/img/logo_text.svg" width="320" alt="Nest Logo" /></a>
</p>

[circleci-image]: https://img.shields.io/circleci/build/github/nestjs/nest/master?token=abc123def456
[circleci-url]: https://circleci.com/gh/nestjs/nest

<p align="center">A progressive <a href="http://nodejs.org" target="_blank">Node.js</a> framework for building efficient and scalable server-side applications.</p>
<p align="center">
<a href="https://www.npmjs.com/~nestjscore" target="_blank"><img src="https://img.shields.io/npm/v/@nestjs/core.svg" alt="NPM Version" /></a>
<a href="https://www.npmjs.com/~nestjscore" target="_blank"><img src="https://img.shields.io/npm/l/@nestjs/core.svg" alt="Package License" /></a>
<a href="https://www.npmjs.com/~nestjscore" target="_blank"><img src="https://img.shields.io/npm/dm/@nestjs/common.svg" alt="NPM Downloads" /></a>
<a href="https://circleci.com/gh/nestjs/nest" target="_blank"><img src="https://img.shields.io/circleci/build/github/nestjs/nest/master" alt="CircleCI" /></a>
<a href="https://coveralls.io/github/nestjs/nest?branch=master" target="_blank"><img src="https://coveralls.io/repos/github/nestjs/nest/badge.svg?branch=master#9" alt="Coverage" /></a>
<a href="https://discord.gg/G7Qnnhy" target="_blank"><img src="https://img.shields.io/badge/discord-online-brightgreen.svg" alt="Discord"/></a>
<a href="https://opencollective.com/nest#backer" target="_blank"><img src="https://opencollective.com/nest/backers/badge.svg" alt="Backers on Open Collective" /></a>
<a href="https://opencollective.com/nest#sponsor" target="_blank"><img src="https://opencollective.com/nest/sponsors/badge.svg" alt="Sponsors on Open Collective" /></a>
<a href="https://paypal.me/kamilmysliwiec" target="_blank"><img src="https://img.shields.io/badge/Donate-PayPal-ff3f59.svg"/></a>
<a href="https://opencollective.com/nest#sponsor" target="_blank"><img src="https://img.shields.io/badge/Support%20us-Open%20Collective-41B883.svg" alt="Support us"></a>
<a href="https://twitter.com/nestframework" target="_blank"><img src="https://img.shields.io/twitter/follow/nestframework.svg?style=social&label=Follow"></a>
</p>
<!--[![Backers on Open Collective](https://opencollective.com/nest/backers/badge.svg)](https://opencollective.com/nest#backer)
[![Sponsors on Open Collective](https://opencollective.com/nest/sponsors/badge.svg)](https://opencollective.com/nest#sponsor)-->

# nestjs-response

## Installation 🤖

```
npm install @hodfords/nestjs-response --save
```

```typescript
class UserResponse {
@ApiProperty()
@IsNotEmpty()
@IsString()
name: string
}

class UserController{
@Get()
@ResponseModel(UserResponse, true)
getAllUser() {
return [{name: "hello"}]
}
}

```

- `Interceptor global`
```javascript
{
providers: [
{
provide: APP_INTERCEPTOR,
useClass: LoggingInterceptor
}
]
}
```

- `Interceptor decorator`
```javascript
@Controller('test')
@UseResponseInterceptor()
export class TestController {

}
```
1 change: 1 addition & 0 deletions libs/constants/metadata.constant.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export const RESPONSE_METADATA_KEY = 'response:class'
13 changes: 13 additions & 0 deletions libs/decorators/response-model.decorator.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import { applyDecorators, SetMetadata } from '@nestjs/common';
import { RESPONSE_METADATA_KEY } from '../constants/metadata.constant';
import { ApiResponse } from '@nestjs/swagger';

export function ResponseModel(responseClass, isArray = false): any {
return applyDecorators(
ApiResponse({ type: responseClass, isArray }),
SetMetadata(RESPONSE_METADATA_KEY, {
responseClass,
isArray
})
);
}
6 changes: 6 additions & 0 deletions libs/decorators/use-response-interceptor.decorator.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
import {UseInterceptors} from "@nestjs/common";
import {ResponseInterceptor} from "../interceptors/response.interceptor";

export function UseResponseInterceptor(){
return UseInterceptors(ResponseInterceptor)
}
7 changes: 7 additions & 0 deletions libs/exceptions/response-validate.exception.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
import { HttpException, HttpStatus } from '@nestjs/common';

export class ResponseValidateException extends HttpException {
constructor(public errors) {
super({}, HttpStatus.INTERNAL_SERVER_ERROR);
}
}
5 changes: 5 additions & 0 deletions libs/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
export * from './constants/metadata.constant'
export * from './decorators/response-model.decorator'
export * from './decorators/use-response-interceptor.decorator'
export * from './exceptions/response-validate.exception'
export * from './interceptors/response.interceptor'
46 changes: 46 additions & 0 deletions libs/interceptors/response.interceptor.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
import { CallHandler, ExecutionContext, Injectable, NestInterceptor } from '@nestjs/common';
import { map, Observable } from 'rxjs';
import { plainToInstance } from 'class-transformer';
import { validate } from 'class-validator';
import { ResponseValidateException } from '../exceptions/response-validate.exception';
import { RESPONSE_METADATA_KEY } from '../constants/metadata.constant';

@Injectable()
export class ResponseInterceptor implements NestInterceptor {
intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
return next.handle().pipe(map((data) => this.handleResponse(context, data)));
}

async handleResponse(context: ExecutionContext, data) {
let responseMetadata = Reflect.getMetadata(RESPONSE_METADATA_KEY, context.getHandler());
if (!responseMetadata) {
return data;
}
if (responseMetadata.isArray) {
let newData = [];
for (let item of data) {
let newItem = plainToInstance(responseMetadata.responseClass, item);
let errors = await validate(newItem, {
whitelist: true,
stopAtFirstError: true
});
if (errors.length) {
console.error(errors);
throw new ResponseValidateException(errors);
}
newData.push(newItem);
}
return newData;
}
let newData = plainToInstance(responseMetadata.responseClass, data);
let errors = await validate(newData, {
whitelist: true,
stopAtFirstError: true
});
if (errors.length) {
console.error(errors);
throw new ResponseValidateException(errors);
}
return newData;
}
}
21 changes: 21 additions & 0 deletions nest-cli.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
{
"collection": "@nestjs/schematics",
"sourceRoot": "src",
"projects": {
"nestjs-response": {
"type": "library",
"root": "libs",
"entryFile": "index",
"sourceRoot": "libs"
}
},
"compilerOptions": {
"webpack": false,
"assets": [
{
"include": "../libs/public/**",
"watchAssets": true
}
]
}
}
Loading

0 comments on commit 5a704c4

Please sign in to comment.