Commit 0e854772 authored by huanglu's avatar huanglu

feat: 集成MongoDB

parent dfd8dcc3
...@@ -8,12 +8,14 @@ ...@@ -8,12 +8,14 @@
- Typescript 2.8+ - Typescript 2.8+
### 中间件 ### 中间件
- - egg-jwt
- egg-validate
- egg-router-plus
- egg-bcrypt
### 模板渲染 egg-view-nunjucks ### 模板渲染 egg-view-nunjucks
### helpers ### 框架扩展
import { Controller } from 'egg';
export default class CommApi extends Controller {
public async api() {
const { ctx } = this;
ctx.body = 'this is public api';
}
}
...@@ -2,6 +2,7 @@ import { Context } from 'egg'; ...@@ -2,6 +2,7 @@ import { Context } from 'egg';
module.exports = () => { module.exports = () => {
return async function errorHandler(ctx: Context, next: Function) { return async function errorHandler(ctx: Context, next: Function) {
try {
await next(); await next();
const { status } = ctx; const { status } = ctx;
if (status === 404) { if (status === 404) {
...@@ -15,5 +16,16 @@ module.exports = () => { ...@@ -15,5 +16,16 @@ module.exports = () => {
} }
ctx.body = '<h1>访问路径不存在</h1>'; ctx.body = '<h1>访问路径不存在</h1>';
} }
} catch (error) {
if (ctx.acceptJSON) {
ctx.body = {
code: 400,
message: error.message || '',
};
ctx.status = 200;
return;
}
ctx.body = '<h1>' + error.message + '</h1>';
}
}; };
}; };
import { Context } from 'egg'; import { Context } from 'egg';
import { pathToRegexp } from 'path-to-regexp';
module.exports = (options: any) => { module.exports = () => {
return async function jwtErr(ctx: Context, next: Function) { return async function jwtErr(ctx: Context, next: Function) {
const { request, path } = ctx;
const token = request.header.authorization;
let decode = '';
if (token) {
try { try {
// 解码token const { request, path, method } = ctx;
decode = ctx.app.jwt.verify(token, options.secret); // login生成token
console.log('decode======>', decode); if (/\/login/g.test(path) && method === 'POST') {
} catch (error) { const { request } = ctx;
ctx.status = 401; const { pwd } = request.body;
ctx.body = { const token = ctx.app.jwt.sign({ pwd }
message: error.message, , ctx.app.config.jwt.secret);
}; ctx.token = token;
}
// 是否需要token路径
const noAuthPath = (ctx.app.config.excludeAuths || []).find(itm => {
return pathToRegexp(itm).exec(path);
});
if (noAuthPath) {
await next();
return; return;
} }
} else { const token = request.header.authorization;
if (/\/api/g.test(path)) { if (token) { // 存在token
const decodeToken = ctx.app.jwt.verify(token, ctx.app.config.secret);
ctx.authInfo = decodeToken;
}
} catch (error) {
ctx.status = 200; ctx.status = 200;
ctx.body = { ctx.body = {
message: '没有token', code: 401,
code: 404, message: error.message,
}; };
return; return;
} }
await next(); await next();
}
}; };
}; };
import { Application } from 'egg';
export default (app: Application) => {
const mongoose = app.mongoose;
const Schema = mongoose.Schema;
const userInfo = new Schema({
name: { type: String, default: '', required: true },
age: { type: Number, default: 0 },
pwd: { type: String },
token: { type: String, required: true },
});
return mongoose.model('User', userInfo);
};
...@@ -6,4 +6,7 @@ export default (app: Application) => { ...@@ -6,4 +6,7 @@ export default (app: Application) => {
const { controller } = app; const { controller } = app;
app.get('/', controller.home.index); app.get('/', controller.home.index);
app.post('/login', controller.home.login); app.post('/login', controller.home.login);
app.get('/public', controller.public.api);
app.get('/public/hh', controller.public.api);
app.get('/public/hh/12', controller.public.api);
}; };
...@@ -4,16 +4,23 @@ export default class Account extends Service { ...@@ -4,16 +4,23 @@ export default class Account extends Service {
public async login() { public async login() {
const { ctx } = this; const { ctx } = this;
// const sourceUrl = config.source_url; // const sourceUrl = config.source_url;
const result = await ctx.helper.http().get('https://registry.npm.taobao.org/egg/latest'); // const result = await ctx.helper.http().get('https://registry.npm.taobao.org/egg/latest');
ctx.body = result; console.log('sfsfs; ', ctx.token);
const { pwd, name, age } = ctx.request.body;
const token = ctx.token;
const hashName = await ctx.genHash(pwd);
// const origin = await ctx.compare(pwd, hashName);
const user = await ctx.model.User.create({
name,
pwd: hashName,
age,
token,
});
ctx.body = user;
} }
public async index() { public async index() {
const { ctx } = this; const { ctx } = this;
// const headers = {
// 'Content-Type': 'text/html',
// };
// ctx.set(headers);
await ctx.render('login.html'); await ctx.render('login.html');
} }
} }
...@@ -2,8 +2,10 @@ ...@@ -2,8 +2,10 @@
<html lang="en"> <html lang="en">
<head> <head>
<meta charset="UTF-8"> <meta charset="UTF-8">
<link rel="icon" href="https://geek.jkwljy.com/signin/favicon.ico">
<meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title> <title>Document</title>
<meta name=""
</head> </head>
<body> <body>
{% block header %} {% block header %}
......
{% extends "./base.html" %} {% extends "./base.html" %}
{% block header %} {% block header %}
<form action="logisn" method="POST" accept="*" enctype="application/x-www-form-urlencoded"> <form action="login" method="POST" accept="*" enctype="application/x-www-form-urlencoded">
<label for="name">
name:
<input name="name" type="text" /><br> <input name="name" type="text" /><br>
</label>
<label for="age">
age:
<input type="number" name='age'><br> <input type="number" name='age'><br>
</label>
<label for="pwd">
pwd:
<input type="password" name='pwd'><br>
</label>
<input type="submit" title="submit" /> <input type="submit" title="submit" />
</form> </form>
{% endblock %} {% endblock %}
\ No newline at end of file
...@@ -13,11 +13,21 @@ export default (appInfo: EggAppInfo) => { ...@@ -13,11 +13,21 @@ export default (appInfo: EggAppInfo) => {
trimBlocks: true, trimBlocks: true,
lstripBlocks: true, lstripBlocks: true,
}, },
// 远程调用数据的服务器地址
source_url: 'https://registry.npm.taobao.org', source_url: 'https://registry.npm.taobao.org',
// 配置不进行token检验的接口
excludeAuths: [
'/logout',
'/public/:sub/:other?',
],
bcrypt: {
saltRounds: 10,
},
}; };
config.jwt = { // jwt配置项 config.jwt = { // jwt配置项
secret: '123456', secret: 'geek_jwt',
}; };
// 中间件
config.middleware = [ 'errorHandler', 'jwtHandler' ]; config.middleware = [ 'errorHandler', 'jwtHandler' ];
return { return {
...config, ...config,
......
import { EggAppConfig, PowerPartial } from 'egg';
console.log('==== env : dev =====');
export default () => {
const config: PowerPartial<EggAppConfig> = {};
config.swaggerdoc = {
dirScanner: './app/controller',
apiInfo: {
title: 'egg-swagger',
description: 'swagger-ui for egg',
version: '1.0.0',
},
schemes: [ 'http', 'https' ],
consumes: [ 'application/json' ],
produces: [ 'application/json' ],
securityDefinitions: {
},
enableSecurity: false,
// enableValidate: true,
routerMap: false,
enable: true,
};
return config;
};
import { EggAppConfig, PowerPartial } from 'egg'; import { EggAppConfig, PowerPartial } from 'egg';
console.log('==== env : local =====');
export default () => { export default () => {
const config: PowerPartial<EggAppConfig> = {}; const config: PowerPartial<EggAppConfig> = {};
config.mongoose = {
client: {
url: 'mongodb://127.0.0.1/demo',
options: {},
// mongoose global plugins, expected a function or an array of function and options
// plugins: [createdPlugin, [updatedPlugin, pluginOptions]],
},
};
return config; return config;
}; };
import { EggAppConfig, PowerPartial } from 'egg'; import { EggAppConfig, PowerPartial } from 'egg';
console.log('==== env : prod =====');
export default () => { export default () => {
const config: PowerPartial<EggAppConfig> = {}; const config: PowerPartial<EggAppConfig> = {};
config.mongoose = {
client: {
url: 'mongodb://127.0.0.1/prod',
options: {},
// mongoose global plugins, expected a function or an array of function and options
// plugins: [createdPlugin, [updatedPlugin, pluginOptions]],
},
};
return config; return config;
}; };
...@@ -10,9 +10,21 @@ const plugin: EggPlugin = { ...@@ -10,9 +10,21 @@ const plugin: EggPlugin = {
package: 'egg-router-plus', package: 'egg-router-plus',
}, },
jwt: { jwt: {
enable: false, enable: true,
package: 'egg-jwt', package: 'egg-jwt',
}, },
validate: {
enable: true,
package: 'egg-validate',
},
bcrypt: {
enable: true,
package: 'egg-bcrypt',
},
mongoose: {
enable: true,
package: 'egg-mongoose',
},
}; };
export default plugin; export default plugin;
...@@ -23,12 +23,15 @@ ...@@ -23,12 +23,15 @@
}, },
"dependencies": { "dependencies": {
"egg": "^2.6.1", "egg": "^2.6.1",
"egg-bcrypt": "^1.1.0",
"egg-jwt": "^3.1.7", "egg-jwt": "^3.1.7",
"egg-mongoose": "^3.2.0",
"egg-router-plus": "^1.3.1", "egg-router-plus": "^1.3.1",
"egg-scripts": "^2.6.0", "egg-scripts": "^2.6.0",
"egg-validate": "^2.0.2", "egg-validate": "^2.0.2",
"egg-view-nunjucks": "^2.2.0", "egg-view-nunjucks": "^2.2.0",
"moment": "^2.27.0" "moment": "^2.27.0",
"path-to-regexp": "^6.1.0"
}, },
"devDependencies": { "devDependencies": {
"@types/mocha": "^2.2.40", "@types/mocha": "^2.2.40",
...@@ -39,7 +42,6 @@ ...@@ -39,7 +42,6 @@
"egg-bin": "^4.11.0", "egg-bin": "^4.11.0",
"egg-ci": "^1.8.0", "egg-ci": "^1.8.0",
"egg-mock": "^3.16.0", "egg-mock": "^3.16.0",
"egg-swagger-doc": "^2.3.2",
"eslint": "^6.7.2", "eslint": "^6.7.2",
"eslint-config-egg": "^8.0.0", "eslint-config-egg": "^8.0.0",
"husky": "^4.2.5", "husky": "^4.2.5",
......
...@@ -3,9 +3,11 @@ ...@@ -3,9 +3,11 @@
import 'egg'; import 'egg';
import ExportHome from '../../../app/controller/home'; import ExportHome from '../../../app/controller/home';
import ExportPublic from '../../../app/controller/public';
declare module 'egg' { declare module 'egg' {
interface IController { interface IController {
home: ExportHome; home: ExportHome;
public: ExportPublic;
} }
} }
// This file is created by egg-ts-helper@1.25.8
// Do not modify this file!!!!!!!!!
import 'egg';
import ExportUser from '../../../app/model/user';
declare module 'egg' {
interface IModel {
User: ReturnType<typeof ExportUser>;
}
}
...@@ -16,6 +16,10 @@ import 'egg-jsonp'; ...@@ -16,6 +16,10 @@ import 'egg-jsonp';
import 'egg-view'; import 'egg-view';
import 'egg-view-nunjucks'; import 'egg-view-nunjucks';
import 'egg-router-plus'; import 'egg-router-plus';
import 'egg-jwt';
import 'egg-validate';
import 'egg-bcrypt';
import 'egg-mongoose';
import { EggPluginItem } from 'egg'; import { EggPluginItem } from 'egg';
declare module 'egg' { declare module 'egg' {
interface EggPlugin { interface EggPlugin {
...@@ -34,5 +38,8 @@ declare module 'egg' { ...@@ -34,5 +38,8 @@ declare module 'egg' {
nunjucks?: EggPluginItem; nunjucks?: EggPluginItem;
routerPlus?: EggPluginItem; routerPlus?: EggPluginItem;
jwt?: EggPluginItem; jwt?: EggPluginItem;
validate?: EggPluginItem;
bcrypt?: EggPluginItem;
mongoose?: EggPluginItem;
} }
} }
\ No newline at end of file
...@@ -4,5 +4,7 @@ import { Application, Application } from 'egg'; ...@@ -4,5 +4,7 @@ import { Application, Application } from 'egg';
declare module 'egg' { declare module 'egg' {
interface Application { interface Application {
jwt: any jwt: any
genHash: function(string): Promise<string>
compare: function(string, string): Promise<string>
} }
} }
\ 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