重构路由;重构控制器;优化跨域中间件;移除日志模块;

v1
宇天 2020-09-24 15:02:14 +08:00
parent 41e4f9de6d
commit c9d1939502
6 changed files with 48 additions and 115 deletions

View File

@ -23,7 +23,6 @@ export default {
website: 'localhost', website: 'localhost',
domain: '', // cookie域, 默认等于website domain: '', // cookie域, 默认等于website
port: 3000, port: 3000,
routeMode: 'action', // action | __main__
env: process.env.NODE_ENV === ENV_PROD ? ENV_PROD : ENV_DEV, env: process.env.NODE_ENV === ENV_PROD ? ENV_PROD : ENV_DEV,
debug: process.env.NODE_ENV === ENV_DEV, // debug模式 debug: process.env.NODE_ENV === ENV_DEV, // debug模式
smtp: { smtp: {

View File

@ -9,20 +9,16 @@ import 'es.shim' // 加载拓展方法
import http from 'http' import http from 'http'
import path from 'path' import path from 'path'
import fs from 'iofs' import fs from 'iofs'
// import Ioredis from 'ioredis'
import Request from '@gm5/request' import Request from '@gm5/request'
import Response from '@gm5/response' import Response from '@gm5/response'
// import Session from '@gm5/session' import { sessionStore, sessionWare } from '@gm5/session'
import Jwt from '@gm5/jwt'
import init from './lib/reg-init.js' import config from './config/index.js'
import Log from './lib/log.js' //基础日志记录工具
import routerWare from './middleware/router.js' import routerWare from './middleware/router.js'
import credentialsWare from './middleware/credentials.js' import corsWare from './middleware/cors.js'
// import sessionWare from './module/session.js'
var log = console.log
function hideProperty(host, name, value) { function hideProperty(host, name, value) {
Object.defineProperty(host, name, { Object.defineProperty(host, name, {
@ -35,37 +31,26 @@ function hideProperty(host, name, value) {
export default class Five { export default class Five {
constructor() { constructor() {
hideProperty(this, '__FIVE__', Object.assign({}, init)) hideProperty(this, '__FIVE__', config)
hideProperty(this, '__MODULES__', {}) hideProperty(this, '__MODULES__', {})
hideProperty(this, '__MIDDLEWARE__', [credentialsWare]) hideProperty(this, '__MIDDLEWARE__', [corsWare])
} }
__init__() { __main__() {
var { domain, website, session } = this.__FIVE__ var { domain, website, session } = this.__FIVE__
domain = domain || website domain = domain || website
session.domain = session.domain || domain session.domain = session.domain || domain
this.set({ domain, session }) this.set({ domain, session })
// 这里只创建session的存储器, 而初始化操作在中间件中进行 // 安装jwt
// if (session.type === 'redis') { this.install(Jwt)
// hideProperty(
// this,
// '__SESSION_STORE__',
// new Ioredis({
// host: session.db.host || '127.0.0.1',
// port: session.db.port || 6379,
// db: session.db.db || 0
// })
// )
// } else {
// hideProperty(this, '__SESSION_STORE__', {})
// }
// 将session和cookie的中间件提到最前 // 将session中间件提到最前
// 以便用户自定义的中间件可以直接操作session和cookie // 以便用户自定义的中间件可以直接操作session
// this.__MIDDLEWARE__.unshift(sessionWare) this.install(sessionStore)
// this.__MIDDLEWARE__.unshift(credentialsWare) this.__MIDDLEWARE__.unshift(sessionWare)
// 路由中间件要在最后
this.use(routerWare) this.use(routerWare)
} }
@ -81,7 +66,7 @@ export default class Five {
try { try {
Object.assign(this.__FIVE__[i], obj[i]) Object.assign(this.__FIVE__[i], obj[i])
} catch (err) { } catch (err) {
log(err) console.error(err)
} }
} }
} else { } else {
@ -105,7 +90,14 @@ export default class Five {
this.__MIDDLEWARE__.push(fn) this.__MIDDLEWARE__.push(fn)
return this return this
} }
throw TypeError('argument must be a callback') throw TypeError('argument must be a function')
}
// 注入实例化对象到实例池中
// 与use方法不同的是, 这个会在server创建之前就已经执行
install({ name, install }, args) {
this['$$' + name] = install.call(this, args)
return this
} }
// 预加载应用, 缓存以提高性能 // 预加载应用, 缓存以提高性能
@ -133,19 +125,12 @@ export default class Five {
return this return this
} }
// 注入实例化对象到实例池中
// 与use方法不同的是, 这个会在server创建之前就已经执行
install({ name, install }) {
this['$$' + name] = install.call(this, this.__FIVE__)
return this
}
// 启动http服务 // 启动http服务
listen(port) { listen(port) {
var _this = this var _this = this
var server var server
this.__init__() this.__main__()
server = http.createServer(function(req, res) { server = http.createServer(function(req, res) {
var request = new Request(req, res) var request = new Request(req, res)

View File

@ -1,48 +0,0 @@
/**
* 简单的日志封装
* @author yutent<yutent.io@gmail.com>
* @date 2020/09/18 16:07:26
*/
import fs from 'iofs'
import path from 'path'
export default class Log {
constructor(file = 'run_time.log', dir = './') {
if (!dir) {
throw new Error(`agument dir must be a string, but ${typeof dir} given.`)
}
if (!fs.exists(dir)) {
fs.mkdir(dir)
}
this.file = path.resolve(dir, file)
}
error(str) {
this.save(str, 'error')
}
info(str) {
this.save(str, 'info')
}
warn(str) {
this.save(str, 'warning')
}
debug(str) {
this.save(str, 'debug')
}
//写入日志文件
save(str, type) {
type = type || 'debug'
fs.echo(
`[${type}] ${new Date().format('Y-m-d_H:i:s')} ${str} \n`,
this.file,
true
)
}
}

View File

@ -6,10 +6,6 @@
export default function(req, res, next) { export default function(req, res, next) {
var debug = this.get('debug') var debug = this.get('debug')
if (this.__MODULES__.__error__) {
var err = this.__MODULES__.__error__
return res.error(debug ? err.stack || err : err, err.status || 500)
}
// 1. 先判断控制器是否存在 // 1. 先判断控制器是否存在
if (!this.__MODULES__[req.app]) { if (!this.__MODULES__[req.app]) {
@ -23,32 +19,32 @@ export default function(req, res, next) {
// 3. 实例化控制器 // 3. 实例化控制器
this.__MODULES__[req.app] this.__MODULES__[req.app]
.then(({ default: Mod }) => { .then(async ({ default: Mod }) => {
var app var app
var err = '' var err = ''
if (Mod) { if (Mod) {
app = new Mod({ ctx: this, req, res }) app = new Mod()
app.__f_i_v_e__(this, req, res)
// action模式, 则路由自动调用对应的action方法 // 4. 优先执行__main__方法
// __main__模式, 则路由全部走__main__方法 if (app.__main__) {
if (this.get('routeMode') === 'action') { try {
var route = req.path.shift() await app.__main__()
var act = route + 'Action' } catch (err) {
return Promise.reject(err)
if (app[act]) {
return app[act].apply(app, req.path)
} else {
err = new Error(`Route [${route}] not found`)
}
} else {
if (app.__main__) {
return app.__main__.apply(app, req.path)
} else {
err = new Error('__main__() not found')
} }
} }
err.status = 404
var route = req.path.shift()
var act = route + 'Action'
if (app[act]) {
return app[act].apply(app, req.path)
} else {
err = new Error(`Route [${route}] not found`)
err.status = 404
}
} else { } else {
err = new Error(`Controller [${req.app}] load error`) err = new Error(`Controller [${req.app}] load error`)
err.status = 500 err.status = 500

View File

@ -1,15 +1,16 @@
{ {
"name": "@gm5/core", "name": "@gm5/core",
"version": "3.2.6", "version": "1.0.0",
"type": "module", "type": "module",
"description": "Five.js, 一个轻量级的nodejs mvc框架 旨在简单易用, 5分钟即可上手", "description": "Five.js, 一个轻量级的nodejs mvc框架 旨在简单易用, 5分钟即可上手",
"author": "yutent <yutent.io@gmail.com>", "author": "yutent <yutent.io@gmail.com>",
"main": "index.js", "main": "index.js",
"dependencies": { "dependencies": {
"@gm5/session": "^1.0.0", "@gm5/session": "^1.0.0",
"@gm5/request": "^1.2.0", "@gm5/request": "^1.2.1",
"@gm5/response": "^1.3.0", "@gm5/response": "^1.3.1",
"@gm5/controller": "^1.0.0", "@gm5/controller": "^1.0.0",
"@gm5/jwt": "^1.1.0",
"crypto.js": "^2.0.1", "crypto.js": "^2.0.1",
"es.shim": "^2.0.1", "es.shim": "^2.0.1",
"iofs": "^1.5.0" "iofs": "^1.5.0"