<

1. 初始化项目 #

egg-init zfchat-api --type=simple

2. 支持socket.io #

2.1 安装egg-socket.io #

cnpm i egg-socket.io -S

2.2 安装启动插件 #

config\plugin.js

exports.io = {
    enable:true,
    package:'egg-socket.io'
}

2.2 配置路由 #

app\router.js

'use strict';

/**
 * @param {Egg.Application} app - egg application
 */
module.exports = app => {
  //io 你可以把它当成 require('socket.io')
  const { router, controller, io } = app;
  router.get('/', controller.home.index);
  //当服务器收到客户端的addMessage事件之后,会交给addMessage方法来处理
  //向服务器发射一个新的消息,并且让服务器广播给所有的客户端
  io.route('addMessage', io.controller.room.addMessage);
  //获取所有的历史消息
  io.route('getAllMessages', io.controller.room.getAllMessages);
  //注册或者登录
  router.post('/login', controller.user.login);
  //验证用户身份
  router.post('/validate', controller.user.validate);
  //创建新的房间
  router.post('/createRoom', controller.rooms.createRoom);
  //返回所有的房间列表
  router.get('/getAllRooms', controller.rooms.getAllRooms);
};

2.3 配置控制器 #

app\io\controller\room.js

const { Controller } = require('egg');
class RoomController extends Controller {
    async addMessage() {
        let { ctx, app } = this;
        //{user,room,content}
        let message = ctx.args[0];
        let doc = await ctx.model.Message.create(message);
        doc = await ctx.model.Message.findById(doc._id).populate('user');
        //此入应该是向某个房间内广播 
        app.io.emit('messageAdded', doc.toJSON());
    }
    async getAllMessages() {
        let { ctx, app } = this;
        let room = ctx.args[0];
        let messages = await ctx.model.Message.find({ room }).populate('user').sort({ createAt: -1 }).limit(20);
        ctx.socket.emit('allMessages', messages.reverse());
    }
}
module.exports = RoomController;

2.4 配置插件 #

  config.io = {
    namespace: {
      "/": {
        connectionMiddleware: ["connect"],
        packetMiddleware:[]
      }
    }
  }

2.5 编写中间件 #

const SYSTEM = {
    name: '系统',
    email: 'admin@126.com',
    avatar: 'http://www.gravatar.com/avatar/1e6fd8e56879c84999cd481255530592'
}
module.exports = app => {
    return async function (ctx, next) {
        const { app, socket, query: { token, room } } = ctx;
        if (token && token != '') {
            const user = app.jwt.verify(token, app.config.jwt.secret);
            if (user) {
                const id = socket.id;
                const nsp = app.io;
                await ctx.model.User.findByIdAndUpdate(user._id, { $set: { online: true, room } });
                socket.join(room);
                socket.broadcast.to(room).emit('online', {
                    user: SYSTEM,
                    content: `用户${user.name}加入聊天室`
                });
                await next();
                await ctx.model.User.findByIdAndUpdate(user._id, { $set: { online: false, room: null } });
                socket.leave(room);
                socket.broadcast.to(room).emit('offline', {
                    user: SYSTEM,
                    content: `用户${user.name}离开聊天室`
                });
            } else {
                socket.emit('needLogin');
            }

        } else {
            socket.emit('needLogin');
        }
    }
}

2.6 配置脚本 #

框架是以 Cluster 方式启动的,而 socket.io 协议实现需要 sticky 特性支持,否则在多进程模式下无法正常工作。 修改 package.json 中 npm scripts 脚本:

{
  "scripts": {
    "dev": "egg-bin dev --sticky",
    "start": "egg-scripts start --sticky"
  }
}

2.7 测试 #

server\server.js

var express = require('express');
var app = express();
var path = require('path');
var server = require('http').createServer(app);
app.use(express.static(path.join(__dirname, 'public')));
var io = require('socket.io')(server);
var port = process.env.PORT || 3000;

server.listen(port, () => {
    console.log('Server listening at port %d', port);
});

server\public\index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
    <button onclick="send()">发送</button>
    <script src="/socket.io/socket.io.js"></script>
    <script>
        let socket = io('http://localhost:7001/');
        socket.on('connect', function () {
            console.log('连接成功');
            socket.emit('getAllMessages');
        });
        socket.on('messageAdded', function (message) {
            console.log(message);
        });
        socket.on('allMessages', function (messages) {
            console.log(messages);
        });
        socket.on('online', function (message) {
            console.log(message);
        });
        socket.on('offline', function (message) {
            console.log(message);
        });
        function send() {
            socket.emit('addMessage', { content: '你好' });
        }
    </script>
</body>

</html>

3.支持mongoose #

3.1 安装 #

cnpm i egg-mongoose --save

3.2 启动插件 #

config\plugin.js

exports.mongoose = {
    enable: true,
    package: 'egg-mongoose'
}

3.3 配置插件 #

config\config.default.js

exports.mongoose = {
  client: {
    url: 'mongodb://127.0.0.1/zfchat',
    options: {},
  },
};

3.4 配置消息模型 #

module.exports = app => {
    const mongoose = app.mongoose;
    const Schema = mongoose.Schema;
    const ObjectId = Schema.Types.ObjectId;
    const MessageSchema = new Schema({
        content: String,
        user: {
            type: ObjectId,
            ref: 'User'
        },
        room: {
            type: ObjectId,
            ref: 'Room'
        },
        createAt: { type: Date, default: Date.now }
    });
    return mongoose.model('Message', MessageSchema);
}

4. egg-jwt #

4.1 安装egg-jwt #

cnpm i egg-jwt -S

4.2 启用egg-jwt #

exports.jwt = {
    enable:true,
    package:'egg-jwt'
}

4.3 配置jwt #

config.jwt = {
   secret: 'zfpx'
}
config.security = {
   csrf: false
}

5. egg-cors #

5.1 安装egg-cors #

cnpm i egg-cors -S

5.2 启用egg-cors #

exports.cors={
    enable: true,
    package:'egg-cors'
}

5.3 配置egg-cors #

config.security={
    domainWhiteList:['http://localhost:3000'],
    csrf:false
  }

6. 实现用户登录 #

6.1 注册模型 #

module.exports = app => {
    let mongoose = app.mongoose;
    let Schema = mongoose.Schema;
    let ObjectId = Schema.Types.ObjectId;
    let UserSchema = new Schema({
        name: String,
        email: String,
        avatar: String,
        online: { type: Boolean, default: false },
        room: {
            type: ObjectId,
            ref: 'Room'
        },
        createAt: { type: Date, default: Date.now }
    });
    return mongoose.model('User', UserSchema);
}

6.2 添加路由规则 #

app\router.js

router.post('/login', controller.user.login);
router.post('/validate', controller.user.validate);

6.3 控制器 #

app\controller\base.js

let { Controller } = require('egg');
class BaseController extends Controller {
    async success(data) {
        this.ctx.body = {
            code: 0,  //0表示成功
            data
        }
    }
    async error(error) {
        this.ctx.body = {
            code: 1,  //1表示失败
            error
        }
    }
}
module.exports = BaseController;

6.4 添加用户控制器 #

gravatar

cnpm i gravatar -S

\app\controller\user.js

let BaseController = require('./base');
let gravatar = require('gravatar')
// post {email:'zfpx@126.com'} jwt
class UserController extends BaseController {
    async login() {
        const { app, ctx } = this;
        let user = ctx.request.body;
        let doc = await ctx.model.User.findOne({ email: user.email });
        if (!doc) {//如果此邮件已经存在,则认为直接可以登录
            user.name = user.email.split('@')[0];//把邮件的前半部分作为用户名
            user.avatar = gravatar.url(user.email);//通过邮箱拿到头像的图片地址
            doc = await ctx.model.User.create(user);//返回一个保存后的对象
        }
        let token = app.jwt.sign(doc.toJSON(), app.config.jwt.secret);
        this.success(token);
    }
    //当第一次用户登录之后,服务器会把 token返回给客户端,客户端需要保存在到sessionStorage localStorage cookie
    //下次再访问服务器的时候要把token传给服务器(放在请求头,请求体,cookie)
    async validate() {
        const { app, ctx } = this;
        let { token } = ctx.request.body;
        try {
            let user = app.jwt.verify(token, app.config.jwt.secret);
            this.success(user);
        } catch (error) {
            this.error('用户验证失败');
        }
    }
}
module.exports = UserController;

6.5 注册结果 #

{"code":0,"data":"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJlbWFpbCI6IjFAMS5jb20iLCJpYXQiOjE1MjcyNTY0NzF9.2tVGRzHLh75oDKbdc7WHciM80JeW3y2Pqu9WKdjeGGU"}

7.实现房间管理功能 #

7.1 注册模型 #

module.exports = app => {
    let mongoose = app.mongoose;
    let Schema = mongoose.Schema;
    let RoomSchema = new Schema({
        name: String,
        createAt: { type: Date, default: Date.now }
    });
    return mongoose.model('Room', RoomSchema);
}

7.2 配置路由 #

router.post('/addRoom', controller.rooms.addRoom);//添加房间
router.post('/getAllRooms', controller.rooms.getAllRooms);//获取所有的房间

7.3 Rooms控制器 #

app\controller\rooms.js

let BaseController = require('./base');
class RoomsController extends BaseController {
    async createRoom() {
        const { ctx, app } = this;
        let room = ctx.request.body;
        let doc = await ctx.model.Room.findOne({ name: room.name });
        if (doc) {
            this.error('房间已经存在!');
        } else {
            doc = await ctx.model.Room.create(room);
            this.success(doc.toJSON());
        }
    }
    async getAllRooms() {
        const { ctx, app } = this;
        let rooms = await ctx.model.Room.find();
        rooms = rooms.map(room => room.toJSON());
        for (let i = 0; i < rooms.length; i++) {
            let users = await ctx.model.User.find({ room: rooms[i]._id });
            rooms[i].users = users.map(user => user.toJSON())
        }
        this.success(rooms);
    }
}
module.exports = RoomsController;

参考 #