Commit 8a0fabf2 by yixinjj

添加一些基础搭建内容

1 parent 4d471c11
......@@ -20,5 +20,8 @@ module.exports = {
'@typescript-eslint/interface-name-prefix': 'off',
'@typescript-eslint/explicit-function-return-type': 'off',
'@typescript-eslint/no-explicit-any': 'off',
'@typescript-eslint/camelcase': 'off',
// "quote-props": ["error", "always"],
// "quotes": ["error", "single"]
},
};
......@@ -11,9 +11,11 @@ export class ExceptionsFilter implements ExceptionFilter {
// 获取响应体
const response = ctx.getResponse<Response>()
const request = ctx.getRequest<Request>()
console.log(exception)
// 获取状态码,判断是HTTP异常还是服务器异常
const statusCode = exception instanceof HttpException ? exception.getStatus() : HttpStatus.INTERNAL_SERVER_ERROR
const msg = exception instanceof HttpException? exception.message : '服务器异常'
// 自定义异常返回体
response.status(statusCode).json(BodyResponse(null, '服务器内部错误!', statusCode, request.url))
response.status(statusCode).json(BodyResponse(null, msg, statusCode,exception, request.url))
}
}
......@@ -20,6 +20,6 @@ export class HttpExceptionFilter implements ExceptionFilter<HttpException> {
// message,
// });
// 自定义异常返回体
response.status(status).json(BodyResponse(null, message, status, request.url))
response.status(status).json(BodyResponse(null, message, status,exception, request.url))
}
}
import { HttpExceptionFilter } from './http-exception.filter'
import { ExceptionsFilter } from './exception.filter'
import { ValidateExceptionFilter } from './validate-exception.filter'
export { HttpExceptionFilter, ExceptionsFilter, ValidateExceptionFilter }
import { ArgumentsHost, Catch, ExceptionFilter,HttpStatus } from '@nestjs/common'
import { ValidationError } from 'class-validator';
import { Request, Response } from 'express'
import { BodyResponse } from '../utils'
@Catch(ValidationError)
export class ValidateExceptionFilter implements ExceptionFilter<ValidationError> {
catch(exception: ValidationError, host: ArgumentsHost) {
const ctx = host.switchToHttp();
const response = ctx.getResponse();
const status = HttpStatus.BAD_REQUEST;
console.log(1,exception)
// response
// .status(status)
// .json({
// statusCode: status,
// // message: exception.message,
// });
// // 自定义异常返回体
// response.status(status).json(BodyResponse(null, message, status, request.url))
}
}
import { map } from 'rxjs/operators'
import { Observable } from 'rxjs'
import { BodyResponse, Response } from '../../common/utils'
import { BodyResponse } from '../../common/utils'
import { CallHandler, ExecutionContext, Injectable, NestInterceptor } from '@nestjs/common'
@Injectable()
export class TransformInterceptor<T> implements NestInterceptor<T, Response<T>> {
intercept(context: ExecutionContext, next: CallHandler<T>): Observable<Response<T>> {
return next.handle().pipe(map(data => BodyResponse(data)))
export class TransformInterceptor<T> implements NestInterceptor<T, CommonTypes.IResData> {
intercept(context: ExecutionContext, next: CallHandler<T>): Observable<CommonTypes.IResData> {
return next.handle().pipe(map((data:CommonTypes.IResData) => BodyResponse(data)))
}
}
import { PagesPipe } from './pages-arguments.pipe'
import { ParseIntPipe } from "./parse-int.pipe";
import { ValidationPipe } from "./validation.pipe";
export { PagesPipe,ParseIntPipe,ValidationPipe}
import { PipeTransform, Injectable } from '@nestjs/common'
@Injectable()
export class PagesPipe implements PipeTransform<CommonTypes.IPageIn> {
async transform(value: CommonTypes.IPageIn) {
const { pageIndex, pageSize } = value
const skip = (pageIndex - 1) * pageSize
value.skip = +skip < 0 ? 0 : skip
value.take = +pageSize
return value
}
}
import {
ArgumentMetadata,
HttpException,
HttpStatus,
Injectable,
PipeTransform,
Type,
} from '@nestjs/common';
import { plainToClass } from 'class-transformer';
import { validate } from 'class-validator';
import { ArgumentMetadata,BadRequestException, HttpException, HttpStatus, Injectable, PipeTransform, Type } from '@nestjs/common'
import { plainToClass } from 'class-transformer'
import { validate } from 'class-validator'
@Injectable()
export class ValidationPipe implements PipeTransform<any> {
async transform(value: any, metadata: ArgumentMetadata) {
// tslint:disable-next-line
console.log(value);
const { metatype } = metadata;
console.log(value)
const { metatype } = metadata
if (!metatype || !this.toValidate(metatype)) {
return value;
return value
}
const object = plainToClass(metatype, value);
const errors = await validate(object);
const object = plainToClass(metatype, value)
const errors = await validate(object)
if (errors.length > 0) {
const errObj = {};
errors.forEach(err => {
const {
property,
constraints,
} = err;
errObj[property] = Object.values(constraints);
});
throw new HttpException(
{ message: 'Request params validation failed', error: errObj },
HttpStatus.BAD_REQUEST,
);
const msg = Object.values(errors[0]?.constraints)[0]; // 只需要取第一个错误信息并返回即可
// Logger.error(`Validation failed: ${msg}`);
throw new BadRequestException(`参数验证失败: ${msg}`);
// const errObj = {}
// errors.forEach(err => {
// const { property, constraints } = err
// errObj[property] = Object.values(constraints)
// })
// throw new HttpException({ message: errObj||'Request params validation failed', error: errObj }, HttpStatus.BAD_REQUEST)
}
return value;
return value
}
private toValidate(metatype: Type<any>): boolean {
const types = [String, Boolean, Number, Array, Object];
return !types.find(type => metatype === type);
const types = [String, Boolean, Number, Array, Object]
return !types.find(type => metatype === type)
}
}
import { RESPONSE_CODE, RESPONSE_MSG } from '../enums';
import type { Response } from './types';
import { types } from 'util'
import { RESPONSE_CODE, RESPONSE_MSG } from '../enums'
export const getCurrentTimestamp = (): number=> {
return Date.parse(new Date().toString()) / 1000;
export const getCurrentTimestamp = (): number => {
return Date.parse(new Date().toString()) / 1000
}
/**
/**
* @description: 统一返回体
*/
export const BodyResponse = <T = any>(
data,
msg?: string ,
code?: number,
url?: string
): Response<T> => {
export const BodyResponse: CommonTypes.TBodyResponse = (result, msg, code,error, url) => {
if(msg instanceof Array){
msg = msg.join(';')
}
const { total, data } = result || {}
return {
code:code || RESPONSE_CODE.SUCCESS,
msg:msg || RESPONSE_MSG.SUCCESS,
data,
timestamp: getCurrentTimestamp(),
url,
};
};
export * from './types';
\ No newline at end of file
data,
total,
error,
'timestamp': getCurrentTimestamp(),
'msg': msg || RESPONSE_MSG.SUCCESS,
'code': code || RESPONSE_CODE.SUCCESS
}
}
type ResponseBase = {
code?: number // 状态码
msg?: string // 响应信息
url?: string // 请求接口路径
timestamp: number // 时间戳
}
type pagenation = {
current?: number // 页码
size?: number // 当前页条数
total?: number // 总条数
}
/**
* @description: 全局响应体
*/
export type Response<T = any> = {
data?: T // 业务数据
} & ResponseBase & pagenation
/**
* @description: 分页数据
*/
export type PageResponse<T = any> = {
current?: number // 页码
size?: number // 当前页条数
total?: number // 总条数
data: T[] // 业务数据
} & ResponseBase
import { NestFactory } from '@nestjs/core'
import { DocumentBuilder, SwaggerModule } from '@nestjs/swagger'
import { HttpExceptionFilter } from './common/filters/http-exception.filter'
import { ExceptionsFilter } from './common/filters/exception.filter'
import { HttpExceptionFilter, ExceptionsFilter } from './common/filters'
import { ValidationPipe } from './common/pipes/validation.pipe'
import { LoggingInterceptor } from './common/interceptors/logging.interceptor'
import { AppModule } from './app.module'
......@@ -13,8 +12,9 @@ async function bootstrap() {
// app.use(logger)
// 全局过滤器
app.useGlobalFilters(new HttpExceptionFilter())
app.useGlobalFilters(new ExceptionsFilter())
app.useGlobalFilters(new HttpExceptionFilter())
// app.useGlobalFilters(new ValidateExceptionFilter())
// 全局管道
// app.useGlobalPipes(new ValidationPipe());
......
import { Controller, Get, Query, UseGuards } from '@nestjs/common';
import { ApiTags, ApiBearerAuth } from '@nestjs/swagger';
import { DeviceInfoService } from './device-info.service';
@ApiBearerAuth()
@ApiTags('device-info')
@Controller('/device-info')
export class DeviceInfoController {
constructor(private readonly deviceInfoService: DeviceInfoService) {}
// 查询
@Get()
fetch(@Query() { id }): string {
return this.deviceInfoService.fetch(id);
}
}
import { Module } from '@nestjs/common';
import { DeviceInfoController } from './device-info.controller';
import { DeviceInfoService } from './device-info.service';
@Module({
imports: [],
controllers: [DeviceInfoController],
providers: [DeviceInfoService],
})
export class DeviceInfoModule {}
import { Injectable } from '@nestjs/common';
@Injectable()
export class DeviceInfoService {
fetch(id): string {
return `Hello World! ${id}`;
}
save(message): string {
return `Set Hello Done.${message}`;
}
update(id: string, message: string): string {
return `Update Hello Done. ${id}:${message}`;
}
remove(id: number): string {
return `${id} Record Was Removed.`;
}
}
import { Controller, Get, Post, Body, UseInterceptors, Query } from '@nestjs/common'
import { Controller, Get, Post, Body, UseInterceptors, Query, UsePipes } from '@nestjs/common'
import { DeviceService } from './device.service'
import { TransformInterceptor } from '../../common/interceptors'
import { ResponseDto } from 'src/dto/response.dto'
import { AddDeviceDto, AddDeviceInfoDto } from './dto/device.dto'
import { PagesPipe, ValidationPipe } from '../../common/pipes'
@Controller('device')
@UseInterceptors(TransformInterceptor)
// @UsePipes(new ValidationPipe({transform: true}))
@UsePipes(new ValidationPipe()) // 使用管道验证
export class DeviceController {
constructor(private readonly deviceService: DeviceService) {}
@Get()
@UseInterceptors(TransformInterceptor)
findAll(@Query() { user,mobile,sn,pageindex,pageSize }:Api.Device.QueryDevice):Promise<Api.Device.DeviceInfo[]> {
return this.deviceService.findAll({user,mobile,sn,pageindex,pageSize})
@UsePipes(new PagesPipe())
findAll(@Query() params: DeviceTypes.IQueryDevices): Promise<CommonTypes.IResData> {
return this.deviceService.findAll(params)
}
@Post('/add')
addDevice(@Body() param: AddDeviceDto){
// console.log(param)
return this.deviceService.addDevice(param)
}
@Post('/addInfo')
addDeviceInfo(@Body() param: AddDeviceInfoDto){
// console.log(param)
return this.deviceService.addDeviceInfo(param)
}
@Post()
async create(@Body() param) {
const newParam = { ...param, status: true }
......
......@@ -3,6 +3,7 @@ import { Inject, Injectable, HttpException, HttpStatus } from '@nestjs/common'
// import { InjectRepository } from '@nestjs/typeorm';
// import { Device as DeviceEntity } from '../entities/Device'
import { PrismaService } from 'nestjs-prisma'
import { AddDeviceInfoDto } from './dto/device.dto'
@Injectable()
export class DeviceService {
constructor(
......@@ -12,22 +13,39 @@ export class DeviceService {
private readonly prisma: PrismaService // private connection: Connection,
) {}
async findAll({ user, mobile, sn, pageSize, pageindex }: Api.Device.QueryDevice): Promise<Api.Device.DeviceInfo[]> {
const result = await this.prisma.device.findMany({
// skip,
// take,
async findAll({ user, mobile, sn, skip, take }: DeviceTypes.IQueryDevices): Promise<CommonTypes.IResData<DeviceTypes.IDeviceInfo[]>> {
const where = {
sn: {
contains: sn
},
AND: {
device_info: {
mobile: {
contains: mobile
},
user: {
contains: user
}
}
}
}
const result: DeviceTypes.IDeviceResult[] = await this.prisma.device.findMany({
skip,
take,
select: {
sn: true,
'device_info': {
device_info: {
select: {
user: true,
status: true,
'log_config': {
mobile: true,
merchant_name: true,
log_config: {
select: {
'log_saved_days': true,
'user_fields': {
log_saved_days: true,
user_fields: {
select: {
'log_user_field': {
log_user_field: {
select: {
name: true
}
......@@ -39,33 +57,33 @@ export class DeviceService {
}
}
},
where: {
sn:{
contains: sn
},
AND: {
'device_info': {
mobile: {
contains: mobile
},
user: {
contains: user
}
}
}
}
where
})
const data = result.reduce((pre, cur) => {
const total = await this.prisma.device.count({
where
})
const data: DeviceTypes.IDeviceInfo[] = result.reduce((pre: DeviceTypes.IDeviceInfo[], cur: DeviceTypes.IDeviceResult) => {
pre.push({
sn: cur.sn,
user: cur.device_info?.user,
mobile: cur.device_info?.mobile,
status: cur.device_info?.status,
'log_saved_days': cur.device_info?.log_config?.log_saved_days,
'log_user_fields': cur.device_info?.log_config?.user_fields?.map(item => item.log_user_field.name)
merchant_name: cur.device_info?.merchant_name,
log_saved_days: cur.device_info?.log_config?.log_saved_days,
log_user_fields: cur.device_info?.log_config?.user_fields?.map((item: DeviceTypes.ILogUserFields) => item.log_user_field.name)
})
return pre
}, [])
return data
const resBody: CommonTypes.IResData<DeviceTypes.IDeviceInfo[]> = { total, data }
return resBody
}
async addDevice(device: Omit<DeviceTypes.IDevice,'id'|'create_time'>) {
return await this.prisma.device.create({ data: device })
}
async addDeviceInfo(deviceInfo: AddDeviceInfoDto) {
return await this.prisma.device_info.create({ data: deviceInfo })
}
// async create(user): Promise<DeviceEntity[]> {
......
import { IsString, IsNumber, IsNotEmpty, MaxLength, IsMobilePhone,IsOptional } from 'class-validator'
import { ApiProperty } from '@nestjs/swagger'
export class AddDeviceDto {
@ApiProperty({
type: String,
description: '设备SN',
default: ''
})
@MaxLength(20, { message: '设备SN不能超过20个字符' })
@IsNotEmpty({ message: '设备SN不能为空' })
sn: string
}
/**
* model device_info {
id Int @id @default(autoincrement())
device_id Int @unique(map: "device_id") @default(0)
user String? @db.VarChar(20)
status Int? @db.TinyInt
last_log_upload_time String? @db.VarChar(30)
last_log_remove_time String? @db.VarChar(30)
created_at DateTime @default(now()) @db.Timestamp(0)
updated_at DateTime @default(now()) @db.Timestamp(0)
mobile String? @db.VarChar(20)
merchant_name String? @db.VarChar(50)
log_config log_config?
}
*/
export class AddDeviceInfoDto {
@ApiProperty({
type: Number,
description: '设备信息ID',
default: 0
})
id: number
@ApiProperty({
type: Number,
description: '设备ID',
default: 0
})
@IsNumber({},{ message: '设备ID必须是数字'})
@IsNotEmpty({ message: '设备ID不能为空' })
device_id: number
@ApiProperty({
type: String,
description: '设备用户',
default: ''
})
user: string
@ApiProperty({
type: Number,
description: '设备状态',
default: 0
})
status: number
@ApiProperty({
type: String,
description: '最后一次上传日志的时间',
default: ''
})
last_log_upload_time: string
@ApiProperty({
type: String,
description: '最后一次移除日志的时间',
default: ''
})
last_log_remove_time: string
@ApiProperty({
type: String,
description: '创建时间',
default: ''
})
created_at: string
@ApiProperty({
type: String,
description: '更新时间',
default: ''
})
updated_at: string
@IsMobilePhone('zh-CN',{},{ message: '手机号格式不正确'})
@IsOptional()
@ApiProperty({
type: String,
description: '使用者手机号',
default: ''
})
mobile: string
@ApiProperty({
type: String,
description: '使用者商户名称',
default: ''
})
merchant_name: string
@ApiProperty({
type: Object,
description: '日志配置',
default: {}
})
log_config: {}
}
import {
Controller,
Get,
Post,
Patch,
Query,
Delete,
Body,
Param,
Headers,
UseFilters,
HttpException,
HttpStatus,
ParseIntPipe,
} from '@nestjs/common';
import {
ApiTags,
ApiBearerAuth,
ApiBody,
ApiParam,
} from '@nestjs/swagger';
import { ExceptionService } from './exception.service';
import { HttpExceptionFilter } from '../../common/filters/http-exception.filter';
import { Controller, Get, Post, Patch, Query, Delete, Body, Param, Headers, UseFilters, HttpException, HttpStatus, ParseIntPipe } from '@nestjs/common'
import { ApiTags, ApiBearerAuth, ApiBody, ApiParam } from '@nestjs/swagger'
import { ExceptionService } from './exception.service'
import { HttpExceptionFilter } from '../../common/filters/http-exception.filter'
@ApiBearerAuth()
@ApiTags('exception')
......@@ -33,19 +14,16 @@ export class ExceptionController {
@Get()
fetch(@Query() { id }, @Headers('token') token): string {
if (!id) {
throw new HttpException(
{ status: HttpStatus.BAD_REQUEST, message: '请求参数id 必传', error: 'id is required' },
HttpStatus.BAD_REQUEST,
);
throw new HttpException({ status: HttpStatus.BAD_REQUEST, message: '请求参数id 必传', error: 'id is required' }, HttpStatus.BAD_REQUEST)
}
return this.exceptionService.fetch(id);
return this.exceptionService.fetch(id)
}
// 创建
@Post()
@ApiBody({ description: '填写更新内容' })
save(@Body() { message, id }): string {
return this.exceptionService.save(message);
return this.exceptionService.save(message)
}
// 更新
......@@ -56,12 +34,12 @@ export class ExceptionController {
// !现nest自带部分管道
update(@Param('id', new ParseIntPipe()) id, @Body() { message }): string {
console.log(typeof id)
return this.exceptionService.update(id, message);
return this.exceptionService.update(id, message)
}
// 删除
@Delete()
remove(@Query() { id }): string {
return this.exceptionService.remove(id);
return this.exceptionService.remove(id)
}
}
/**
* 公共命名空间声明
*/
declare namespace CommonTypes{
/**
* 定义一个基本的响应对象接口
*/
type IResponseBase = {
/**
* 状态码
*/
code?: number
/**
* 响应信息
*/
msg?: string | string[]
/**
* 请求接口路径
*/
url?: string ,
error?: any,
/**
* 时间戳
*/
timestamp?: number
}
/**
* 定义一个基本的分页对象接口
*/
interface IPageBase {
/**
* 页码
*/
pageIndex?: number
/**
* 当前页条数
*/
pageSize?: number
}
/**
* 扩展分页对象接口,包括总条数
*/
interface IPagenation extends IPageBase {
/**
* 总条数
*/
total?: number
}
/**
* 响应数据接口,继承自分页对象接口,包含业务数据
*/
interface IResData<T = any> extends IPageBase {
/**
* 业务数据
*/
data?: T
/**
* 总条数
*/
total?: number
}
/**
* 全局响应体接口,继承自分页对象、响应基本对象和响应数据接口
*/
interface IResponse<T> extends IPagenation, IResponseBase {
/**
* 业务数据
*/
data?: T
}
/**
* 扩展分页对象接口,用于传入查询参数,包含附加属性
*/
interface IPageIn extends IPageBase {
[key: string]: any
}
/**
* 定义一个基本的查询对象接口
*/
interface IQueryBase {
/**
* 跳过数量
*/
skip?: number
/**
* 获取数量
*/
take?: number
}
/**
* 定义一个响应体生成函数类型
*
* @param result - 响应数据
* @param msg - 消息
* @param code - 状态码
* @param url - 路径
* @returns 返回给前端的响应体
*/
type TBodyResponse = (result: IResData, msg?: string | string[], code?: number,error?:any, url?: string) => IResponse<IResData<any>>
}
declare namespace DeviceTypes {
/**
* 查询设备信息的查询对象接口
*
* @param user - 用户
* @param mobile - 手机号
* @param sn - 设备号
* @param skip - 可选,跳过的记录数量
* @param take - 可选,获取的记录数量
*/
interface IQueryDevices extends CommonTypes.IQueryBase {
user?: string
mobile?: string
sn?: string
}
interface IDeviceInfoBase {
/**
* 用户
*/
user?: string
/**
* 手机号
*/
mobile?: string
/**
* 商户名称
*/
merchant_name?: string
/**
* 状态
*/
status?: number
/**
* 日志保存天数
*/
log_saved_days?: number
}
/**
* 设备信息接口
*/
interface IDeviceInfo extends IDeviceInfoBase, IDevice {
/**
* 日志用户字段
*/
log_user_fields?: string[]
}
/**
* model device_info {
id Int @id @default(autoincrement())
device_id Int @unique(map: "device_id") @default(0)
user String? @db.VarChar(20)
status Int? @db.TinyInt
last_log_upload_time String? @db.VarChar(30)
last_log_remove_time String? @db.VarChar(30)
created_at DateTime @default(now()) @db.Timestamp(0)
updated_at DateTime @default(now()) @db.Timestamp(0)
mobile String? @db.VarChar(20)
merchant_name String? @db.VarChar(50)
log_config log_config?
}
*/
interface IDeviceInfoInput extends IDeviceInfoBase {
id?: number
last_log_upload_time?: string
last_log_remove_time?: string
device_id?: number
created_at?: number
updated_at?: number
}
/**
* 表示设备结果的接口
*/
interface IDeviceResult extends IDevice {
/**
* 与设备关联的详细信息
*/
device_info: IDeviceInfoRes
}
interface IDevice {
/**
* 设备的唯一标识符
*/
id?: number
/**
* 设备的序列号
*/
sn: string
/**
* 设备创建的时间戳
*/
create_time?: number
}
/**
* 表示设备详细信息的接口
*/
interface IDeviceInfoRes extends IDeviceInfoBase {
/**
* 设备信息的唯一标识符
*/
id?: number
/**
* 设备的唯一标识符(外键)
*/
device_id?: number
/**
* 上次日志上传的时间
*/
last_log_upload_time?: string
/**
* 上次日志移除的时间
*/
last_log_remove_time?: string
/**
* 设备信息创建的时间戳
*/
created_at?: number
/**
* 设备信息更新的时间戳
*/
updated_at?: number
/**
* 与设备关联的日志配置信息
*/
log_config: ILogConfig
}
/**
* 表示日志配置的接口
*/
interface ILogConfig {
/**
* 日志保存的天数
*/
log_saved_days: number
/**
* 日志用户字段的配置信息
*/
user_fields: ILogUserFields[]
}
/**
* 表示日志用户字段的接口
*/
interface ILogUserFields {
/**
* 日志用户字段的详细信息
*/
log_user_field?: ILogUserField
}
/**
* 表示日志用户字段的详细信息的接口
*/
interface ILogUserField {
/**
* 日志用户字段的唯一标识符
*/
id?: number
/**
* 日志用户字段的名称
*/
name: string
}
}
declare namespace Api {
namespace Common {
/**
* @description: 全局响应体
*/
type Response<T = any> = {
code: number // 状态码
data?: T // 业务数据
msg: string // 响应信息
timestamp: number // 时间戳
}
/**
* @description: 分页数据
*/
type PageResponse<T = any> = {
current?: number // 页码
size?: number // 当前页条数
total?: number // 总条数
records: T[] // 业务数据
}
}
namespace Device {
type QueryDevice = {
user?: string // 用户
mobile?: string // 手机号
sn?: string // 设备号
pageindex?: number // 页码
pageSize?: number // 每页条数
}
type DeviceInfo = {
id?: string // 设备id
user?: string // 用户
mobile?: string // 手机号
sn?: string // 设备号
status?: number // 状态
log_saved_days?: number // 日志保存天数
log_user_fields?: string[] // 日志用户字段
}
}
}
http://localhost:3000/device?user=李四1
\ No newline at end of file
//http://localhost:3000/device?pageIndex=1&pageSize=1&user=李四
# POST http://localhost:3000/device/add HTTP/1.1
# content-type: application/json
# {
# "sn":"sn1111211212122"
# }
POST http://localhost:3000/device/addInfo HTTP/1.1
content-type: application/json
{
"device_id":1,
"mobile":"3800138000"
}
\ No newline at end of file
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!