Commit 31ca4c8e by yixinjj

新增文件上传指令响应

1 parent 85d8752f
import { resolve } from 'path' import { resolve } from 'path'
import { Module, MiddlewareConsumer, RequestMethod } from '@nestjs/common' import { Module, MiddlewareConsumer, RequestMethod } from '@nestjs/common'
import { TypeOrmModule } from '@nestjs/typeorm'
import { ScheduleModule } from '@nestjs/schedule' import { ScheduleModule } from '@nestjs/schedule'
import { ConfigModule, ConfigService } from 'nestjs-config' import { ConfigModule, ConfigService } from 'nestjs-config'
import { MailerModule } from '@nest-modules/mailer' import { MailerModule } from '@nest-modules/mailer'
import { StatusMonitorModule } from 'nest-status-monitor' import { StatusMonitorModule } from 'nest-status-monitor'
import statusMonitorConfig from './config/statusMonitor' import statusMonitorConfig from './config/statusMonitor'
import { LoggerMiddleware } from './common/middleware/logger.middleware' import { LoggerMiddleware } from './common/middleware/logger.middleware'
import { TasksModule } from './tasks/tasks.module' // import { TasksModule } from './tasks/tasks.module'
import { AudioModule } from './jobs/audio/audio.module' // import { AudioModule } from './jobs/audio/audio.module'
import { AuthModule } from './modules/auth/auth.module' // import { AuthModule } from './modules/auth/auth.module'
import { HelloModule } from './modules/hello/hello.module' // import { HelloModule } from './modules/hello/hello.module'
import { DeviceModule } from './modules/device/device.module' import { DeviceModule } from './modules/device/device.module'
import { ExceptionModule } from './modules/exception/exception.module' import { ExceptionModule } from './modules/exception/exception.module'
import { RoleGuardModule } from './modules/role-guard/role-guard.module' // import { RoleGuardModule } from './modules/role-guard/role-guard.module'
import { EmailModule } from './modules/email/email.module' // import { EmailModule } from './modules/email/email.module'
// import { UsersModule } from './modules/users/users.module' // import { UsersModule } from './modules/users/users.module'
import { FileModule } from './modules/file/file.module' import { FileModule } from './modules/file/file.module'
import { WsModule } from './modules/ws/ws.module' import { WsModule } from './modules/ws/ws.module'
// import { WsGateway } from './modules/ws/ws.gateway'; // import { WsGateway } from './modules/ws/ws.gateway';
import { SseModule } from './modules/sse/sse.module' // import { SseModule } from './modules/sse/sse.module'
import { LogConfigModule } from './modules/config/config.module'; import { LogConfigModule } from './modules/config/config.module'
import { BroadcastModule } from './modules/broadcast/broadcast.module' import { BroadcastModule } from './modules/broadcast/broadcast.module'
import { EventEmitterModule } from '@nestjs/event-emitter'; import { EventEmitterModule } from '@nestjs/event-emitter'
@Module({ @Module({
imports: [ imports: [
ConfigModule.load(resolve(__dirname, 'config', '**/!(*.d).{ts,js}')), ConfigModule.load(resolve(__dirname, 'config', '**/!(*.d).{ts,js}')),
...@@ -40,26 +39,23 @@ import { EventEmitterModule } from '@nestjs/event-emitter'; ...@@ -40,26 +39,23 @@ import { EventEmitterModule } from '@nestjs/event-emitter';
EventEmitterModule.forRoot(), EventEmitterModule.forRoot(),
// TasksModule, // TasksModule,
// AudioModule, // AudioModule,
AuthModule, // AuthModule,
HelloModule, // HelloModule,
ExceptionModule, ExceptionModule,
RoleGuardModule, // RoleGuardModule,
EmailModule, // EmailModule,
// UsersModule, // UsersModule,
FileModule, FileModule,
SseModule, // SseModule,
WsModule, WsModule,
DeviceModule, DeviceModule,
BroadcastModule, BroadcastModule,
LogConfigModule LogConfigModule
], ]
}) })
export class AppModule { export class AppModule {
configure(consumer: MiddlewareConsumer) { configure(consumer: MiddlewareConsumer) {
// 为 hello 路由添加中间件 // 为 hello 路由添加中间件
consumer consumer.apply(LoggerMiddleware).exclude({ path: 'hello', method: RequestMethod.POST }).forRoutes('hello')
.apply(LoggerMiddleware)
.exclude({ path: 'hello', method: RequestMethod.POST })
.forRoutes('hello')
} }
} }
...@@ -41,9 +41,9 @@ export enum WsAccess { ...@@ -41,9 +41,9 @@ export enum WsAccess {
InValidToken = '无效token', InValidToken = '无效token',
InvalidDeviceId = '无效设备id', InvalidDeviceId = '无效设备id',
IsOnline = '通过验证,设备上线', IsOnline = '通过验证,设备上线',
IsOffline = '设备下线', IsOffline = '设备下线'
} }
export enum WsConnEvents { export enum WsConnEvents {
Connection='connection', Connection = 'connection'
} }
import { ArgumentsHost, Catch, ExceptionFilter, HttpException, HttpStatus } from '@nestjs/common' import { ArgumentsHost, Catch, ExceptionFilter, HttpException, HttpStatus, Logger } from '@nestjs/common'
import { Response, Request } from 'express' import { Response, Request } from 'express'
import { BodyResponse } from '../utils' import { BodyResponse } from '../utils'
...@@ -11,7 +11,9 @@ export class ExceptionsFilter implements ExceptionFilter { ...@@ -11,7 +11,9 @@ export class ExceptionsFilter implements ExceptionFilter {
// 获取响应体 // 获取响应体
const response = ctx.getResponse<Response>() const response = ctx.getResponse<Response>()
const request = ctx.getRequest<Request>() const request = ctx.getRequest<Request>()
console.log(1,exception) Logger.error(exception)
console.log(exception)
// 获取状态码,判断是HTTP异常还是服务器异常 // 获取状态码,判断是HTTP异常还是服务器异常
const statusCode = exception instanceof HttpException ? exception.getStatus() : HttpStatus.INTERNAL_SERVER_ERROR const statusCode = exception instanceof HttpException ? exception.getStatus() : HttpStatus.INTERNAL_SERVER_ERROR
const msg = exception instanceof HttpException? exception.message : '服务器异常' const msg = exception instanceof HttpException? exception.message : '服务器异常'
......
import { ArgumentsHost, Catch, ExceptionFilter, HttpException } from '@nestjs/common' import { ArgumentsHost, Catch, ExceptionFilter, HttpException, Logger } from '@nestjs/common'
import { Request, Response } from 'express' import { Request, Response } from 'express'
import { BodyResponse } from '../utils' import { BodyResponse } from '../utils'
@Catch(HttpException) @Catch(HttpException)
...@@ -8,7 +8,8 @@ export class HttpExceptionFilter implements ExceptionFilter<HttpException> { ...@@ -8,7 +8,8 @@ export class HttpExceptionFilter implements ExceptionFilter<HttpException> {
const response = ctx.getResponse<Response>() const response = ctx.getResponse<Response>()
const request = ctx.getRequest<Request>() const request = ctx.getRequest<Request>()
const status = exception.getStatus() const status = exception.getStatus()
console.log(2,exception) Logger.error(exception)
console.log(exception)
const exceptionRes: any = exception.getResponse() const exceptionRes: any = exception.getResponse()
const { message } = exceptionRes const { message } = exceptionRes
......
import { ArgumentsHost, Catch, ExceptionFilter,HttpStatus } from '@nestjs/common' import { ArgumentsHost, Catch, ExceptionFilter,HttpStatus, Logger } from '@nestjs/common'
import { ValidationError } from 'class-validator'; import { ValidationError } from 'class-validator';
import { Request, Response } from 'express' import { Request, Response } from 'express'
import { BodyResponse } from '../utils' import { BodyResponse } from '../utils'
...@@ -8,7 +8,7 @@ export class ValidateExceptionFilter implements ExceptionFilter<ValidationError> ...@@ -8,7 +8,7 @@ export class ValidateExceptionFilter implements ExceptionFilter<ValidationError>
const ctx = host.switchToHttp(); const ctx = host.switchToHttp();
const response = ctx.getResponse(); const response = ctx.getResponse();
const status = HttpStatus.BAD_REQUEST; const status = HttpStatus.BAD_REQUEST;
console.log(1,exception) Logger.error(exception)
// response // response
// .status(status) // .status(status)
// .json({ // .json({
......
import { ArgumentMetadata,BadRequestException, HttpException, HttpStatus, Injectable, PipeTransform, Type } from '@nestjs/common' import { ArgumentMetadata,BadRequestException, HttpException, HttpStatus, Injectable, Logger, PipeTransform, Type } from '@nestjs/common'
import { plainToClass } from 'class-transformer' import { plainToClass } from 'class-transformer'
import { validate } from 'class-validator' import { validate } from 'class-validator'
@Injectable() @Injectable()
export class ValidationPipe implements PipeTransform<any> { export class ValidationPipe implements PipeTransform<any> {
async transform(value: any, metadata: ArgumentMetadata) { async transform(value: any, metadata: ArgumentMetadata) {
console.log(value)
const { metatype } = metadata const { metatype } = metadata
if (!metatype || !this.toValidate(metatype)) { if (!metatype || !this.toValidate(metatype)) {
return value return value
} }
const object = plainToClass(metatype, value) const object = plainToClass(metatype, value)
const errors = await validate(object) let errors = await validate(object)
if (errors.length > 0) { if (errors.length > 0) {
if(!errors[0].constraints && errors[0].children?.length){
errors = errors[0].children
}
const msg = Object.values(errors[0]?.constraints)[0]; // 只需要取第一个错误信息并返回即可 const msg = Object.values(errors[0]?.constraints)[0]; // 只需要取第一个错误信息并返回即可
// Logger.error(`Validation failed: ${msg}`); Logger.error(`Validation failed: ${msg}`);
throw new BadRequestException(`参数验证失败: ${msg}`); throw new BadRequestException(`参数验证失败: ${msg}`);
// const errObj = {} // const errObj = {}
// errors.forEach(err => { // errors.forEach(err => {
......
...@@ -6,9 +6,10 @@ export default { ...@@ -6,9 +6,10 @@ export default {
storage: diskStorage({ storage: diskStorage({
destination: join(__dirname, `../uploads/${new Date().toLocaleDateString()}`), destination: join(__dirname, `../uploads/${new Date().toLocaleDateString()}`),
filename: (req, file, cb) => { filename: (req, file, cb) => {
const deviceId = req.body.deviceId;
// const name=file.originalname.split('.'); // const name=file.originalname.split('.');
// const filename = `${name[0]}-${new Date().getTime()}.${name.pop()}`//${file.mimetype.split('/')[1]}`; // const filename = `${name[0]}-${new Date().getTime()}.${name.pop()}`//${file.mimetype.split('/')[1]}`;
const path = `${file.originalname.split('.').shift()}-${Date.now()}-${Math.round(Math.random() * 1e10)}${extname(file.originalname)}` const path = `${file.originalname.split('.').shift()}@${deviceId}@${Date.now()}-${Math.round(Math.random() * 1e10)}${extname(file.originalname)}`
return cb(null, path); return cb(null, path);
}, },
}), }),
......
import { ApiProperty } from '@nestjs/swagger'
import { WsMessageType } from '../common/enums'
import { IsDefined, IsNotEmpty, IsNumber, IsString, ValidateIf, ValidateNested } from 'class-validator'
import { Type } from 'class-transformer'
class DataDto {
@ApiProperty({
type: String,
description: '命令类型'
})
@IsString({ message: '命令为必填参数' })
@IsNotEmpty({ message: '命令不能为空' })
readonly order: string
@ApiProperty({
description: '下发的参数',
})
readonly payload: any
}
export class BroadcastDto {
@ApiProperty({
type: WsMessageType,
description: '事件类型: private-私有消息,system-系统消息',
default: WsMessageType.Private
})
@IsNotEmpty({ message: '事件类型不能为空' })
readonly event: WsMessageType
@ValidateIf(o => o.event === WsMessageType.Private)
@IsDefined({ message: '发送私有消息时,device_id是必填的' })
@IsNumber({},{ message: 'device_id必须是数字'})
@ApiProperty({
type: Number,
description: '设备号,私发信息必填',
default: ''
})
readonly device_id: number
@IsNotEmpty({ message: '消息不能为空' })
@ApiProperty({ description: '要发送的数据' })
@ValidateNested()
@Type(() => DataDto)
readonly data: DataDto
}
export * from './broadcast.dto'
export * from './config.dto'
export * from './device.dto'
export * from './response.dto'
import { Controller,Post,Body ,UseInterceptors} from '@nestjs/common' import { Controller, Post, Body, UseInterceptors, UsePipes } from '@nestjs/common'
import { BroadcastService } from './broadcast.service' import { BroadcastService } from './broadcast.service'
import { TransformInterceptor } from '../../common/interceptors' import { TransformInterceptor } from '../../common/interceptors'
import { WsGateway } from '../ws/ws.gateway'; import { WsGateway } from '../ws/ws.gateway'
import { BroadcastDto } from '../../dto'
import { ValidationPipe } from '../../common/pipes'
@Controller('broadcast') @Controller('broadcast')
@UseInterceptors(TransformInterceptor) @UseInterceptors(TransformInterceptor)
@UsePipes(new ValidationPipe()) // 使用管道验证
export class BroadcastController { export class BroadcastController {
constructor(private readonly broadcastService: BroadcastService, constructor(
private readonly broadcastService: BroadcastService,
private readonly wsGateway: WsGateway private readonly wsGateway: WsGateway
){} ) {}
//写一个message方法 接收params参数 然后调用broadcastService的message方法 //写一个message方法 接收params参数 然后调用broadcastService的message方法
@Post('/message') @Post('/message')
async message(@Body() params):Promise<any>{ async message(@Body() params: BroadcastDto): Promise<any> {
return this.wsGateway.send(params) return this.wsGateway.send(params)
} }
} }
import { Controller, Get, Post, Body, UseInterceptors, Query, UsePipes } from '@nestjs/common' import { Controller, Get, Post, Body, UseInterceptors, Query, UsePipes } from '@nestjs/common'
import { DeviceService } from './device.service' import { DeviceService } from './device.service'
import { TransformInterceptor } from '../../common/interceptors' import { TransformInterceptor } from '../../common/interceptors'
import { AddDeviceDto, AddDeviceInfoDto } from '../../dto/device.dto' import { AddDeviceDto, AddDeviceInfoDto } from '../../dto'
import { PagesPipe, ValidationPipe } from '../../common/pipes' import { PagesPipe, ValidationPipe } from '../../common/pipes'
import { OnEvent } from '@nestjs/event-emitter' import { OnEvent } from '@nestjs/event-emitter'
import { WsConnEvents } from '../../common/enums' import { WsConnEvents } from '../../common/enums'
......
import { Controller, Post, UploadedFile, UseInterceptors, Get, Res } from '@nestjs/common' import { Controller, Post, UploadedFile, UseInterceptors, Get, Res, Req } from '@nestjs/common'
import { Response } from 'express'
import { FileInterceptor } from '@nestjs/platform-express' import { FileInterceptor } from '@nestjs/platform-express'
import { FileService } from './file.service' import { FileService } from './file.service'
import { Response, Request } from 'express'
import { FileMimeTypeFilter } from '../../common/filters' import { FileMimeTypeFilter } from '../../common/filters'
import { UploadFile } from '../../common/decorators' import { UploadFile } from '../../common/decorators'
...@@ -10,9 +10,9 @@ export class FileController { ...@@ -10,9 +10,9 @@ export class FileController {
constructor(private readonly fileService: FileService) {} constructor(private readonly fileService: FileService) {}
@Post('upload') @Post('upload')
@UseInterceptors(FileInterceptor('file')) @UploadFile('file', { fileFilter: FileMimeTypeFilter('text/plain'), limits: { fileSize: 1024 * 1024 * 100 } })
@UploadFile('file', { fileFilter: FileMimeTypeFilter('text/plain') }) upload(@UploadedFile() file: Express.Multer.File, @Req() req: Request) {
upload(@UploadedFile() file: Express.Multer.File) { console.log(req.body.deviceId)
this.fileService.upload(file) this.fileService.upload(file)
return file return file
} }
......
import { Injectable } from '@nestjs/common'; import { Injectable } from '@nestjs/common';
import { tar } from 'compressing'; import { tar } from 'compressing';
import { ConfigService } from 'nestjs-config'; import { ConfigService } from 'nestjs-config';
import * as fs from 'fs';
import * as path from 'path';
@Injectable() @Injectable()
export class FileService { export class FileService {
...@@ -16,4 +18,14 @@ export class FileService { ...@@ -16,4 +18,14 @@ export class FileService {
await tarStream.addEntry(uploadDir); await tarStream.addEntry(uploadDir);
return { filename: 'hello-world.tar', tarStream }; return { filename: 'hello-world.tar', tarStream };
} }
moveFile(sourcePath: string, destinationPath: string): Promise<void> {
return new Promise((resolve, reject) => {
const rs = fs.createReadStream(sourcePath);
const ws = fs.createWriteStream(destinationPath);
rs.on('error', reject);
ws.on('error', reject);
ws.on('finish', resolve);
rs.pipe(ws);
});
}
} }
...@@ -110,7 +110,7 @@ export class WsGateway implements WsTypes.WebSocketGateway<Server, Observable<Ws ...@@ -110,7 +110,7 @@ export class WsGateway implements WsTypes.WebSocketGateway<Server, Observable<Ws
this.wsService.resetClients() this.wsService.resetClients()
} }
public send(payload: WsTypes.MessageBody): Promise<any> { public send(payload: WsTypes.MessageBody<WsTypes.WsMessageData<string>,WsMessageType>): Promise<any> {
if (payload.event === WsMessageType.Private) { if (payload.event === WsMessageType.Private) {
return this.wsService.sendPrivateMessage(payload) return this.wsService.sendPrivateMessage(payload)
} else { } else {
......
...@@ -76,7 +76,7 @@ export class WsService { ...@@ -76,7 +76,7 @@ export class WsService {
* @param messagePath 发布地址 * @param messagePath 发布地址
* @param response 响应数据 * @param response 响应数据
*/ */
async sendPublicMessage(payload: WsTypes.MessageBody) { async sendPublicMessage(payload: WsTypes.MessageBody<WsTypes.WsMessageData<string>>) {
console.log('websocket send', payload) console.log('websocket send', payload)
const res = this.server?.emit(WsMessageType.System, payload.data) const res = this.server?.emit(WsMessageType.System, payload.data)
if (!res) { if (!res) {
...@@ -91,14 +91,14 @@ export class WsService { ...@@ -91,14 +91,14 @@ export class WsService {
* @param response 响应数据 * @param response 响应数据
* @param deviceId 接收者设备号 * @param deviceId 接收者设备号
*/ */
async sendPrivateMessage(payload: WsTypes.MessageBody) { async sendPrivateMessage(payload: WsTypes.MessageBody<WsTypes.WsMessageData<string>>) {
console.log('websocket send', payload) console.log('websocket send', payload)
if (!payload.device_id) throw new HttpException({ status: HttpStatus.BAD_REQUEST, message: '请求参数employeeId 必传', error: 'deviceId is required' }, HttpStatus.BAD_REQUEST) if (!payload.device_id) throw new HttpException({ status: HttpStatus.BAD_REQUEST, message: '请求参数employeeId 必传', error: 'deviceId is required' }, HttpStatus.BAD_REQUEST)
const client = this.server.sockets.sockets.get(this.clientIds.get(payload.device_id)) const client = this.server.sockets.sockets.get(this.clientIds.get(payload.device_id))
const res = client?.emit(WsMessageType.Private, payload.data) const res = client?.emit(WsMessageType.Private, payload.data)
if (!res) { if (!res) {
Logger.log('websocket send error', payload) Logger.log('websocket send error', payload)
throw new HttpException({ status: HttpStatus.BAD_REQUEST, message: `发送失败,客户端:${payload.device_id}不在线`, error: 'send error' }, HttpStatus.BAD_REQUEST) throw new HttpException({ status: HttpStatus.BAD_REQUEST, message: `发送失败,客户端:(设备号->${payload.device_id}) 不在线`, error: 'send error' }, HttpStatus.BAD_REQUEST)
} }
} }
} }
/**
* 公共命名空间声明
*/
declare module CommonTypes {
/** /**
* 公共命名空间声明 * 定义一个基本的响应对象接口
*/ */
declare module CommonTypes{ type IResponseBase = {
/** /**
* 定义一个基本的响应对象接口 * 状态码
*/ */
type IResponseBase = { code?: number
/** /**
* 状态码 * 响应信息
*/ */
code?: number msg?: string | string[]
/**
* 响应信息
*/
msg?: string | string[]
/**
* 请求接口路径
*/
url?: string ,
error?: any,
/**
* 时间戳
*/
timestamp?: number
}
/** /**
* 定义一个基本的分页对象接口 * 请求接口路径
*/ */
interface IPageBase { url?: string
/** error?: any
* 页码
*/
pageIndex?: number
/**
* 当前页条数
*/
pageSize?: number
}
/** /**
* 扩展分页对象接口,包括总条数 * 时间戳
*/ */
interface IPagenation extends IPageBase { timestamp?: number
/** }
* 总条数 /**
*/ * 定义一个基本的分页对象接口
total?: number */
} interface IPageBase {
/** /**
* 响应数据接口,继承自分页对象接口,包含业务数据 * 页码
*/ */
interface IResData<T = any> extends IPageBase { pageIndex?: number
/**
* 业务数据
*/
data?: T
/**
* 总条数
*/
total?: number
}
/** /**
* 全局响应体接口,继承自分页对象、响应基本对象和响应数据接口 * 当前页条数
*/ */
interface IResponse<T> extends IPagenation, IResponseBase { pageSize?: number
/** }
* 业务数据 /**
*/ * 扩展分页对象接口,包括总条数
data?: T */
} interface IPagenation extends IPageBase {
/** /**
* 扩展分页对象接口,用于传入查询参数,包含附加属性 * 总条数
*/ */
interface IPageIn extends IPageBase { total?: number
[key: string]: any }
} /**
* 响应数据接口,继承自分页对象接口,包含业务数据
*/
interface IResData<T = any> extends IPageBase {
/** /**
* 定义一个基本的查询对象接口 * 业务数据
*/ */
interface IQueryBase { data?: T
/**
* 跳过数量
*/
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>> total?: number
type Optional<T, K extends keyof T> = Omit<T, K> & Required<Pick<T, K>>
} }
/**
* 全局响应体接口,继承自分页对象、响应基本对象和响应数据接口
*/
interface IResponse<T> extends IPagenation, IResponseBase {
/**
* 业务数据
*/
data?: T
}
/**
* 扩展分页对象接口,用于传入查询参数,包含附加属性
*/
// interface IPageIn extends IPageBase {
// [key: string]: any
// }
type IPageIn = IPageBase & TObj
/**
* 定义一个基本的查询对象接口
*/
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>>
type Optional<T, K extends keyof T> = Omit<T, K> & Required<Pick<T, K>>
type TObj = { [key: string]: any }
}
...@@ -6,9 +6,9 @@ declare module WsTypes { ...@@ -6,9 +6,9 @@ declare module WsTypes {
} }
type WsMsgType = 'private' | 'system' type WsMsgType = 'private' | 'system'
type MessageBody<T = WsMsgType> = { type MessageBody<U,T = WsMsgType> = {
event: T event: T
data: any data: U
} & (T extends 'private' ? IPrivateData : Partial<IPrivateData>) } & (T extends 'private' ? IPrivateData : Partial<IPrivateData>)
interface IPrivateData { interface IPrivateData {
...@@ -26,4 +26,10 @@ declare module WsTypes { ...@@ -26,4 +26,10 @@ declare module WsTypes {
message: U message: U
} }
type LoginValidate<T> = { isValidate: boolean; errMsg: T } type LoginValidate<T> = { isValidate: boolean; errMsg: T }
type MessageData<T, U = CommonTypes.TObj> = {
order: T | string
payload: U
}
type WsMessageData<T> = MessageData<T>
} }
...@@ -27,15 +27,16 @@ ...@@ -27,15 +27,16 @@
// eventSource.onmessage = ({ data }) => { // eventSource.onmessage = ({ data }) => {
// console.log(111,data) // console.log(111,data)
// }; // };
// const fileInput = document.querySelector('#fileInput'); const fileInput = document.querySelector('#fileInput');
// // const chunkSize = 20 * 1024; // const chunkSize = 20 * 1024;
// fileInput.onchange = async function () { fileInput.onchange = async function () {
// const file = fileInput.files[0]; const file = fileInput.files[0];
// console.log(file); console.log(file);
// const data = new FormData(); const data = new FormData();
// data.append('file', file); data.append('file', file);
// axios.post('http://localhost:3000/file/upload', data); axios.post('http://localhost:3000/file/upload', data);
}
// const chunks = []; // const chunks = [];
// let startPos = 0; // let startPos = 0;
// while(startPos < file.size) { // while(startPos < file.size) {
...@@ -52,26 +53,26 @@ ...@@ -52,26 +53,26 @@
// } // }
const socket = io('http://192.168.1.129:8080', { // const socket = io('http://192.168.1.129:8080', {
auth: { token: '123456', deviceId: 12 }, // auth: { token: '123456', deviceId: 12 },
}); // });
socket.on('connect', function () { // socket.on('connect', function () {
console.log('Connected'); // console.log('Connected');
console.log(socket) // console.log(socket)
//socket.emit('private', { test: 'test' }); // //socket.emit('private', { test: 'test' });
// socket.emit('system', 0, response => // // socket.emit('system', 0, response =>
// console.log('Identity:', response), // // console.log('Identity:', response),
// ); // // );
}); // });
socket.on('private', function (data) { // socket.on('private', function (data) {
console.log('event', data); // console.log('event', data);
}); // });
socket.on('system', function (data) { // socket.on('system', function (data) {
console.log('消息', data); // console.log('消息', data);
}); // });
socket.on('disconnect', function () { // socket.on('disconnect', function () {
console.log('Disconnected'); // console.log('Disconnected');
}); // });
</script> </script>
</body> </body>
......
...@@ -21,23 +21,26 @@ ...@@ -21,23 +21,26 @@
# POST http://localhost:3000/broadcast/message HTTP/1.1 POST http://localhost:3000/broadcast/message HTTP/1.1
# content-type: application/json content-type: application/json
# { {
# "event":"private", "event":"private",
# "device_id":1, "device_id":12,
# "data":{ "data":{
# "message":"hello limin" "order":"logs",
# } "payload":{
# } "message":"log message"
}
}
}
# http://localhost:3000/config?device_id=2 # http://localhost:3000/config?device_id=2
POST http://localhost:3000/config/add HTTP/1.1 # POST http://localhost:3000/config/add HTTP/1.1
content-type: application/json # content-type: application/json
{ # {
"device_id":1, # "device_id":1,
"log_saved_days":8, # "log_saved_days":8,
"user_fields":[1,2,3,4] # "user_fields":[1,2,3,4]
} # }
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!