Commit e28458d4 authored by huanglu's avatar huanglu

feat: update

parent 59d498c9
......@@ -4,10 +4,9 @@ export default class Auth extends Controller {
async login() {
const { ctx } = this
console.log('=== login: ', ctx.query)
ctx.body = ctx.helper.success({
userId: ''
})
console.log('====: ', ctx.request.body, ctx.data)
const data = await ctx.service.auth.index.register()
ctx.body = ctx.helper.success(data)
}
async getUserInfo() {
......
......@@ -8,6 +8,14 @@ export default {
};
},
fail(msg = '请求失败') {
return {
code: 1,
data: null,
msg,
};
},
sendMsg(target: any, msg: {}) {
const { ctx } = this as any;
return {
......
import { Controller } from 'egg';
const CHAT_KEY = 'chat';
const ROOM_CHAT_KEY = 'room';
export default class NspController extends Controller {
async send() {
const { ctx } = this;
// const nsp = app.io.of('/') as any;
const message = ctx.args[0] || {};
ctx.socket.emit();
// const socketId = ctx.socket;
const fn = ctx.args[1];
console.log(message);
const { type, target } = message;
if (type === CHAT_KEY) {
ctx.socket.emit(target, ctx.helper.sendMsg(target, message));
fn && fn({
code: 0, message: '消息已发送', payload: message,
});
}
// 群聊
if (type === ROOM_CHAT_KEY) {
ctx.socket.emit(target, ctx.helper.sendGrooupMsg(target, message));
fn && fn({
code: 0, message: '消息已发送', payload: message,
});
}
}
}
import { Context } from 'egg';
export default () => {
return async (_ctx: Context, next: any) => {
// _ctx.socket.on('msg', (value: any, fn: any) => {
// console.log('链接成功: ', value);
// // console.log('链接成功: fn ===', fn);
// fn('woot');
// });
// const { token } = _ctx.query;
// try {
// _ctx.app.jwt.verify(token || '', _ctx.app.config.jwt.secret);
await next();
// } catch (error) {
// _ctx.socket.disconnect();
// await next();
// }
};
};
import { Context } from 'egg';
export default () => {
return async (_ctx: Context, next: any) => {
await next();
};
};
import { Context } from "egg";
module.exports = () => {
return async function errorHandler(ctx: Context, next: Function) {
try {
await next();
} catch (err) {
ctx.app.emit("error", err, ctx);
const status = err.status || 500;
// 生产环境时 500 错误的详细错误内容不返回给客户端,因为可能包含敏感信息
const error = status === 500 && err.message || "Internal Server Error";
// 从 error 对象上读出各个属性,设置到响应中
ctx.body = ctx.helper.fail(error)
}
};
};
import { Application } from 'egg';
import socketRouter from './socket-router';
import authRouter from './router/auth';
export default (app: Application) => {
// const jwt = app.middleware.jwt(app.config.jwt);
socketRouter(app);
authRouter(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);
};
......@@ -2,6 +2,6 @@ import { Application } from "egg";
export default (app: Application) => {
const { controller } = app
app.get('/login', controller.auth.login)
app.get('/userInfo', controller.auth.getUserInfo)
app.router.post('/login', controller.auth.login)
app.router.get('/userInfo', controller.auth.getUserInfo)
};
\ No newline at end of file
import { Service } from "egg";
export default class AuthService extends Service {
async register() {
const { ctx, app } = this
const { user, password } = ctx.request.body || {}
if (!user || !password) {
throw new Error('user or password not null ')
}
const token = this.app.jwt.sign({
user,
password
}, app.config.jwt.secret)
if (token) {
// const value = await (app as any).mysql.update('geek-user', { username: user, password, token }, { id: 5 })
const sql = `select ? from ?`
console.log('get user : ', sql)
const value = await (app as any).mysql.query(sql, ['username', 'geek-user'])
console.log('get user : ', value)
return {
token,
user
}
} else {
throw new Error('register failed')
}
}
}
\ No newline at end of file
import { Service } from 'egg';
/**
* Test Service
*/
export default class Socket extends Service {
async createRoom() {
const { ctx } = this;
const { id, roomName } = ctx.request.body;
const newRoom = new ctx.model.ChatRoom({
roomName,
ids: [ id ],
});
const room = await newRoom.save();
return ctx.helper.success(room);
}
public async leaveRoom() {
const { ctx } = this;
const { roomId, id } = ctx.request.body;
const room = await ctx.model.ChatRoom.findOneAndUpdate({ roomId }, { $pull: { ids: id } }, { new: true });
if (!room) {
throw new Error('房间不存在');
}
return ctx.helper.success(room);
}
public async joinRoom() {
const { ctx } = this;
const { roomId, id } = ctx.request.body;
const room = await ctx.model.ChatRoom.findOneAndUpdate({ roomId }, {
$addToSet: { ids: id },
}, { new: true, upsert: true });
await ctx.model.ChatUser.findOneAndUpdate({ roomId }, { $addToSet: { ids: id } }, { new: true });
if (!room) {
throw new Error('房间不存在');
}
return ctx.helper.success({});
}
public async queryRooms() {
const { app } = this;
const { redis } = app;
const data = await redis.get('gk_chat_room');
const list = JSON.parse(data || '[]') || [];
return {
data: list.map((itm: any) => ({ groupId: itm.groupId, groupName: itm.groupName })),
code: 0,
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 });
}
}
import { Application } from 'egg';
export default (app: Application) => {
const { io } = app;
io.of('/').route('message', (io.controller as any).nsp.send);
};
import { Context, EggAppConfig, EggAppInfo, PowerPartial } from 'egg';
// import * as qs from 'qs';
import { Context, EggAppConfig, EggAppInfo, PowerPartial } from "egg";
export default (appInfo: EggAppInfo) => {
const config = {} as PowerPartial<EggAppConfig>;
config.keys = appInfo.name + '_1607088260928_8707';
config.keys = appInfo.name + "_1607088260928_8707";
config.middleware = ["auth", 'errorHandler'];
config.middleware = ['auth'];
config.routerNotAuth = [
'/login', '/register'
]
config.routerNotAuth = ["/login", "/register"];
const bizConfig = {
sourceUrl: 'https://geek.jkwljy.com/',
sourceUrl: "https://geek.jkwljy.com/",
};
const view = {
defaultViewEngine: 'nunjucks',
defaultViewEngine: "nunjucks",
mapping: {
'.nj': 'nunjucks',
".nj": "nunjucks",
},
};
const cors = {
origin: '*',
origin: "*",
credentials: true,
allowMethods: 'GET,HEAD,PUT,POST,DELETE,PATCH,OPTIONS',
allowMethods: "GET,HEAD,PUT,POST,DELETE,PATCH,OPTIONS",
};
const onerror = {
......@@ -31,7 +29,7 @@ export default (appInfo: EggAppInfo) => {
// 统一错误处理
ctx.body = {
code: 1001,
msg: err.toString().replace('Error: ', ''),
msg: err.toString().replace("Error: ", ""),
};
ctx.status = 200;
// 统一错误日志记录
......@@ -39,16 +37,14 @@ export default (appInfo: EggAppInfo) => {
},
};
const jwt = {
secret: 'geek-websocket',
secret: "geek-websocket",
};
return {
...config,
...bizConfig,
view,
// io,
jwt,
cors,
onerror,
......@@ -57,5 +53,17 @@ export default (appInfo: EggAppInfo) => {
enable: false,
},
},
mysql: {
client: {
host: "localhost",
port: "3306",
//username
user: "root",
password: "root1234",
database: "geek-front",
},
app: true,
agent: false,
},
};
};
......@@ -5,10 +5,6 @@ const plugin: EggPlugin = {
enable: true,
package: 'egg-view-nunjucks',
},
io: {
enable: true,
package: 'egg-socket.io',
},
redis: {
enable: true,
package: 'egg-redis',
......@@ -21,6 +17,10 @@ const plugin: EggPlugin = {
enable: true,
package: 'egg-jwt',
},
mysql:{
enable:true,
package:'egg-mysql',
}
};
export default plugin;
......@@ -3,9 +3,11 @@
import 'egg';
import ExportAuth from '../../../app/middleware/auth';
import ExportErrorHandler from '../../../app/middleware/error_handler';
declare module 'egg' {
interface IMiddleware {
auth: typeof ExportAuth;
errorHandler: typeof ExportErrorHandler;
}
}
......@@ -6,10 +6,12 @@ type AnyClass = new (...args: any[]) => any;
type AnyFunc<T = any> = (...args: any[]) => T;
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;
import ExportSocket from '../../../app/service/socket';
import ExportAuthIndex from '../../../app/service/auth/index';
declare module 'egg' {
interface IService {
socket: AutoInstanceType<typeof ExportSocket>;
auth: {
index: AutoInstanceType<typeof ExportAuthIndex>;
}
}
}
......@@ -15,10 +15,10 @@ import 'egg-static';
import 'egg-jsonp';
import 'egg-view';
import 'egg-view-nunjucks';
import 'egg-socket.io';
import 'egg-redis';
import 'egg-cors';
import 'egg-jwt';
import 'egg-mysql';
import { EggPluginItem } from 'egg';
declare module 'egg' {
interface EggPlugin {
......@@ -35,9 +35,9 @@ declare module 'egg' {
jsonp?: EggPluginItem;
view?: EggPluginItem;
nunjucks?: EggPluginItem;
io?: EggPluginItem;
redis?: EggPluginItem;
cors?: EggPluginItem;
jwt?: EggPluginItem;
mysql?: EggPluginItem;
}
}
\ No newline at end of file
This source diff could not be displayed because it is too large. You can view the blob instead.
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