home.js 1.66 KB
Newer Older
wuhao's avatar
wuhao committed
1 2 3 4 5 6 7 8 9 10
/*
 * @Author: wuhao930406 1148547900@qq.com
 * @Date: 2023-08-03 16:51:19
 * @LastEditors: wuhao930406 1148547900@qq.com
 * @LastEditTime: 2023-08-03 17:23:07
 * @FilePath: /socketio_middleware/app/controller/home.js
 * @Description: 
 * 
 * Copyright (c) 2023 by ${git_name_email}, All Rights Reserved. 
 */
wuhao's avatar
wuhao committed
11 12
/* eslint-disable eqeqeq */
/* eslint-disable array-callback-return */
wuhao's avatar
wuhao committed
13 14 15 16 17 18 19 20 21 22 23 24 25
'use strict';

const { Controller } = require('egg');

class HomeController extends Controller {
  async index() {
    const { ctx } = this;
    ctx.body = 'hi, egg';
  }

  async postmsg() {
    const { ctx, app } = this;

wuhao's avatar
wuhao committed
26 27
    const { id, msg, mutiplemsg } = ctx.request.body;
    if (!id && !mutiplemsg) {
wuhao's avatar
wuhao committed
28 29 30 31 32 33 34 35 36 37 38
      ctx.body = {
        code: 0,
        success: true,
        data: ctx.request.body,
      };
      return;
    }

    const clients = app.io.sockets.sockets;
    // query中的id为 用户id  io可以直接emit
    Object.values(clients)?.map(io => {
wuhao's avatar
wuhao committed
39 40 41 42 43 44 45 46 47 48 49 50
      const key = io?.handshake?.query?.id;
      if (mutiplemsg) {
        mutiplemsg?.map(it => {
          console.log('====================================');
          console.log(it);
          console.log('====================================');
          if (it?.id == key) {
            io.emit('message', it?.msg);
          }
        });
      } else {
        const index = id.indexOf(key);
wuhao's avatar
wuhao committed
51
        console.log(io);
wuhao's avatar
wuhao committed
52 53 54 55 56 57
        if (Array.isArray(id) && index !== -1) {
          io.emit('message', msg);
        } else if (key === id) {
          io.emit('message', msg);
        }
        return io;
wuhao's avatar
wuhao committed
58 59 60 61 62 63 64 65 66 67 68 69
      }
    });

    ctx.body = {
      code: 0,
      success: true,
      data: ctx.request.body,
    };
  }
}

module.exports = HomeController;