Compare commits
17 Commits
Author | SHA1 | Date |
---|---|---|
|
edbe01b3e1 | |
|
b2de266b92 | |
|
edce8b8cd6 | |
|
a4df422623 | |
|
a14bdd8e41 | |
|
977e710fee | |
|
b5ffd5572d | |
|
1074b56bde | |
|
f89259a20f | |
|
2803e35311 | |
|
7cb670146a | |
|
7646140360 | |
|
b9c752f8c8 | |
|
e436429872 | |
|
79ff113b6f | |
|
0cb5a56a60 | |
|
b1992d69af |
|
@ -0,0 +1,32 @@
|
||||||
|
declare module '@gm5/core' {
|
||||||
|
import { Server } from 'http'
|
||||||
|
import Request from '@gm5/request'
|
||||||
|
import Response from '@gm5/response'
|
||||||
|
|
||||||
|
declare type Mountable = string[]
|
||||||
|
|
||||||
|
interface Middleware {
|
||||||
|
(req: Request, res: Response, next: () => void): void
|
||||||
|
}
|
||||||
|
|
||||||
|
interface Installable {
|
||||||
|
name: string
|
||||||
|
install: (args?: Record<string, any>) => any
|
||||||
|
}
|
||||||
|
|
||||||
|
export default class Five {
|
||||||
|
get server(): Server
|
||||||
|
|
||||||
|
set(obj: object): this
|
||||||
|
|
||||||
|
get(key: string): any
|
||||||
|
|
||||||
|
use(middleware: Middleware | Installable | Mountable, args?: Record<string, any>): this
|
||||||
|
|
||||||
|
listen(port?: number, callback?: () => void): this
|
||||||
|
}
|
||||||
|
|
||||||
|
export function mount(dir?: string): Mountable
|
||||||
|
|
||||||
|
export function createApp(conf?: object): Five
|
||||||
|
}
|
141
index.js
141
index.js
|
@ -24,15 +24,19 @@ process.on('uncaughtException', err => {
|
||||||
|
|
||||||
class Five {
|
class Five {
|
||||||
#config = config
|
#config = config
|
||||||
#modules = {}
|
#controllers = {}
|
||||||
#middlewares = [createCors()]
|
#middlewares = [createCors()]
|
||||||
|
|
||||||
#server = null
|
#server = null
|
||||||
|
#online = false
|
||||||
|
|
||||||
constructor() {
|
constructor() {
|
||||||
readonlyProp(this, 'state', Object.create(null))
|
readonlyProp(this, 'state', Object.create(null))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 循环顺序执行中间件, 直到执行完所有中间件或没有调用next
|
||||||
|
*/
|
||||||
async #loop(req, res, idx = 0) {
|
async #loop(req, res, idx = 0) {
|
||||||
let fn = this.#middlewares[idx]
|
let fn = this.#middlewares[idx]
|
||||||
if (fn) {
|
if (fn) {
|
||||||
|
@ -43,6 +47,33 @@ class Five {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// 注入实例化对象到实例池中
|
||||||
|
#install({ name, install }, args) {
|
||||||
|
this['$$' + name] = install.call(this, args)
|
||||||
|
return this
|
||||||
|
}
|
||||||
|
|
||||||
|
async #preload(list) {
|
||||||
|
for (let item of list) {
|
||||||
|
let { name } = parse(item)
|
||||||
|
if (name.startsWith('.')) {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
// 如果是目录,则默认加载index.js, 其他文件不加载
|
||||||
|
// 交由index.js自行处理, 用于复杂的应用
|
||||||
|
if (fs.isdir(item)) {
|
||||||
|
item = join(item, './index.js')
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
let { default: Module } = await import(item)
|
||||||
|
this.#controllers[name] = Module
|
||||||
|
} catch (err) {
|
||||||
|
console.error(err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/*------------------------------------------------------------------------*/
|
/*------------------------------------------------------------------------*/
|
||||||
|
|
||||||
get server() {
|
get server() {
|
||||||
|
@ -76,78 +107,70 @@ class Five {
|
||||||
return this.#config[key]
|
return this.#config[key]
|
||||||
}
|
}
|
||||||
|
|
||||||
// 加载中间件
|
/**
|
||||||
// 与别的中间件用法有些不一样, 回调的传入参数中的req和res,
|
* 加载中间件
|
||||||
// 并非原生的request对象和response对象,
|
* 与别的中间件用法有些不一样, 回调的传入参数中的req和res,
|
||||||
// 而是框架内部封装过的,可通过origin属性访问原生的对象
|
* 并非原生的request对象和response对象,
|
||||||
use(fn = noop) {
|
* 而是框架内部封装过的,可通过origin属性访问原生的对象
|
||||||
if (typeof fn === 'function') {
|
* @param {*} middleware
|
||||||
this.#middlewares.push(fn)
|
* @returns Five
|
||||||
return this
|
*/
|
||||||
|
use(middleware = noop, args) {
|
||||||
|
if (this.#online) {
|
||||||
|
return console.error('Server already started, cannot use middleware')
|
||||||
|
}
|
||||||
|
if (typeof middleware === 'function') {
|
||||||
|
this.#middlewares.push(middleware)
|
||||||
|
} else if (typeof middleware === 'object' && typeof middleware.install === 'function') {
|
||||||
|
this.#install(middleware, args)
|
||||||
|
} else if (Array.isArray(middleware)) {
|
||||||
|
this.#preload(middleware)
|
||||||
|
} else {
|
||||||
|
throw TypeError('argument must be a function or installable object')
|
||||||
}
|
}
|
||||||
throw TypeError('argument must be a function')
|
|
||||||
}
|
|
||||||
|
|
||||||
// 注入实例化对象到实例池中
|
|
||||||
// 与use方法不同的是, 这个会在server创建之前就已经执行
|
|
||||||
install({ name, install }, args) {
|
|
||||||
this['$$' + name] = install.call(this, args)
|
|
||||||
return this
|
return this
|
||||||
}
|
}
|
||||||
|
|
||||||
// 预加载应用, 缓存以提高性能
|
/**
|
||||||
|
* 注入中间件, 与use方法不同, install方法会立即执行
|
||||||
|
* @deprecated 请使用use方法, 将在下个版本中移除
|
||||||
|
*/
|
||||||
|
install(middleware, args) {
|
||||||
|
return this.#install(middleware, args)
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 预加载应用, 缓存以提高性能
|
||||||
|
* @deprecated 请使用use方法, 将在下个版本中移除
|
||||||
|
*/
|
||||||
preload(dir) {
|
preload(dir) {
|
||||||
let list = fs.ls(dir)
|
this.#preload(mount(dir))
|
||||||
|
|
||||||
if (list) {
|
|
||||||
list.forEach(item => {
|
|
||||||
let { name } = parse(item)
|
|
||||||
if (name.startsWith('.')) {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
// 如果是目录,则默认加载index.js, 其他文件不加载
|
|
||||||
// 交由index.js自行处理, 用于复杂的应用
|
|
||||||
if (fs.isdir(item)) {
|
|
||||||
item = join(item, './index.js')
|
|
||||||
}
|
|
||||||
|
|
||||||
this.#modules[name] = import(item)
|
|
||||||
.then(r => r.default)
|
|
||||||
.catch(err => {
|
|
||||||
console.error(err)
|
|
||||||
return null
|
|
||||||
})
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
return this
|
return this
|
||||||
}
|
}
|
||||||
|
|
||||||
$load(name) {
|
$load(name) {
|
||||||
return this.#modules[name]
|
return this.#controllers[name]
|
||||||
}
|
}
|
||||||
|
|
||||||
// 启动http服务
|
// 启动http服务
|
||||||
listen(port) {
|
listen(port = 3000, callback = noop) {
|
||||||
this.set({ port })
|
if (this.#online) {
|
||||||
return this
|
return console.error('Server already started')
|
||||||
}
|
}
|
||||||
|
|
||||||
run() {
|
|
||||||
this.#server = http.createServer()
|
|
||||||
|
|
||||||
// 路由中间件要在最后
|
// 路由中间件要在最后
|
||||||
this.use(createRouter())
|
this.use(createRouter())
|
||||||
|
|
||||||
|
this.set({ port })
|
||||||
|
this.#online = true
|
||||||
|
|
||||||
|
this.#server = http.createServer()
|
||||||
|
|
||||||
this.#server
|
this.#server
|
||||||
.on('request', (req, res) => {
|
.on('request', (req, res) => {
|
||||||
let request = new Request(req, res)
|
let request = new Request(req, res)
|
||||||
let response = new Response(req, res)
|
let response = new Response(req, res)
|
||||||
|
|
||||||
if (response.ended) {
|
|
||||||
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)
|
this.#loop(request, response)
|
||||||
|
@ -155,18 +178,28 @@ class Five {
|
||||||
.on('listening', _ => {
|
.on('listening', _ => {
|
||||||
if (this.get('debug')) {
|
if (this.get('debug')) {
|
||||||
console.log('Server successfully started ...')
|
console.log('Server successfully started ...')
|
||||||
console.log('%s://%s:%d\n', 'http', '127.0.0.1', this.get('port'))
|
console.log('%s://%s:%d\n', 'http', '127.0.0.1', port)
|
||||||
|
}
|
||||||
|
// 未开启跨域时, 移除跨域中间件, 以提高性能
|
||||||
|
if (!this.get('cors').enabled) {
|
||||||
|
this.#middlewares.shift()
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
.on('error', err => {
|
.on('error', err => {
|
||||||
console.error(err)
|
console.error(err)
|
||||||
})
|
})
|
||||||
.listen(this.get('port'))
|
.listen(port)
|
||||||
|
|
||||||
|
callback.call(this, this.#server)
|
||||||
return this
|
return this
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export function mount(dir) {
|
||||||
|
let list = fs.ls(dir) || []
|
||||||
|
return list
|
||||||
|
}
|
||||||
|
|
||||||
export function createApp(conf = {}) {
|
export function createApp(conf = {}) {
|
||||||
let app = new Five()
|
let app = new Five()
|
||||||
app.set(conf)
|
app.set(conf)
|
||||||
|
|
|
@ -4,8 +4,6 @@
|
||||||
* @date 2020/09/18 14:55:49
|
* @date 2020/09/18 14:55:49
|
||||||
*/
|
*/
|
||||||
|
|
||||||
import { parse } from 'node:url'
|
|
||||||
|
|
||||||
export function createCors() {
|
export function createCors() {
|
||||||
return function (req, res, next) {
|
return function (req, res, next) {
|
||||||
let opts = this.get('cors')
|
let opts = this.get('cors')
|
||||||
|
@ -13,9 +11,13 @@ export function createCors() {
|
||||||
if (opts.enabled) {
|
if (opts.enabled) {
|
||||||
let origin = req.headers['origin'] || req.headers['referer'] || ''
|
let origin = req.headers['origin'] || req.headers['referer'] || ''
|
||||||
let headers = req.headers['access-control-request-headers']
|
let headers = req.headers['access-control-request-headers']
|
||||||
let { hostname, host, protocol } = parse(origin)
|
|
||||||
|
|
||||||
if (opts.origin.length && hostname) {
|
if (!origin) {
|
||||||
|
return next()
|
||||||
|
}
|
||||||
|
let { hostname, host, protocol } = new URL(origin)
|
||||||
|
|
||||||
|
if (opts.origin.length) {
|
||||||
let pass = false
|
let pass = false
|
||||||
for (let it of opts.origin) {
|
for (let it of opts.origin) {
|
||||||
if (hostname.endsWith(it)) {
|
if (hostname.endsWith(it)) {
|
||||||
|
@ -32,7 +34,7 @@ export function createCors() {
|
||||||
}
|
}
|
||||||
|
|
||||||
res.set('Access-Control-Allow-Origin', `${protocol}//${host}`)
|
res.set('Access-Control-Allow-Origin', `${protocol}//${host}`)
|
||||||
res.set('Access-Control-Allow-Methods', req.method)
|
res.set('Access-Control-Allow-Methods', '*')
|
||||||
|
|
||||||
if (headers) {
|
if (headers) {
|
||||||
res.set('Access-Control-Allow-Headers', headers)
|
res.set('Access-Control-Allow-Headers', headers)
|
||||||
|
|
|
@ -7,69 +7,64 @@
|
||||||
import { readonlyProp } from '../lib.js'
|
import { readonlyProp } from '../lib.js'
|
||||||
|
|
||||||
export function createRouter() {
|
export function createRouter() {
|
||||||
return function (req, res, next) {
|
return async function (req, res, next) {
|
||||||
let debug = this.get('debug')
|
let debug = this.get('debug')
|
||||||
let dynamic = this.get('dynamic')
|
let dynamic = this.get('dynamic')
|
||||||
|
let name = dynamic ? 'index' : req.controller
|
||||||
|
let ModuleController = this.$load(name)
|
||||||
|
let actions = req.actions.concat()
|
||||||
|
|
||||||
// 1. 先判断控制器是否存在
|
// 1. 先判断控制器是否存在
|
||||||
if (!this.$load(dynamic ? 'index' : req.controller)) {
|
if (!ModuleController) {
|
||||||
return res.error(`Controller [${req.controller}] not found`, 404)
|
return res.error(`Controller [${name}] not found`, 404)
|
||||||
}
|
}
|
||||||
|
|
||||||
// 2. 默认二级路由为index
|
// 2. 默认二级路由为index
|
||||||
if (req.path.length < 1 && dynamic === false) {
|
if (actions.length < 1 && dynamic === false) {
|
||||||
req.path.push('index')
|
actions.push('index')
|
||||||
}
|
}
|
||||||
|
|
||||||
// 3. 实例化控制器
|
// 3. 实例化控制器
|
||||||
this.$load(dynamic ? 'index' : req.controller)
|
try {
|
||||||
.then(async ModuleController => {
|
let route, act
|
||||||
let ctrol, route, act
|
let err = ''
|
||||||
let err = ''
|
|
||||||
|
|
||||||
if (ModuleController) {
|
let ctrol = new ModuleController()
|
||||||
ctrol = new ModuleController()
|
|
||||||
|
|
||||||
readonlyProp(ctrol, 'context', this)
|
readonlyProp(ctrol, 'context', this)
|
||||||
readonlyProp(ctrol, 'request', req)
|
readonlyProp(ctrol, 'request', req)
|
||||||
readonlyProp(ctrol, 'response', res)
|
readonlyProp(ctrol, 'response', res)
|
||||||
readonlyProp(ctrol, 'name', req.controller)
|
readonlyProp(ctrol, 'name', req.controller)
|
||||||
|
|
||||||
// 4. 优先执行__main__方法
|
// 4. 优先执行__main__方法
|
||||||
if (ctrol.__main__) {
|
if (ctrol.__main__) {
|
||||||
try {
|
try {
|
||||||
let r = await ctrol.__main__()
|
let r = await ctrol.__main__()
|
||||||
if (r === false) {
|
if (r === false) {
|
||||||
return
|
return
|
||||||
}
|
|
||||||
} catch (err) {
|
|
||||||
return Promise.reject(err)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
} catch (err) {
|
||||||
if (dynamic) {
|
return Promise.reject(err)
|
||||||
return ctrol.indexAction.apply(ctrol, req.path)
|
|
||||||
} else {
|
|
||||||
route = req.path.shift()
|
|
||||||
act = route + 'Action'
|
|
||||||
|
|
||||||
if (ctrol[act]) {
|
|
||||||
return ctrol[act].apply(ctrol, req.path)
|
|
||||||
} else {
|
|
||||||
err = new Error(`Action [${route}] not found`)
|
|
||||||
err.status = 404
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
err = new Error(`Controller [${req.controller}] load error`)
|
|
||||||
err.status = 500
|
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
return Promise.reject(err)
|
if (dynamic) {
|
||||||
})
|
return ctrol.indexAction.apply(ctrol, actions)
|
||||||
.catch(err => {
|
} else {
|
||||||
console.error(err)
|
route = actions.shift()
|
||||||
res.error(debug ? err.stack || err : err, err.status || 500)
|
act = route + 'Action'
|
||||||
})
|
|
||||||
|
if (ctrol[act]) {
|
||||||
|
return ctrol[act].apply(ctrol, actions)
|
||||||
|
} else {
|
||||||
|
err = new Error(`Action [${route}] not found`)
|
||||||
|
err.status = 404
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
res.error(debug ? err.stack || err : err, err.status || 500)
|
||||||
|
} catch (err) {
|
||||||
|
console.error(err)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
14
package.json
14
package.json
|
@ -1,22 +1,24 @@
|
||||||
{
|
{
|
||||||
"name": "@gm5/core",
|
"name": "@gm5/core",
|
||||||
"version": "2.0.2",
|
"version": "3.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",
|
||||||
|
"types": "index.d.ts",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@gm5/session": "^2.0.0",
|
|
||||||
"@gm5/request": "^2.0.3",
|
"@gm5/request": "^2.0.3",
|
||||||
"@gm5/response": "^2.0.1",
|
"@gm5/response": "^2.0.1",
|
||||||
"@gm5/controller": "^2.0.2",
|
"@gm5/controller": "^2.0.2",
|
||||||
"@gm5/jwt": "^2.0.2",
|
"crypto.js": "^3.3.4",
|
||||||
"@gm5/views": "^2.0.0",
|
|
||||||
"crypto.js": "^3.1.2",
|
|
||||||
"es.shim": "^2.2.0",
|
"es.shim": "^2.2.0",
|
||||||
"iofs": "^1.5.3"
|
"iofs": "^1.5.3"
|
||||||
},
|
},
|
||||||
"devDependencies": {},
|
"optionalDependencies": {
|
||||||
|
"@gm5/session": "^3.0.0",
|
||||||
|
"@gm5/jwt": "^3.0.1",
|
||||||
|
"@gm5/views": "^3.0.0"
|
||||||
|
},
|
||||||
"repository": {
|
"repository": {
|
||||||
"type": "git",
|
"type": "git",
|
||||||
"url": "https://git.wkit.fun/gm5/core.git"
|
"url": "https://git.wkit.fun/gm5/core.git"
|
||||||
|
|
Loading…
Reference in New Issue