Commit 0e854772 authored by huanglu's avatar huanglu

feat: 集成MongoDB

parent dfd8dcc3
......@@ -8,12 +8,14 @@
- Typescript 2.8+
### 中间件
-
- egg-jwt
- egg-validate
- egg-router-plus
- egg-bcrypt
### 模板渲染 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,18 +2,30 @@ import { Context } from 'egg';
module.exports = () => {
return async function errorHandler(ctx: Context, next: Function) {
await next();
const { status } = ctx;
if (status === 404) {
try {
await next();
const { status } = ctx;
if (status === 404) {
if (ctx.acceptJSON) {
ctx.body = {
code: 404,
message: '404',
};
ctx.status = 200;
return;
}
ctx.body = '<h1>访问路径不存在</h1>';
}
} catch (error) {
if (ctx.acceptJSON) {
ctx.body = {
code: 404,
message: '404',
code: 400,
message: error.message || '',
};
ctx.status = 200;
return;
}
ctx.body = '<h1>访问路径不存在</h1>';
ctx.body = '<h1>' + error.message + '</h1>';
}
};
};
import { Context } from 'egg';
import { pathToRegexp } from 'path-to-regexp';
module.exports = (options: any) => {
module.exports = () => {
return async function jwtErr(ctx: Context, next: Function) {
const { request, path } = ctx;
const token = request.header.authorization;
let decode = '';
if (token) {
try {
// 解码token
decode = ctx.app.jwt.verify(token, options.secret);
console.log('decode======>', decode);
} catch (error) {
ctx.status = 401;
ctx.body = {
message: error.message,
};
return;
try {
const { request, path, method } = ctx;
// login生成token
if (/\/login/g.test(path) && method === 'POST') {
const { request } = ctx;
const { pwd } = request.body;
const token = ctx.app.jwt.sign({ pwd }
, ctx.app.config.jwt.secret);
ctx.token = token;
}
} else {
if (/\/api/g.test(path)) {
ctx.status = 200;
ctx.body = {
message: '没有token',
code: 404,
};
// 是否需要token路径
const noAuthPath = (ctx.app.config.excludeAuths || []).find(itm => {
return pathToRegexp(itm).exec(path);
});
if (noAuthPath) {
await next();
return;
}
await next();
const token = request.header.authorization;
if (token) { // 存在token
const decodeToken = ctx.app.jwt.verify(token, ctx.app.config.secret);
ctx.authInfo = decodeToken;
}
} catch (error) {
ctx.status = 200;
ctx.body = {
code: 401,
message: error.message,
};
return;
}
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) => {
const { controller } = app;
app.get('/', controller.home.index);
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 {
public async login() {
const { ctx } = this;
// const sourceUrl = config.source_url;
const result = await ctx.helper.http().get('https://registry.npm.taobao.org/egg/latest');
ctx.body = result;
// const result = await ctx.helper.http().get('https://registry.npm.taobao.org/egg/latest');
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() {
const { ctx } = this;
// const headers = {
// 'Content-Type': 'text/html',
// };
// ctx.set(headers);
await ctx.render('login.html');
}
}
......@@ -2,8 +2,10 @@
<html lang="en">
<head>
<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">
<title>Document</title>
<meta name=""
</head>
<body>
{% block header %}
......
{% extends "./base.html" %}
{% block header %}
<form action="logisn" method="POST" accept="*" enctype="application/x-www-form-urlencoded">
<input name="name" type="text" /><br>
<input type="number" name='age'><br>
<form action="login" method="POST" accept="*" enctype="application/x-www-form-urlencoded">
<label for="name">
name:
<input name="name" type="text" /><br>
</label>
<label for="age">
age:
<input type="number" name='age'><br>
</label>
<label for="pwd">
pwd:
<input type="password" name='pwd'><br>
</label>
<input type="submit" title="submit" />
</form>
{% endblock %}
\ No newline at end of file
......@@ -13,11 +13,21 @@ export default (appInfo: EggAppInfo) => {
trimBlocks: true,
lstripBlocks: true,
},
// 远程调用数据的服务器地址
source_url: 'https://registry.npm.taobao.org',
// 配置不进行token检验的接口
excludeAuths: [
'/logout',
'/public/:sub/:other?',
],
bcrypt: {
saltRounds: 10,
},
};
config.jwt = { // jwt配置项
secret: '123456',
secret: 'geek_jwt',
};
// 中间件
config.middleware = [ 'errorHandler', 'jwtHandler' ];
return {
...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';
console.log('==== env : local =====');
export default () => {
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;
};
import { EggAppConfig, PowerPartial } from 'egg';
console.log('==== env : prod =====');
export default () => {
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;
};
......@@ -10,9 +10,21 @@ const plugin: EggPlugin = {
package: 'egg-router-plus',
},
jwt: {
enable: false,
enable: true,
package: 'egg-jwt',
},
validate: {
enable: true,
package: 'egg-validate',
},
bcrypt: {
enable: true,
package: 'egg-bcrypt',
},
mongoose: {
enable: true,
package: 'egg-mongoose',
},
};
export default plugin;
......@@ -23,12 +23,15 @@
},
"dependencies": {
"egg": "^2.6.1",
"egg-bcrypt": "^1.1.0",
"egg-jwt": "^3.1.7",
"egg-mongoose": "^3.2.0",
"egg-router-plus": "^1.3.1",
"egg-scripts": "^2.6.0",
"egg-validate": "^2.0.2",
"egg-view-nunjucks": "^2.2.0",
"moment": "^2.27.0"
"moment": "^2.27.0",
"path-to-regexp": "^6.1.0"
},
"devDependencies": {
"@types/mocha": "^2.2.40",
......@@ -39,7 +42,6 @@
"egg-bin": "^4.11.0",
"egg-ci": "^1.8.0",
"egg-mock": "^3.16.0",
"egg-swagger-doc": "^2.3.2",
"eslint": "^6.7.2",
"eslint-config-egg": "^8.0.0",
"husky": "^4.2.5",
......
......@@ -3,9 +3,11 @@
import 'egg';
import ExportHome from '../../../app/controller/home';
import ExportPublic from '../../../app/controller/public';
declare module 'egg' {
interface IController {
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';
import 'egg-view';
import 'egg-view-nunjucks';
import 'egg-router-plus';
import 'egg-jwt';
import 'egg-validate';
import 'egg-bcrypt';
import 'egg-mongoose';
import { EggPluginItem } from 'egg';
declare module 'egg' {
interface EggPlugin {
......@@ -34,5 +38,8 @@ declare module 'egg' {
nunjucks?: EggPluginItem;
routerPlus?: EggPluginItem;
jwt?: EggPluginItem;
validate?: EggPluginItem;
bcrypt?: EggPluginItem;
mongoose?: EggPluginItem;
}
}
\ No newline at end of file
......@@ -4,5 +4,7 @@ import { Application, Application } from 'egg';
declare module 'egg' {
interface Application {
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