Commit e28458d4 authored by huanglu's avatar huanglu

feat: update

parent 59d498c9
...@@ -4,10 +4,9 @@ export default class Auth extends Controller { ...@@ -4,10 +4,9 @@ export default class Auth extends Controller {
async login() { async login() {
const { ctx } = this const { ctx } = this
console.log('=== login: ', ctx.query) console.log('====: ', ctx.request.body, ctx.data)
ctx.body = ctx.helper.success({ const data = await ctx.service.auth.index.register()
userId: '' ctx.body = ctx.helper.success(data)
})
} }
async getUserInfo() { async getUserInfo() {
......
...@@ -8,6 +8,14 @@ export default { ...@@ -8,6 +8,14 @@ export default {
}; };
}, },
fail(msg = '请求失败') {
return {
code: 1,
data: null,
msg,
};
},
sendMsg(target: any, msg: {}) { sendMsg(target: any, msg: {}) {
const { ctx } = this as any; const { ctx } = this as any;
return { 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 { Application } from 'egg';
import socketRouter from './socket-router';
import authRouter from './router/auth'; import authRouter from './router/auth';
export default (app: Application) => { export default (app: Application) => {
// const jwt = app.middleware.jwt(app.config.jwt);
socketRouter(app);
authRouter(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"; ...@@ -2,6 +2,6 @@ import { Application } from "egg";
export default (app: Application) => { export default (app: Application) => {
const { controller } = app const { controller } = app
app.get('/login', controller.auth.login) app.router.post('/login', controller.auth.login)
app.get('/userInfo', controller.auth.getUserInfo) 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 { Context, EggAppConfig, EggAppInfo, PowerPartial } from "egg";
// import * as qs from 'qs';
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";
config.middleware = ["auth", 'errorHandler'];
config.middleware = ['auth']; config.routerNotAuth = ["/login", "/register"];
config.routerNotAuth = [
'/login', '/register'
]
const bizConfig = { const bizConfig = {
sourceUrl: 'https://geek.jkwljy.com/', sourceUrl: "https://geek.jkwljy.com/",
}; };
const view = { const view = {
defaultViewEngine: 'nunjucks', defaultViewEngine: "nunjucks",
mapping: { mapping: {
'.nj': 'nunjucks', ".nj": "nunjucks",
}, },
}; };
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 onerror = { const onerror = {
...@@ -31,7 +29,7 @@ export default (appInfo: EggAppInfo) => { ...@@ -31,7 +29,7 @@ export default (appInfo: EggAppInfo) => {
// 统一错误处理 // 统一错误处理
ctx.body = { ctx.body = {
code: 1001, code: 1001,
msg: err.toString().replace('Error: ', ''), msg: err.toString().replace("Error: ", ""),
}; };
ctx.status = 200; ctx.status = 200;
// 统一错误日志记录 // 统一错误日志记录
...@@ -39,16 +37,14 @@ export default (appInfo: EggAppInfo) => { ...@@ -39,16 +37,14 @@ export default (appInfo: EggAppInfo) => {
}, },
}; };
const jwt = { const jwt = {
secret: 'geek-websocket', secret: "geek-websocket",
}; };
return { return {
...config, ...config,
...bizConfig, ...bizConfig,
view, view,
// io,
jwt, jwt,
cors, cors,
onerror, onerror,
...@@ -57,5 +53,17 @@ export default (appInfo: EggAppInfo) => { ...@@ -57,5 +53,17 @@ export default (appInfo: EggAppInfo) => {
enable: false, 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 = { ...@@ -5,10 +5,6 @@ const plugin: EggPlugin = {
enable: true, enable: true,
package: 'egg-view-nunjucks', package: 'egg-view-nunjucks',
}, },
io: {
enable: true,
package: 'egg-socket.io',
},
redis: { redis: {
enable: true, enable: true,
package: 'egg-redis', package: 'egg-redis',
...@@ -21,6 +17,10 @@ const plugin: EggPlugin = { ...@@ -21,6 +17,10 @@ const plugin: EggPlugin = {
enable: true, enable: true,
package: 'egg-jwt', package: 'egg-jwt',
}, },
mysql:{
enable:true,
package:'egg-mysql',
}
}; };
export default plugin; export default plugin;
...@@ -3,9 +3,11 @@ ...@@ -3,9 +3,11 @@
import 'egg'; import 'egg';
import ExportAuth from '../../../app/middleware/auth'; import ExportAuth from '../../../app/middleware/auth';
import ExportErrorHandler from '../../../app/middleware/error_handler';
declare module 'egg' { declare module 'egg' {
interface IMiddleware { interface IMiddleware {
auth: typeof ExportAuth; auth: typeof ExportAuth;
errorHandler: typeof ExportErrorHandler;
} }
} }
...@@ -6,10 +6,12 @@ type AnyClass = new (...args: any[]) => any; ...@@ -6,10 +6,12 @@ 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 ExportSocket from '../../../app/service/socket'; import ExportAuthIndex from '../../../app/service/auth/index';
declare module 'egg' { declare module 'egg' {
interface IService { interface IService {
socket: AutoInstanceType<typeof ExportSocket>; auth: {
index: AutoInstanceType<typeof ExportAuthIndex>;
}
} }
} }
...@@ -15,10 +15,10 @@ import 'egg-static'; ...@@ -15,10 +15,10 @@ import 'egg-static';
import 'egg-jsonp'; import 'egg-jsonp';
import 'egg-view'; import 'egg-view';
import 'egg-view-nunjucks'; import 'egg-view-nunjucks';
import 'egg-socket.io';
import 'egg-redis'; import 'egg-redis';
import 'egg-cors'; import 'egg-cors';
import 'egg-jwt'; import 'egg-jwt';
import 'egg-mysql';
import { EggPluginItem } from 'egg'; import { EggPluginItem } from 'egg';
declare module 'egg' { declare module 'egg' {
interface EggPlugin { interface EggPlugin {
...@@ -35,9 +35,9 @@ declare module 'egg' { ...@@ -35,9 +35,9 @@ declare module 'egg' {
jsonp?: EggPluginItem; jsonp?: EggPluginItem;
view?: EggPluginItem; view?: EggPluginItem;
nunjucks?: EggPluginItem; nunjucks?: EggPluginItem;
io?: EggPluginItem;
redis?: EggPluginItem; redis?: EggPluginItem;
cors?: EggPluginItem; cors?: EggPluginItem;
jwt?: 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