|
@@ -5,13 +5,19 @@ import get = require('lodash/get');
|
|
|
import { Application } from '@midwayjs/ws';
|
|
|
import last = require('lodash/last');
|
|
|
import { Types } from 'mongoose';
|
|
|
-const ObjectId = Types.ObjectId
|
|
|
+const ObjectId = Types.ObjectId;
|
|
|
+import { NeedSend } from '../entity/chat/needSend.entity';
|
|
|
+import { ReturnModelType } from '@typegoose/typegoose';
|
|
|
+import { InjectEntityModel } from '@midwayjs/typegoose';
|
|
|
+
|
|
|
@WSController('*/ws/*')
|
|
|
export class WsSocketController {
|
|
|
@Inject()
|
|
|
ctx: Context;
|
|
|
@App('webSocket')
|
|
|
wsApp: Application;
|
|
|
+ @InjectEntityModel(NeedSend)
|
|
|
+ model: ReturnModelType<typeof NeedSend>;
|
|
|
|
|
|
@OnWSConnection()
|
|
|
async onConnectionMethod(socket: Context, request: http.IncomingMessage) {
|
|
@@ -23,12 +29,28 @@ export class WsSocketController {
|
|
|
// 最后一个是该websocket实例,赋上token
|
|
|
const client = last(acs);
|
|
|
client.token = token;
|
|
|
+ await this.checkNeedSend(client);
|
|
|
+ }
|
|
|
+ /**
|
|
|
+ * 给对象补发 未发送出去的消息
|
|
|
+ * @param client ws连接实例
|
|
|
+ */
|
|
|
+ async checkNeedSend(client) {
|
|
|
+ const to = get(client, 'token');
|
|
|
+ if (!to) return;
|
|
|
+ const list = await this.model.find({ to }).lean();
|
|
|
+ for (const i of list) {
|
|
|
+ const { to, msg } = i;
|
|
|
+ await this.toSend(msg, to);
|
|
|
+ await this.model.deleteOne({ _id: i._id });
|
|
|
+ }
|
|
|
}
|
|
|
|
|
|
// 获取信息
|
|
|
@OnWSMessage('message')
|
|
|
async gotMessage(data: Buffer) {
|
|
|
// const msg = data.toString();
|
|
|
+ return '(╯‵□′)╯︵┻━┻';
|
|
|
}
|
|
|
|
|
|
@OnWSDisConnection()
|
|
@@ -42,7 +64,11 @@ export class WsSocketController {
|
|
|
*/
|
|
|
async toSend(data: object, token) {
|
|
|
const clients = this.getClient(token);
|
|
|
- if (!clients) return;
|
|
|
+ if (!clients) {
|
|
|
+ // 存储到待发送表中
|
|
|
+ await this.model.create({ to: token, msg: data });
|
|
|
+ return;
|
|
|
+ }
|
|
|
clients.send(JSON.stringify(data));
|
|
|
}
|
|
|
/**
|