feat: 优化响应装饰器参数
parent
5e18102d61
commit
ee9cb2c81d
Binary file not shown.
|
|
@ -11,12 +11,16 @@ import { redisStore } from 'cache-manager-redis-store';
|
||||||
inject: [ConfigService],
|
inject: [ConfigService],
|
||||||
useFactory: (config: ConfigService) => {
|
useFactory: (config: ConfigService) => {
|
||||||
const { host, port } = config.redis;
|
const { host, port } = config.redis;
|
||||||
|
// TODO
|
||||||
|
let store: any;
|
||||||
|
if (store) {
|
||||||
|
store = () =>
|
||||||
|
redisStore({
|
||||||
|
commandsQueueMaxLength: 1000,
|
||||||
|
socket: { host, port },
|
||||||
|
}) as any;
|
||||||
|
}
|
||||||
return {
|
return {
|
||||||
// store: () =>
|
|
||||||
// redisStore({
|
|
||||||
// commandsQueueMaxLength: 1000,
|
|
||||||
// socket: { host, port },
|
|
||||||
// }) as any,
|
|
||||||
db: 0,
|
db: 0,
|
||||||
ttl: 600,
|
ttl: 600,
|
||||||
};
|
};
|
||||||
|
|
|
||||||
|
|
@ -14,6 +14,7 @@ export class AllExecptionFilter implements ExceptionFilter {
|
||||||
const response = ctx.getResponse<_Response>();
|
const response = ctx.getResponse<_Response>();
|
||||||
const message = exception.message;
|
const message = exception.message;
|
||||||
const code = ResponseCode.UNKNOWN_ERROR;
|
const code = ResponseCode.UNKNOWN_ERROR;
|
||||||
|
console.trace(exception);
|
||||||
this.logger.error(exception, `${request.method} ${request.url}`);
|
this.logger.error(exception, `${request.method} ${request.url}`);
|
||||||
response.status(HttpStatus.INTERNAL_SERVER_ERROR).json(Response.create({ code, message, data: null }));
|
response.status(HttpStatus.INTERNAL_SERVER_ERROR).json(Response.create({ code, message, data: null }));
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -5,31 +5,29 @@ import { SetMetadata } from '@nestjs/common';
|
||||||
*/
|
*/
|
||||||
export const RESPONSE_KEY = 'APP:RESPONSE';
|
export const RESPONSE_KEY = 'APP:RESPONSE';
|
||||||
|
|
||||||
type RespondFn = {
|
/**
|
||||||
(type: 'raw' | 'wrap' | 'pagination'): any;
|
* 响应结果类型
|
||||||
|
*/
|
||||||
|
export enum RespondType {
|
||||||
/**
|
/**
|
||||||
* 原始,返回的数据不会被包装
|
* 原始,返回的数据不会被包装
|
||||||
*/
|
*/
|
||||||
RAW: 'raw';
|
RAW = 'raw',
|
||||||
/**
|
/**
|
||||||
* 包装,返回的数据会被包装成统一的格式
|
* 包装,返回的数据会被包装成统一的格式
|
||||||
*/
|
*/
|
||||||
WRAP: 'wrap';
|
WRAP = 'wrap',
|
||||||
/**
|
/**
|
||||||
* 分页,需返回 `[data, total]` 格式的数据
|
* 分页,需返回 `[data, total]` 格式的数据
|
||||||
*/
|
*/
|
||||||
PAGINATION: 'pagination';
|
PAGINATION = 'pagination',
|
||||||
};
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 响应结果装饰器
|
* 响应结果装饰器
|
||||||
* @param type 类型
|
* @param type 类型
|
||||||
* @returns
|
* @returns
|
||||||
*/
|
*/
|
||||||
export const Respond = <RespondFn>((type = 'wrap') => {
|
export const Respond = (type = RespondType.WRAP) => {
|
||||||
return SetMetadata(RESPONSE_KEY, type);
|
return SetMetadata(RESPONSE_KEY, type);
|
||||||
});
|
};
|
||||||
|
|
||||||
Respond.RAW = 'raw';
|
|
||||||
Respond.WRAP = 'wrap';
|
|
||||||
Respond.PAGINATION = 'pagination';
|
|
||||||
|
|
|
||||||
|
|
@ -2,7 +2,7 @@ import { CallHandler, ExecutionContext, Injectable, NestInterceptor } from '@nes
|
||||||
import { Reflector } from '@nestjs/core';
|
import { Reflector } from '@nestjs/core';
|
||||||
import { Observable, map } from 'rxjs';
|
import { Observable, map } from 'rxjs';
|
||||||
import { Response } from './response';
|
import { Response } from './response';
|
||||||
import { RESPONSE_KEY, Respond } from './response.decorator';
|
import { RESPONSE_KEY, RespondType } from './response.decorator';
|
||||||
import { Request } from 'express';
|
import { Request } from 'express';
|
||||||
import { ConfigService } from '@/config';
|
import { ConfigService } from '@/config';
|
||||||
|
|
||||||
|
|
@ -16,10 +16,10 @@ export class ResponseInterceptor implements NestInterceptor {
|
||||||
const type = this.reflector.getAllAndOverride(RESPONSE_KEY, [controller, handler]);
|
const type = this.reflector.getAllAndOverride(RESPONSE_KEY, [controller, handler]);
|
||||||
return next.handle().pipe(
|
return next.handle().pipe(
|
||||||
map((data: any) => {
|
map((data: any) => {
|
||||||
if (type === Respond.RAW) {
|
if (type === RespondType.RAW) {
|
||||||
return data;
|
return data;
|
||||||
}
|
}
|
||||||
if (type === Respond.PAGINATION) {
|
if (type === RespondType.PAGINATION) {
|
||||||
const request = context.switchToHttp().getRequest<Request>();
|
const request = context.switchToHttp().getRequest<Request>();
|
||||||
const [list, total] = data;
|
const [list, total] = data;
|
||||||
if (request.query.meta) {
|
if (request.query.meta) {
|
||||||
|
|
|
||||||
|
|
@ -1,4 +1,4 @@
|
||||||
import { Respond } from '@/common/response';
|
import { Respond, RespondType } from '@/common/response';
|
||||||
import { Body, Controller, Delete, Get, Param, Patch, Post } from '@nestjs/common';
|
import { Body, Controller, Delete, Get, Param, Patch, Post } from '@nestjs/common';
|
||||||
import { ApiOperation, ApiTags } from '@nestjs/swagger';
|
import { ApiOperation, ApiTags } from '@nestjs/swagger';
|
||||||
import { CreatePermissionDto } from './dto/create-permission.dto';
|
import { CreatePermissionDto } from './dto/create-permission.dto';
|
||||||
|
|
@ -17,7 +17,7 @@ export class PermissionController {
|
||||||
}
|
}
|
||||||
|
|
||||||
@Get()
|
@Get()
|
||||||
@Respond(Respond.PAGINATION)
|
@Respond(RespondType.PAGINATION)
|
||||||
@ApiOperation({ description: '批量查询权限', operationId: 'getPermissions' })
|
@ApiOperation({ description: '批量查询权限', operationId: 'getPermissions' })
|
||||||
findAll() {
|
findAll() {
|
||||||
return this.permissionService.findAll();
|
return this.permissionService.findAll();
|
||||||
|
|
|
||||||
|
|
@ -1 +1,19 @@
|
||||||
export class CreatePostDto {}
|
import { IsString } from 'class-validator';
|
||||||
|
|
||||||
|
export class CreatePostDto {
|
||||||
|
/**
|
||||||
|
* 文章标题
|
||||||
|
*/
|
||||||
|
@IsString()
|
||||||
|
title: string;
|
||||||
|
/**
|
||||||
|
* 文章描述
|
||||||
|
*/
|
||||||
|
@IsString()
|
||||||
|
description: string;
|
||||||
|
/**
|
||||||
|
* 文章内容
|
||||||
|
*/
|
||||||
|
@IsString()
|
||||||
|
content: string;
|
||||||
|
}
|
||||||
|
|
|
||||||
|
|
@ -0,0 +1,4 @@
|
||||||
|
import { PaginationDto } from '@/common/response';
|
||||||
|
import { IntersectionType } from '@nestjs/swagger';
|
||||||
|
|
||||||
|
export class FindPostDto extends IntersectionType(PaginationDto) {}
|
||||||
|
|
@ -1,13 +1,33 @@
|
||||||
import { Body, Controller, Delete, Get, Param, Patch, Post } from '@nestjs/common';
|
import {
|
||||||
|
Body,
|
||||||
|
Controller,
|
||||||
|
Delete,
|
||||||
|
Get,
|
||||||
|
NotFoundException,
|
||||||
|
Param,
|
||||||
|
ParseIntPipe,
|
||||||
|
Patch,
|
||||||
|
Post,
|
||||||
|
Query,
|
||||||
|
Res,
|
||||||
|
} from '@nestjs/common';
|
||||||
import { ApiOperation, ApiTags } from '@nestjs/swagger';
|
import { ApiOperation, ApiTags } from '@nestjs/swagger';
|
||||||
import { CreatePostDto } from './dto/create-post.dto';
|
import { CreatePostDto } from './dto/create-post.dto';
|
||||||
import { UpdatePostDto } from './dto/update-post.dto';
|
import { UpdatePostDto } from './dto/update-post.dto';
|
||||||
import { PostService } from './post.service';
|
import { PostService } from './post.service';
|
||||||
|
import { join } from 'path';
|
||||||
|
import { readFileSync } from 'fs';
|
||||||
|
import { Response } from 'express';
|
||||||
|
import { BaseController } from '@/common/base';
|
||||||
|
import { Respond, RespondType } from '@/common/response';
|
||||||
|
import { FindPostDto } from './dto/find-post.dto';
|
||||||
|
|
||||||
@Controller('post')
|
|
||||||
@ApiTags('post')
|
@ApiTags('post')
|
||||||
export class PostController {
|
@Controller('posts')
|
||||||
constructor(private readonly postService: PostService) {}
|
export class PostController extends BaseController {
|
||||||
|
constructor(private readonly postService: PostService) {
|
||||||
|
super();
|
||||||
|
}
|
||||||
|
|
||||||
@Post()
|
@Post()
|
||||||
@ApiOperation({ description: '创建文章', operationId: 'addPost' })
|
@ApiOperation({ description: '创建文章', operationId: 'addPost' })
|
||||||
|
|
@ -15,27 +35,42 @@ export class PostController {
|
||||||
return this.postService.create(createPostDto);
|
return this.postService.create(createPostDto);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Get('template.xlsx')
|
||||||
|
@ApiOperation({ description: '获取文章下载模板', operationId: 'getPostTemplate' })
|
||||||
|
getTemplate(@Res() res: Response) {
|
||||||
|
try {
|
||||||
|
const filePath = join(process.cwd(), './content/template/模板1.xlsx');
|
||||||
|
res.type('application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
|
||||||
|
res.attachment('模板1.xlsx');
|
||||||
|
// res.sendFile(filePath);
|
||||||
|
res.send(readFileSync(filePath));
|
||||||
|
} catch (e) {
|
||||||
|
throw new NotFoundException('模板不存在');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
@Get()
|
@Get()
|
||||||
|
@Respond(RespondType.PAGINATION)
|
||||||
@ApiOperation({ description: '批量查询文章', operationId: 'getPosts' })
|
@ApiOperation({ description: '批量查询文章', operationId: 'getPosts' })
|
||||||
findAll() {
|
findAll(@Query() findPostDto: FindPostDto) {
|
||||||
return this.postService.findAll();
|
return this.postService.findAll(findPostDto);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Get(':id')
|
@Get(':id')
|
||||||
@ApiOperation({ description: '查询文章', operationId: 'getPost' })
|
@ApiOperation({ description: '查询文章', operationId: 'getPost' })
|
||||||
findOne(@Param('id') id: string) {
|
findOne(@Param('id', ParseIntPipe) id: number) {
|
||||||
return this.postService.findOne(+id);
|
return this.postService.findOne(id);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Patch(':id')
|
@Patch(':id')
|
||||||
@ApiOperation({ description: '更新文章', operationId: 'updatePost' })
|
@ApiOperation({ description: '更新文章', operationId: 'updatePost' })
|
||||||
update(@Param('id') id: string, @Body() updatePostDto: UpdatePostDto) {
|
update(@Param('id', ParseIntPipe) id: number, @Body() updatePostDto: UpdatePostDto) {
|
||||||
return this.postService.update(+id, updatePostDto);
|
return this.postService.update(id, updatePostDto);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Delete(':id')
|
@Delete(':id')
|
||||||
@ApiOperation({ description: '删除文章', operationId: 'delPost' })
|
@ApiOperation({ description: '删除文章', operationId: 'delPost' })
|
||||||
remove(@Param('id') id: string) {
|
remove(@Param('id', ParseIntPipe) id: number) {
|
||||||
return this.postService.remove(+id);
|
return this.postService.remove(+id);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -4,10 +4,14 @@ import { UpdatePostDto } from './dto/update-post.dto';
|
||||||
import { InjectRepository } from '@nestjs/typeorm';
|
import { InjectRepository } from '@nestjs/typeorm';
|
||||||
import { Post } from './entities/post.entity';
|
import { Post } from './entities/post.entity';
|
||||||
import { Repository } from 'typeorm';
|
import { Repository } from 'typeorm';
|
||||||
|
import { BaseService } from '@/common/base';
|
||||||
|
import { FindPostDto } from './dto/find-post.dto';
|
||||||
|
|
||||||
@Injectable()
|
@Injectable()
|
||||||
export class PostService {
|
export class PostService extends BaseService {
|
||||||
constructor(@InjectRepository(Post) private postRepository: Repository<Post>) {}
|
constructor(@InjectRepository(Post) private postRepository: Repository<Post>) {
|
||||||
|
super();
|
||||||
|
}
|
||||||
|
|
||||||
async create(createPostDto: CreatePostDto) {
|
async create(createPostDto: CreatePostDto) {
|
||||||
const post = this.postRepository.create(createPostDto);
|
const post = this.postRepository.create(createPostDto);
|
||||||
|
|
@ -15,12 +19,13 @@ export class PostService {
|
||||||
return post.id;
|
return post.id;
|
||||||
}
|
}
|
||||||
|
|
||||||
findAll() {
|
findAll(findPostDto: FindPostDto) {
|
||||||
return this.postRepository.findAndCount();
|
const { skip, take } = this.formatPagination(findPostDto.page, findPostDto.size);
|
||||||
|
return this.postRepository.findAndCount({ skip, take });
|
||||||
}
|
}
|
||||||
|
|
||||||
findOne(id: number) {
|
findOne(id: number) {
|
||||||
return this.postRepository.findOne({ where: { id } });
|
return this.postRepository.findOneOrFail({ where: { id } });
|
||||||
}
|
}
|
||||||
|
|
||||||
update(id: number, updatePostDto: UpdatePostDto) {
|
update(id: number, updatePostDto: UpdatePostDto) {
|
||||||
|
|
|
||||||
|
|
@ -1,4 +1,4 @@
|
||||||
import { Respond } from '@/common/response';
|
import { Respond, RespondType } from '@/common/response';
|
||||||
import { Body, Controller, Delete, Get, Param, Patch, Post } from '@nestjs/common';
|
import { Body, Controller, Delete, Get, Param, Patch, Post } from '@nestjs/common';
|
||||||
import { ApiOperation, ApiTags } from '@nestjs/swagger';
|
import { ApiOperation, ApiTags } from '@nestjs/swagger';
|
||||||
import { CreateRoleDto } from './dto/create-role.dto';
|
import { CreateRoleDto } from './dto/create-role.dto';
|
||||||
|
|
@ -17,7 +17,7 @@ export class RoleController {
|
||||||
}
|
}
|
||||||
|
|
||||||
@Get()
|
@Get()
|
||||||
@Respond(Respond.PAGINATION)
|
@Respond(RespondType.PAGINATION)
|
||||||
@ApiOperation({ description: '批量查询角色', operationId: 'getRoles' })
|
@ApiOperation({ description: '批量查询角色', operationId: 'getRoles' })
|
||||||
findAll() {
|
findAll() {
|
||||||
return this.roleService.findAll();
|
return this.roleService.findAll();
|
||||||
|
|
|
||||||
|
|
@ -1,4 +1,4 @@
|
||||||
import { Respond } from '@/common/response';
|
import { Respond, RespondType } from '@/common/response';
|
||||||
import { Controller, Delete, Get, Ip, Param, Patch, Post, Req, UploadedFile, UseInterceptors } from '@nestjs/common';
|
import { Controller, Delete, Get, Ip, Param, Patch, Post, Req, UploadedFile, UseInterceptors } from '@nestjs/common';
|
||||||
import { FileInterceptor } from '@nestjs/platform-express';
|
import { FileInterceptor } from '@nestjs/platform-express';
|
||||||
import { ApiBody, ApiConsumes, ApiOperation, ApiTags } from '@nestjs/swagger';
|
import { ApiBody, ApiConsumes, ApiOperation, ApiTags } from '@nestjs/swagger';
|
||||||
|
|
@ -22,7 +22,7 @@ export class UploadController {
|
||||||
}
|
}
|
||||||
|
|
||||||
@Get()
|
@Get()
|
||||||
@Respond(Respond.PAGINATION)
|
@Respond(RespondType.PAGINATION)
|
||||||
@ApiOperation({ description: '批量查询', operationId: 'getUploads' })
|
@ApiOperation({ description: '批量查询', operationId: 'getUploads' })
|
||||||
findAll() {
|
findAll() {
|
||||||
return this.uploadService.findAll();
|
return this.uploadService.findAll();
|
||||||
|
|
|
||||||
|
|
@ -1,5 +1,5 @@
|
||||||
import { BaseController } from '@/common/base';
|
import { BaseController } from '@/common/base';
|
||||||
import { Respond } from '@/common/response';
|
import { Respond, RespondType } from '@/common/response';
|
||||||
import { Body, Controller, Delete, Get, Param, Patch, Post, Query, Version } from '@nestjs/common';
|
import { Body, Controller, Delete, Get, Param, Patch, Post, Query, Version } from '@nestjs/common';
|
||||||
import { ApiOkResponse, ApiOperation, ApiTags } from '@nestjs/swagger';
|
import { ApiOkResponse, ApiOperation, ApiTags } from '@nestjs/swagger';
|
||||||
import { CreateUserDto } from './dto/create-user.dto';
|
import { CreateUserDto } from './dto/create-user.dto';
|
||||||
|
|
@ -22,7 +22,7 @@ export class UserController extends BaseController {
|
||||||
}
|
}
|
||||||
|
|
||||||
@Get()
|
@Get()
|
||||||
@Respond(Respond.PAGINATION)
|
@Respond(RespondType.PAGINATION)
|
||||||
@ApiOkResponse({ isArray: true, type: User })
|
@ApiOkResponse({ isArray: true, type: User })
|
||||||
@ApiOperation({ description: '批量查询用户', operationId: 'getUsers' })
|
@ApiOperation({ description: '批量查询用户', operationId: 'getUsers' })
|
||||||
async findMany(@Query() query: FindUserDto) {
|
async findMany(@Query() query: FindUserDto) {
|
||||||
|
|
|
||||||
Loading…
Reference in New Issue