Commit 2ad1654c authored by huanglu's avatar huanglu

feat: 优化socket,并增加群聊功能

parent c8fb0d60
# hackernews-async-ts ## api
[Hacker News](https://news.ycombinator.com/) showcase using typescript && egg
## QuickStart
### Development
```bash
$ npm i
$ npm run dev
$ open http://localhost:7001/
```
Don't tsc compile at development mode, if you had run `tsc` then you need to `npm run clean` before `npm run dev`.
### Deploy
```bash
$ npm run tsc
$ npm start
```
### Npm Scripts
- Use `npm run lint` to check code style
- Use `npm test` to run unit test
- se `npm run clean` to clean compiled js at development mode once
### Requirement
- Node.js 8.x
- Typescript 2.8+
import { Application } from 'egg';
export default (app: Application) => {
const { router } = app;
router.post('/account/login', app.controller.account.login);
};
import { Controller } from 'egg';
export default class extends Controller {
async login() {
const { ctx } = this;
const result = await ctx.service.account.login();
ctx.body = result;
}
}
import { Controller } from 'egg';
export default class HomeController extends Controller {
public async index() {
const { ctx } = this;
ctx.body = await ctx.service.home.sayHi('egg');
}
}
import { Controller } from 'egg'; import { Controller } from 'egg';
export default class HomeController extends Controller { export default class HomeController extends Controller {
public async queryList() {
const { ctx } = this;
ctx.body = await ctx.service.socket.queryRooms();
}
public async login() {
this.ctx.body = await this.ctx.service.socket.login();
}
public async createRoom() { public async createRoom() {
const { ctx } = this; const { ctx } = this;
ctx.body = await ctx.service.socket.createRoom(); ctx.body = await ctx.service.socket.createRoom();
...@@ -11,8 +21,8 @@ export default class HomeController extends Controller { ...@@ -11,8 +21,8 @@ export default class HomeController extends Controller {
ctx.body = await ctx.service.socket.joinRoom(); ctx.body = await ctx.service.socket.joinRoom();
} }
public async queryList() { async leaveRoom() {
const { ctx } = this; const { ctx } = this;
ctx.body = await ctx.service.socket.queryRooms(); ctx.body = await ctx.service.socket.leaveRoom();
} }
} }
export default { export default {
parseMsg(action: string, payload = {}, metadata = {}) { // 处理成功响应
const meta = Object.assign({}, { success(res: any, msg = '请求成功') {
timestamp: Date.now(),
}, metadata);
console.log((this as any).redis);
return { return {
meta, code: 0,
data: { data: res || {},
action, msg,
payload,
},
}; };
}, },
async cacheGroupId(redis: any, groupId: string, socketId: string, groupName: string) {
const data = await redis.get('gk_chat_room'); sendMsg(target: any, msg: {}) {
if (data) { const { ctx } = this as any;
const list = JSON.parse(data) || []; return {
const targetGroup = list.find((itm: any) => itm.groupId === groupId); target,
if (targetGroup) { from: ctx.socket.id,
const sockets = targetGroup.groups || []; tm: new Date().getTime(),
sockets.push(socketId); msg,
await redis.set('gk_chat_room', JSON.stringify(list)); type: 'chat',
return; };
}
}
const value = JSON.stringify([{
groupId, groupName,
groups: [
socketId,
],
}]);
await redis.set('gk_chat_room', value);
},
async queryGroup(redis: any, groupId: string) {
const data = await redis.get('gk_chat_room');
const list = JSON.parse(data || '[]') || [];
const group = list.find((itm: any) => itm.groupId === groupId) || {};
return group;
}, },
async removeIdFromGroup(redis: any, groupId:string, socketId: string) { sendGrooupMsg(target: number, msg: {}) {
const data = await redis.get('gk_chat_room'); const { ctx } = this as any;
if (data) { return {
const list = JSON.parse(data) || []; target,
const targetGroup = list.find((itm: any) => itm.groupId === groupId); from: ctx.socket.id,
if (targetGroup) { tm: new Date().getTime(),
const sockets = (targetGroup.groups || []).filter((itm: any) => itm !== socketId); msg,
targetGroup.groups = sockets; type: 'room',
await redis.set('gk_chat_room', JSON.stringify(list)); };
}
}
}, },
}; };
import { Controller } from 'egg'; import { Controller } from 'egg';
const CHAT_KEY = 'chat';
const ROOM_CHAT_KEY = 'room';
export default class NspController extends Controller { export default class NspController extends Controller {
async send() { async send() {
const { ctx, app } = this; const { ctx } = this;
const nsp = app.io.of('/') as any; // const nsp = app.io.of('/') as any;
const message = ctx.args[0] || {}; const message = ctx.args[0] || {};
const socketId = ctx.socket.id; ctx.socket.emit();
// const socketId = ctx.socket;
const fn = ctx.args[1]; const fn = ctx.args[1];
try { console.log(message);
const { target, groupId } = message; const { type, target } = message;
const group = await ctx.helper.queryGroup(app.redis, groupId); if (type === CHAT_KEY) {
if (nsp.sockets) { ctx.socket.emit(target, ctx.helper.sendMsg(target, message));
Object.keys(nsp.sockets).forEach((id: string) => {
nsp.sockets[id] && socketId !== id && nsp.sockets[id].emit('msg', message);
});
fn && fn({ fn && fn({
code: 0, message: '消息已收到', tm: new Date().getTime(), code: 0, message: '消息已发送', payload: message,
}); });
return;
} }
if (group) { // 聊天室 // 群聊
(group.groups || []).forEach((sck: string) => { if (type === ROOM_CHAT_KEY) {
nsp.sockets[sck] && nsp.sockets[sck].emit('msg', message); ctx.socket.emit(target, ctx.helper.sendGrooupMsg(target, message));
fn && fn({
code: 0, message: '消息已发送', payload: message,
}); });
} else { // 单聊
target && nsp.sockets[target].emit('msg', message);
}
} catch (error) {
app.logger.error(error);
} }
} }
} }
...@@ -2,14 +2,18 @@ import { Context } from 'egg'; ...@@ -2,14 +2,18 @@ import { Context } from 'egg';
export default () => { export default () => {
return async (_ctx: Context, next: any) => { return async (_ctx: Context, next: any) => {
console.log('链接成功', _ctx.socket.id);
// _ctx.socket.on('msg', (value: any, fn: any) => { // _ctx.socket.on('msg', (value: any, fn: any) => {
// console.log('链接成功: ', value); // console.log('链接成功: ', value);
// // console.log('链接成功: fn ===', fn); // // console.log('链接成功: fn ===', fn);
// fn('woot'); // fn('woot');
// }); // });
// const { token } = _ctx.query;
// try {
// _ctx.app.jwt.verify(token || '', _ctx.app.config.jwt.secret);
await next(); await next();
// 断开连接后,删除对应的 群聊信息 // } catch (error) {
console.log('链接成功失败', _ctx.socket.id); // _ctx.socket.disconnect();
// await next();
// }
}; };
}; };
import { Context, EggAppConfig } from 'egg';
export default function jwt(options: EggAppConfig['jwt']) {
return async (ctx: Context, next:() => Promise<any>) => {
const token = ctx.request.headers.authorization;
if (token) {
try {
ctx.app.jwt.verify(token, options.secret);
await next();
} catch (error) {
ctx.status = 401;
ctx.body = {
message: error.message,
};
return;
}
} else {
ctx.status = 401;
ctx.body = {
message: '没有token',
};
return;
}
};
}
import { Application } from 'egg';
module.exports = (app: Application) => {
const mongoose = app.mongoose;
const Schema = mongoose.Schema;
const ChatRoomSchema = new Schema({
roomId: { type: String },
roomName: { type: String },
ids: { type: Array },
});
ChatRoomSchema.pre('save', async function(next) {
app.model.GCounter.findByIdAndUpdate('chatRoomId', { $inc: { roomId: 1 } as any }, { new: true, upsert: true }, (error, counter) => {
if (error) return next(error);
(this as any).roomId = (counter as any).roomId;
next();
});
});
return mongoose.model('ChatRoom', ChatRoomSchema);
};
import { Application } from 'egg';
module.exports = (app: Application) => {
const mongoose = app.mongoose;
const Schema = mongoose.Schema;
const ChatUserSchema = new Schema({
name: { type: String },
username: { type: String },
avator: { type: String },
password: { type: String },
token: { type: String },
userId: { type: Number },
});
const userModel = mongoose.model('ChatUser', ChatUserSchema);
return userModel;
};
import { Application } from 'egg';
module.exports = (app: Application) => {
const mongoose = app.mongoose;
const Schema = mongoose.Schema;
const RoomCounterSchema = new Schema({
_id: { type: String, default: 'chatRoomId' },
roomId: { type: Number },
userId: { type: Number, default: 100000 },
});
return mongoose.model('GCounter', RoomCounterSchema);
};
import { Application } from 'egg'; import { Application } from 'egg';
import accountRouter from './account-router';
import socketRouter from './socket-router'; import socketRouter from './socket-router';
export default (app: Application) => { export default (app: Application) => {
const { controller, router } = app; // const jwt = app.middleware.jwt(app.config.jwt);
router.get('/', controller.home.index);
router.get('/socket/queryRooms', controller.socket.queryList);
router.post('/socket/createroom', controller.socket.createRoom);
router.post('/socket/joinroom', controller.socket.joinRoom);
accountRouter(app);
socketRouter(app); socketRouter(app);
// app.post('/login', controller.socket.login);
// app.post('/createRoom', jwt, controller.socket.createRoom);
// app.post('/joinRoom', jwt, controller.socket.joinRoom);
// app.post('/leaveRoom', jwt, controller.socket.leaveRoom);
}; };
import { Service } from 'egg';
export default class extends Service {
async login() {
const { ctx, app, config } = this;
const { request } = ctx;
const body = request.body;
const { username, password } = body || {};
const result = await app.curl(config.sourceUrl + 'service-user/auth/employee', {
method: 'POST',
data: {
account: username,
assistant: false,
identityType: 1,
ip: '0.0.0.0',
password,
type: 'employee',
},
contentType: 'json',
dataType: 'json',
});
if (result.status >= 200 && result.status <= 299 && result.data.code === 0) {
const bussinessData = result.data || {};
const { data = {} } = bussinessData;
const info = await app.curl(config.sourceUrl + 'service-user/employees/info', {
headers: {
Authorization: `Bearer ${data.token || ''}`,
},
dataType: 'json',
contentType: 'json',
});
if (info.status >= 200 && info.status <= 299 && info.data.code === 0) {
return {
data: {
token: data.token || '',
...(info.data || {}).data || {},
},
code: 0,
};
}
}
return {
code: 100,
msg: 'error',
data: null,
};
}
}
import { Service } from 'egg';
/**
* Test Service
*/
export default class Test extends Service {
public async sayHi(name: string) {
return `hi, ${name}`;
}
}
...@@ -4,57 +4,45 @@ import { Service } from 'egg'; ...@@ -4,57 +4,45 @@ import { Service } from 'egg';
* Test Service * Test Service
*/ */
export default class Socket extends Service { export default class Socket extends Service {
public async createRoom() {
const { app, ctx } = this;
const { redis } = app;
const { request } = ctx;
const body = request.body;
const { groupId, groupName, socketId } = body;
const group = await ctx.helper.queryGroup(redis, groupId); async createRoom() {
if (group) { const { ctx } = this;
return { const { id, roomName } = ctx.request.body;
data: { const newRoom = new ctx.model.ChatRoom({
groupId, roomName,
groupName, ids: [ id ],
}, });
code: 1, const room = await newRoom.save();
msg: '房间已存在', return ctx.helper.success(room);
};
} }
await ctx.helper.cacheGroupId(redis, groupId, socketId, groupName);
return { public async leaveRoom() {
data: { const { ctx } = this;
groupId, const { roomId, id } = ctx.request.body;
groupName, const room = await ctx.model.ChatRoom.findOneAndUpdate({ roomId }, { $pull: { ids: id } }, { new: true });
}, if (!room) {
code: 0, throw new Error('房间不存在');
msg: 'success', }
}; return ctx.helper.success(room);
} }
public async joinRoom() { public async joinRoom() {
const { app, ctx } = this; const { ctx } = this;
const { redis } = app; const { roomId, id } = ctx.request.body;
const { request } = ctx; const room = await ctx.model.ChatRoom.findOneAndUpdate({ roomId }, {
const body = request.body; $addToSet: { ids: id },
const { groupId, socketId, groupName } = body; }, { new: true, upsert: true });
await ctx.helper.cacheGroupId(redis, groupId, socketId, groupName); await ctx.model.ChatUser.findOneAndUpdate({ roomId }, { $addToSet: { ids: id } }, { new: true });
return { if (!room) {
data: { throw new Error('房间不存在');
groupId, }
id: socketId, return ctx.helper.success({});
},
code: 0,
msg: 'success',
};
} }
public async queryRooms() { public async queryRooms() {
const { app } = this; const { app } = this;
const { redis, logger } = app; const { redis } = app;
const data = await redis.get('gk_chat_room'); const data = await redis.get('gk_chat_room');
logger.info('queryRooms: ', data);
const list = JSON.parse(data || '[]') || []; const list = JSON.parse(data || '[]') || [];
return { return {
data: list.map((itm: any) => ({ groupId: itm.groupId, groupName: itm.groupName })), data: list.map((itm: any) => ({ groupId: itm.groupId, groupName: itm.groupName })),
...@@ -62,4 +50,38 @@ export default class Socket extends Service { ...@@ -62,4 +50,38 @@ export default class Socket extends Service {
msg: '', msg: '',
}; };
} }
async login() {
const { ctx } = this;
const { username, password } = ctx.request.body;
const token = ctx.app.jwt.sign({
username,
password,
}, this.app.config.jwt.secret, {
expiresIn: '60d',
});
let res = await ctx.model.ChatUser.findOneAndUpdate({ username, password }, {
$set: { token },
}, { new: true });
let counter = null;
if (!res) {
const isExist = await ctx.model.GCounter.findById('chatRoomId');
// 自增方式获取userId
if (!isExist) {
counter = await new ctx.model.GCounter().save();
} else {
counter = await ctx.model.GCounter.findByIdAndUpdate('chatRoomId', {
$inc: { userId: 1 } as any,
}, { new: true, upsert: true });
}
const { userId } = counter || {} as any;
const user = new ctx.model.ChatUser({
username, password,
token, userId,
});
res = await user.save();
}
const { username: nUsername, userId } = res;
return ctx.helper.success({ username: nUsername, token, userId });
}
} }
...@@ -2,5 +2,5 @@ import { Application } from 'egg'; ...@@ -2,5 +2,5 @@ import { Application } from 'egg';
export default (app: Application) => { export default (app: Application) => {
const { io } = app; const { io } = app;
io.of('/').route('msg', (io.controller as any).nsp.send); io.of('/').route('message', (io.controller as any).nsp.send);
}; };
import { EggAppConfig, EggAppInfo, PowerPartial, Request } from 'egg'; import { Context, EggAppConfig, EggAppInfo, PowerPartial, Request } from 'egg';
import * as qs from 'qs'; import * as qs from 'qs';
// const redisConfig = {
// host: '192.168.32.34',
// port: 6379,
// password: '123456',
// };
export default (appInfo: EggAppInfo) => { export default (appInfo: EggAppInfo) => {
const config = {} as PowerPartial<EggAppConfig>; const config = {} as PowerPartial<EggAppConfig>;
config.keys = appInfo.name + '_1607088260928_8707'; config.keys = appInfo.name + '_1607088260928_8707';
...@@ -22,6 +16,10 @@ export default (appInfo: EggAppInfo) => { ...@@ -22,6 +16,10 @@ export default (appInfo: EggAppInfo) => {
'.nj': 'nunjucks', '.nj': 'nunjucks',
}, },
}; };
const redis = {
host: '192.168.32.32',
port: 6379,
};
const io = { const io = {
init: { wsEngine: 'ws' }, init: { wsEngine: 'ws' },
namespace: { namespace: {
...@@ -34,28 +32,55 @@ export default (appInfo: EggAppInfo) => { ...@@ -34,28 +32,55 @@ export default (appInfo: EggAppInfo) => {
const data = qs.parse(req.url.split('?')[1]); const data = qs.parse(req.url.split('?')[1]);
return data.userId || new Date().getTime().toFixed(0); return data.userId || new Date().getTime().toFixed(0);
}, },
// redis: { redis,
// ...redisConfig,
// },
}; };
// const redis = {
// client: {
// ...redisConfig,
// db: 0,
// },
// };
const cors = { const cors = {
origin: '*', origin: '*',
credentials: true, credentials: true,
allowMethods: 'GET,HEAD,PUT,POST,DELETE,PATCH,OPTIONS', allowMethods: 'GET,HEAD,PUT,POST,DELETE,PATCH,OPTIONS',
}; };
const mongoose = {
client: {
url: 'mongodb://192.168.32.32/fastgeek',
options: {
user: 'root',
pass: '123456',
useUnifiedTopology: true,
useFindAndModify: false,
},
},
};
const onerror = {
all(err: Error, ctx: Context) {
// 统一错误处理
ctx.body = {
code: 1001,
msg: err.toString().replace('Error: ', ''),
};
ctx.status = 200;
// 统一错误日志记录
ctx.logger.info(`统一错误日志:发现了错误${err}`);
},
};
const jwt = {
secret: 'geek-websocket',
};
return { return {
...config, ...config,
...bizConfig, ...bizConfig,
view, view,
io, io,
// redis, jwt,
redis,
cors, cors,
mongoose,
onerror,
security: { security: {
csrf: { csrf: {
enable: false, enable: false,
......
...@@ -3,7 +3,7 @@ import { EggAppConfig, PowerPartial } from 'egg'; ...@@ -3,7 +3,7 @@ import { EggAppConfig, PowerPartial } from 'egg';
export default () => { export default () => {
const cluster = { const cluster = {
listen: { listen: {
port: 7001, port: 3008,
hostname: '0,0,0,0', // 不建议设置 hostname 为 '0.0.0.0',它将允许来自外部网络和来源的连接,请在知晓风险的情况下使用 hostname: '0,0,0,0', // 不建议设置 hostname 为 '0.0.0.0',它将允许来自外部网络和来源的连接,请在知晓风险的情况下使用
}, },
}; };
......
...@@ -17,6 +17,14 @@ const plugin: EggPlugin = { ...@@ -17,6 +17,14 @@ const plugin: EggPlugin = {
enable: true, enable: true,
package: 'egg-cors', package: 'egg-cors',
}, },
mongoose: {
enable: true,
package: 'egg-mongoose',
},
jwt: {
enable: true,
package: 'egg-jwt',
},
}; };
export default plugin; export default plugin;
...@@ -8,7 +8,7 @@ ...@@ -8,7 +8,7 @@
"declarations": true "declarations": true
}, },
"scripts": { "scripts": {
"start": "npm run tsc && egg-scripts start --daemon --title=egg-websocket --sticky", "start": "npm run tsc && egg-scripts start --daemon --sticky",
"stop": "egg-scripts stop --title=egg-server-geek-egg", "stop": "egg-scripts stop --title=egg-server-geek-egg",
"dev": "egg-bin dev --sticky", "dev": "egg-bin dev --sticky",
"debug": "egg-bin debug", "debug": "egg-bin debug",
...@@ -24,6 +24,8 @@ ...@@ -24,6 +24,8 @@
"dependencies": { "dependencies": {
"egg": "^2.6.1", "egg": "^2.6.1",
"egg-cors": "^2.2.3", "egg-cors": "^2.2.3",
"egg-jwt": "^3.1.7",
"egg-mongoose": "^3.3.1",
"egg-redis": "^2.4.0", "egg-redis": "^2.4.0",
"egg-scripts": "^2.6.0", "egg-scripts": "^2.6.0",
"egg-socket.io": "^4.1.6", "egg-socket.io": "^4.1.6",
...@@ -41,6 +43,7 @@ ...@@ -41,6 +43,7 @@
"egg-mock": "^3.16.0", "egg-mock": "^3.16.0",
"eslint": "^6.7.2", "eslint": "^6.7.2",
"eslint-config-egg": "^8.0.0", "eslint-config-egg": "^8.0.0",
"sequelize-cli": "^6.2.0",
"tslib": "^1.9.0", "tslib": "^1.9.0",
"typescript": "^3.0.0" "typescript": "^3.0.0"
}, },
......
...@@ -2,14 +2,10 @@ ...@@ -2,14 +2,10 @@
// Do not modify this file!!!!!!!!! // Do not modify this file!!!!!!!!!
import 'egg'; import 'egg';
import ExportAccount from '../../../app/controller/account';
import ExportHome from '../../../app/controller/home';
import ExportSocket from '../../../app/controller/socket'; import ExportSocket from '../../../app/controller/socket';
declare module 'egg' { declare module 'egg' {
interface IController { interface IController {
account: ExportAccount;
home: ExportHome;
socket: ExportSocket; socket: ExportSocket;
} }
} }
// This file is created by egg-ts-helper@1.25.8
// Do not modify this file!!!!!!!!!
import 'egg';
import ExportJwt from '../../../app/middleware/jwt';
declare module 'egg' {
interface IMiddleware {
jwt: typeof ExportJwt;
}
}
// This file is created by egg-ts-helper@1.25.8
// Do not modify this file!!!!!!!!!
import 'egg';
import ExportChatRoom from '../../../app/model/ChatRoom';
import ExportChatUser from '../../../app/model/ChatUser';
import ExportGCounter from '../../../app/model/GCounter';
declare module 'egg' {
interface IModel {
ChatRoom: ReturnType<typeof ExportChatRoom>;
ChatUser: ReturnType<typeof ExportChatUser>;
GCounter: ReturnType<typeof ExportGCounter>;
}
}
...@@ -6,14 +6,10 @@ type AnyClass = new (...args: any[]) => any; ...@@ -6,14 +6,10 @@ type AnyClass = new (...args: any[]) => any;
type AnyFunc<T = any> = (...args: any[]) => T; type AnyFunc<T = any> = (...args: any[]) => T;
type CanExportFunc = AnyFunc<Promise<any>> | AnyFunc<IterableIterator<any>>; type CanExportFunc = AnyFunc<Promise<any>> | AnyFunc<IterableIterator<any>>;
type AutoInstanceType<T, U = T extends CanExportFunc ? T : T extends AnyFunc ? ReturnType<T> : T> = U extends AnyClass ? InstanceType<U> : U; type AutoInstanceType<T, U = T extends CanExportFunc ? T : T extends AnyFunc ? ReturnType<T> : T> = U extends AnyClass ? InstanceType<U> : U;
import ExportAccount from '../../../app/service/account';
import ExportHome from '../../../app/service/home';
import ExportSocket from '../../../app/service/socket'; import ExportSocket from '../../../app/service/socket';
declare module 'egg' { declare module 'egg' {
interface IService { interface IService {
account: AutoInstanceType<typeof ExportAccount>;
home: AutoInstanceType<typeof ExportHome>;
socket: AutoInstanceType<typeof ExportSocket>; socket: AutoInstanceType<typeof ExportSocket>;
} }
} }
...@@ -18,6 +18,8 @@ import 'egg-view-nunjucks'; ...@@ -18,6 +18,8 @@ import 'egg-view-nunjucks';
import 'egg-socket.io'; import 'egg-socket.io';
import 'egg-redis'; import 'egg-redis';
import 'egg-cors'; import 'egg-cors';
import 'egg-mongoose';
import 'egg-jwt';
import { EggPluginItem } from 'egg'; import { EggPluginItem } from 'egg';
declare module 'egg' { declare module 'egg' {
interface EggPlugin { interface EggPlugin {
...@@ -37,5 +39,7 @@ declare module 'egg' { ...@@ -37,5 +39,7 @@ declare module 'egg' {
io?: EggPluginItem; io?: EggPluginItem;
redis?: EggPluginItem; redis?: EggPluginItem;
cors?: EggPluginItem; cors?: EggPluginItem;
mongoose?: EggPluginItem;
jwt?: EggPluginItem;
} }
} }
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment