lrf 2 gadi atpakaļ
vecāks
revīzija
573995acfa
2 mainītis faili ar 39 papildinājumiem un 2 dzēšanām
  1. 11 0
      src/entity/chat/needSend.entity.ts
  2. 28 2
      src/socket/ws.controller.ts

+ 11 - 0
src/entity/chat/needSend.entity.ts

@@ -0,0 +1,11 @@
+import { modelOptions, prop } from '@typegoose/typegoose';
+import { BaseModel } from 'free-midway-component';
+@modelOptions({
+  schemaOptions: { collection: 'needSend' },
+})
+export class NeedSend extends BaseModel {
+  @prop({ required: false, index: true, zh: '接收人' })
+  to: string;
+  @prop({ required: false, index: false, zh: '消息' })
+  msg: object;
+}

+ 28 - 2
src/socket/ws.controller.ts

@@ -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));
   }
   /**