Compare commits

..

No commits in common. "f939dcca395fb3e36393109e4662f7b07bbdcc94" and "04069523d352a7c05dec8ea4f701c2893b6e157b" have entirely different histories.

5 changed files with 79 additions and 114 deletions

View File

@ -51,8 +51,8 @@ export default {
origin: [], // ['abc.com', 'a.foo.com'] origin: [], // ['abc.com', 'a.foo.com']
maxAge: 14400 maxAge: 14400
}, },
// 常用正则
regexp: { regexp: {
// 常用正则
email: /^[\w\.\-]+@\w+([\.\-]\w+)*\.\w+$/, email: /^[\w\.\-]+@\w+([\.\-]\w+)*\.\w+$/,
uname: /^[A-Za-z\d_]{4,16}$/, uname: /^[A-Za-z\d_]{4,16}$/,
passwd: /^\S{6,20}$/, passwd: /^\S{6,20}$/,

125
index.js
View File

@ -11,75 +11,77 @@ import fs from 'iofs'
import Request from '@gm5/request' import Request from '@gm5/request'
import Response from '@gm5/response' import Response from '@gm5/response'
import Views from '@gm5/views'
// import { sessionPackage, sessionConnect } from '@gm5/session' import { sessionPackage, sessionConnect } from '@gm5/session'
// import { jwtPackage, jwtConnect } from '@gm5/jwt' import { jwtPackage, jwtConnect } from '@gm5/jwt'
import config from './config/index.js' import config from './config/index.js'
import Routers from './middleware/router.js' import Routers from './middleware/router.js'
import Cors from './middleware/cors.js' import Cors from './middleware/cors.js'
function hideProperty(host, name, value) {
Object.defineProperty(host, name, {
value: value,
enumerable: false
})
}
process.on('uncaughtException', err => { process.on('uncaughtException', err => {
console.error('UncaughtException: ', err) console.error('UncaughtException: ', err)
}) })
class Five { export default class Five {
#config = config constructor() {
#modules = {} hideProperty(this, '__FIVE__', config)
#middlewares = [Cors] hideProperty(this, '__MODULES__', {})
hideProperty(this, '__MIDDLEWARE__', [Cors])
}
#loadBuildIn() { __main__() {
let { domain, website, session, jwt } = this.#config var { domain, website, session, jwt } = 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 })
// 安装模板引擎
this.install(Views)
// 将jwt & session中间件提到最前 // 将jwt & session中间件提到最前
// 以便用户自定义的中间件可以直接操作session // 以便用户自定义的中间件可以直接操作session
// if (session.enabled) { if (session.enabled) {
// this.install(sessionPackage) this.install(sessionPackage)
// this.#middlewares.unshift(sessionConnect) this.__MIDDLEWARE__.unshift(sessionConnect)
// } }
// // 开启jwt // 开启jwt
// if (jwt) { if (jwt) {
// this.install(jwtPackage) this.install(jwtPackage)
// this.#middlewares.unshift(jwtConnect) this.__MIDDLEWARE__.unshift(jwtConnect)
// } }
// 路由中间件要在最后 // 路由中间件要在最后
this.use(Routers) this.use(Routers)
} }
async #loop(req, res, idx = 0) {
let fn = this.#middlewares[idx]
if (fn) {
await fn.call(this, req, res, _ => {
idx++
this.#loop(req, res, idx)
})
}
}
/*------------------------------------------------------------------------*/ /*------------------------------------------------------------------------*/
// 注册属性到全局Five对象 // 注册属性到全局Five对象
set(obj) { set(obj) {
for (let i in obj) { for (let i in obj) {
if (typeof obj[i] === 'object' && !Array.isArray(obj[i])) { if (typeof obj[i] === 'object' && !Array.isArray(obj[i])) {
if (!this.#config[i]) { if (!this.__FIVE__[i]) {
this.#config[i] = obj[i] this.__FIVE__[i] = obj[i]
} else { } else {
try { try {
Object.assign(this.#config[i], obj[i]) Object.assign(this.__FIVE__[i], obj[i])
} catch (err) { } catch (err) {
console.error(err) console.error(err)
} }
} }
} else { } else {
this.#config[i] = obj[i] this.__FIVE__[i] = obj[i]
} }
} }
return this return this
@ -87,7 +89,7 @@ class Five {
// 获取全局配置 // 获取全局配置
get(key) { get(key) {
return this.#config[key] return this.__FIVE__[key]
} }
// 加载中间件 // 加载中间件
@ -96,7 +98,7 @@ class Five {
// 而是框架内部封装过的,可通过origin属性访问原生的对象 // 而是框架内部封装过的,可通过origin属性访问原生的对象
use(fn) { use(fn) {
if (typeof fn === 'function') { if (typeof fn === 'function') {
this.#middlewares.push(fn) this.__MIDDLEWARE__.push(fn)
return this return this
} }
throw TypeError('argument must be a function') throw TypeError('argument must be a function')
@ -125,9 +127,7 @@ class Five {
item = path.join(item, './index.js') item = path.join(item, './index.js')
} }
this.#modules[name] = import(item) this.__MODULES__[name] = import(item).catch(err => {
.then(r => r.default)
.catch(err => {
console.error(err) console.error(err)
return { default: null } return { default: null }
}) })
@ -137,51 +137,40 @@ class Five {
return this return this
} }
$load(name) {
return this.#modules[name]
}
// 启动http服务 // 启动http服务
listen(port) { listen(port) {
this.set({ port }) var _this = this
return this var server
}
run() { this.__main__()
this.#loadBuildIn()
let server = http.createServer() server = http.createServer(function (req, res) {
var request = new Request(req, res)
var response = new Response(req, res)
this.server = server var middleware = _this.__MIDDLEWARE__.concat()
var fn = middleware.shift()
server
.on('request', (req, res) => {
let request = new Request(req, res)
let response = new Response(req, res)
if (response.rendered) { if (response.rendered) {
return return
} }
response.set('X-Powered-By', this.get('X-Powered-By') || 'Five.js') response.set('X-Powered-By', _this.get('X-Powered-By') || 'Five.js')
this.#loop(request, response) if (fn) {
}) ;(async function next() {
.on('listening', _ => { await fn.call(_this, request, response, function () {
if(this.get('debug')){ fn = middleware.shift()
console.log('Server successfully started ...') if (fn) {
console.log('%s://%s:%d\n', 'http', '127.0.0.1', this.get('port')) next()
} }
}) })
.on('error', err => { })()
console.error(err) }
}) })
.listen(this.get('port'))
return this server.listen(port || this.get('port'))
return server
} }
} }
export function createApp() {
return new Five()
}

17
lib.js
View File

@ -1,17 +0,0 @@
/**
* {}
* @author yutent<yutent.io@gmail.com>
* @date 2023/10/24 18:23:21
*/
export function noop() {}
export function readonlyProp(host, name, value) {
Object.defineProperty(host, name, {
get() {
return value
},
set(vale) {},
enumerable: false
})
}

View File

@ -4,14 +4,12 @@
* @date 2020/09/18 15:16:29 * @date 2020/09/18 15:16:29
*/ */
import { readonlyProp } from '../lib.js'
export default function (req, res, next) { export default function (req, res, next) {
var debug = this.get('debug') var debug = this.get('debug')
var spa = this.get('spa') var spa = this.get('spa')
// 1. 先判断控制器是否存在 // 1. 先判断控制器是否存在
if (!this.$load(spa ? 'index' : req.app)) { if (!this.__MODULES__[spa ? 'index' : req.app]) {
return res.error(`Controller [${req.app}] not found`, 404) return res.error(`Controller [${req.app}] not found`, 404)
} }
@ -21,23 +19,19 @@ export default function (req, res, next) {
} }
// 3. 实例化控制器 // 3. 实例化控制器
this.$load(spa ? 'index' : req.app) this.__MODULES__[spa ? 'index' : req.app]
.then(async Module => { .then(async ({ default: Mod }) => {
let mod, route, act let app, route, act
let err = '' let err = ''
if (Module) { if (Mod) {
mod = new Module() app = new Mod()
app.__f_i_v_e__(this, req, res)
readonlyProp(mod, 'context', this)
readonlyProp(mod, 'request', req)
readonlyProp(mod, 'response', res)
readonlyProp(mod, 'name', req.app)
// 4. 优先执行__main__方法 // 4. 优先执行__main__方法
if (mod.__main__) { if (app.__main__) {
try { try {
let r = await mod.__main__() let r = await app.__main__()
if (r === false) { if (r === false) {
return return
} }
@ -47,13 +41,13 @@ export default function (req, res, next) {
} }
if (spa) { if (spa) {
return mod.indexAction.apply(mod, req.path) return app.indexAction.apply(app, req.path)
} else { } else {
route = req.path.shift() route = req.path.shift()
act = route + 'Action' act = route + 'Action'
if (mod[act]) { if (app[act]) {
return mod[act].apply(mod, req.path) return app[act].apply(app, req.path)
} else { } else {
err = new Error(`Action [${route}] not found`) err = new Error(`Action [${route}] not found`)
err.status = 404 err.status = 404
@ -67,7 +61,6 @@ export default function (req, res, next) {
return Promise.reject(err) return Promise.reject(err)
}) })
.catch(err => { .catch(err => {
console.error(err)
res.error(debug ? err.stack || err : err, err.status || 500) res.error(debug ? err.stack || err : err, err.status || 500)
}) })
} }

View File

@ -1,6 +1,6 @@
{ {
"name": "@gm5/core", "name": "@gm5/core",
"version": "2.0.0", "version": "1.1.5",
"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>",