Compare commits
15 Commits
Author | SHA1 | Date |
---|---|---|
|
edbe01b3e1 | |
|
b2de266b92 | |
|
edce8b8cd6 | |
|
a4df422623 | |
|
a14bdd8e41 | |
|
977e710fee | |
|
b5ffd5572d | |
|
1074b56bde | |
|
f89259a20f | |
|
2803e35311 | |
|
7cb670146a | |
|
7646140360 | |
|
b9c752f8c8 | |
|
e436429872 | |
|
79ff113b6f |
|
@ -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
|
||||
}
|
137
index.js
137
index.js
|
@ -24,15 +24,19 @@ process.on('uncaughtException', err => {
|
|||
|
||||
class Five {
|
||||
#config = config
|
||||
#modules = {}
|
||||
#controllers = {}
|
||||
#middlewares = [createCors()]
|
||||
|
||||
#server = null
|
||||
#online = false
|
||||
|
||||
constructor() {
|
||||
readonlyProp(this, 'state', Object.create(null))
|
||||
}
|
||||
|
||||
/**
|
||||
* 循环顺序执行中间件, 直到执行完所有中间件或没有调用next
|
||||
*/
|
||||
async #loop(req, res, idx = 0) {
|
||||
let fn = this.#middlewares[idx]
|
||||
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() {
|
||||
|
@ -76,78 +107,70 @@ class Five {
|
|||
return this.#config[key]
|
||||
}
|
||||
|
||||
// 加载中间件
|
||||
// 与别的中间件用法有些不一样, 回调的传入参数中的req和res,
|
||||
// 并非原生的request对象和response对象,
|
||||
// 而是框架内部封装过的,可通过origin属性访问原生的对象
|
||||
use(fn = noop) {
|
||||
if (typeof fn === 'function') {
|
||||
this.#middlewares.push(fn)
|
||||
return this
|
||||
/**
|
||||
* 加载中间件
|
||||
* 与别的中间件用法有些不一样, 回调的传入参数中的req和res,
|
||||
* 并非原生的request对象和response对象,
|
||||
* 而是框架内部封装过的,可通过origin属性访问原生的对象
|
||||
* @param {*} middleware
|
||||
* @returns Five
|
||||
*/
|
||||
use(middleware = noop, args) {
|
||||
if (this.#online) {
|
||||
return console.error('Server already started, cannot use middleware')
|
||||
}
|
||||
throw TypeError('argument must be a function')
|
||||
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')
|
||||
}
|
||||
|
||||
// 注入实例化对象到实例池中
|
||||
// 与use方法不同的是, 这个会在server创建之前就已经执行
|
||||
install({ name, install }, args) {
|
||||
this['$$' + name] = install.call(this, args)
|
||||
return this
|
||||
}
|
||||
|
||||
// 预加载应用, 缓存以提高性能
|
||||
/**
|
||||
* 注入中间件, 与use方法不同, install方法会立即执行
|
||||
* @deprecated 请使用use方法, 将在下个版本中移除
|
||||
*/
|
||||
install(middleware, args) {
|
||||
return this.#install(middleware, args)
|
||||
}
|
||||
|
||||
/**
|
||||
* 预加载应用, 缓存以提高性能
|
||||
* @deprecated 请使用use方法, 将在下个版本中移除
|
||||
*/
|
||||
preload(dir) {
|
||||
let list = fs.ls(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
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
this.#preload(mount(dir))
|
||||
return this
|
||||
}
|
||||
|
||||
$load(name) {
|
||||
return this.#modules[name]
|
||||
return this.#controllers[name]
|
||||
}
|
||||
|
||||
// 启动http服务
|
||||
listen(port) {
|
||||
this.set({ port })
|
||||
return this
|
||||
listen(port = 3000, callback = noop) {
|
||||
if (this.#online) {
|
||||
return console.error('Server already started')
|
||||
}
|
||||
|
||||
run() {
|
||||
this.#server = http.createServer()
|
||||
|
||||
// 路由中间件要在最后
|
||||
this.use(createRouter())
|
||||
|
||||
this.set({ port })
|
||||
this.#online = true
|
||||
|
||||
this.#server = http.createServer()
|
||||
|
||||
this.#server
|
||||
.on('request', (req, res) => {
|
||||
let request = new Request(req, res)
|
||||
let response = new Response(req, res)
|
||||
|
||||
if (response.ended) {
|
||||
return
|
||||
}
|
||||
|
||||
response.set('X-Powered-By', this.get('X-Powered-By') || 'Five.js')
|
||||
|
||||
this.#loop(request, response)
|
||||
|
@ -155,18 +178,28 @@ class Five {
|
|||
.on('listening', _ => {
|
||||
if (this.get('debug')) {
|
||||
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 => {
|
||||
console.error(err)
|
||||
})
|
||||
.listen(this.get('port'))
|
||||
.listen(port)
|
||||
|
||||
callback.call(this, this.#server)
|
||||
return this
|
||||
}
|
||||
}
|
||||
|
||||
export function mount(dir) {
|
||||
let list = fs.ls(dir) || []
|
||||
return list
|
||||
}
|
||||
|
||||
export function createApp(conf = {}) {
|
||||
let app = new Five()
|
||||
app.set(conf)
|
||||
|
|
|
@ -4,8 +4,6 @@
|
|||
* @date 2020/09/18 14:55:49
|
||||
*/
|
||||
|
||||
import { parse } from 'node:url'
|
||||
|
||||
export function createCors() {
|
||||
return function (req, res, next) {
|
||||
let opts = this.get('cors')
|
||||
|
@ -13,9 +11,13 @@ export function createCors() {
|
|||
if (opts.enabled) {
|
||||
let origin = req.headers['origin'] || req.headers['referer'] || ''
|
||||
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
|
||||
for (let it of opts.origin) {
|
||||
if (hostname.endsWith(it)) {
|
||||
|
|
|
@ -7,28 +7,29 @@
|
|||
import { readonlyProp } from '../lib.js'
|
||||
|
||||
export function createRouter() {
|
||||
return function (req, res, next) {
|
||||
return async function (req, res, next) {
|
||||
let debug = this.get('debug')
|
||||
let dynamic = this.get('dynamic')
|
||||
let name = dynamic ? 'index' : req.controller
|
||||
let ModuleController = this.$load(name)
|
||||
let actions = req.actions.concat()
|
||||
|
||||
// 1. 先判断控制器是否存在
|
||||
if (!this.$load(dynamic ? 'index' : req.controller)) {
|
||||
return res.error(`Controller [${req.controller}] not found`, 404)
|
||||
if (!ModuleController) {
|
||||
return res.error(`Controller [${name}] not found`, 404)
|
||||
}
|
||||
|
||||
// 2. 默认二级路由为index
|
||||
if (req.path.length < 1 && dynamic === false) {
|
||||
req.path.push('index')
|
||||
if (actions.length < 1 && dynamic === false) {
|
||||
actions.push('index')
|
||||
}
|
||||
|
||||
// 3. 实例化控制器
|
||||
this.$load(dynamic ? 'index' : req.controller)
|
||||
.then(async ModuleController => {
|
||||
let ctrol, route, act
|
||||
try {
|
||||
let route, act
|
||||
let err = ''
|
||||
|
||||
if (ModuleController) {
|
||||
ctrol = new ModuleController()
|
||||
let ctrol = new ModuleController()
|
||||
|
||||
readonlyProp(ctrol, 'context', this)
|
||||
readonlyProp(ctrol, 'request', req)
|
||||
|
@ -48,28 +49,22 @@ export function createRouter() {
|
|||
}
|
||||
|
||||
if (dynamic) {
|
||||
return ctrol.indexAction.apply(ctrol, req.path)
|
||||
return ctrol.indexAction.apply(ctrol, actions)
|
||||
} else {
|
||||
route = req.path.shift()
|
||||
route = actions.shift()
|
||||
act = route + 'Action'
|
||||
|
||||
if (ctrol[act]) {
|
||||
return ctrol[act].apply(ctrol, req.path)
|
||||
return ctrol[act].apply(ctrol, actions)
|
||||
} 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)
|
||||
})
|
||||
.catch(err => {
|
||||
console.error(err)
|
||||
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",
|
||||
"version": "2.0.3",
|
||||
"version": "3.0.0",
|
||||
"type": "module",
|
||||
"description": "Five.js, 一个轻量级的nodejs mvc框架 旨在简单易用, 5分钟即可上手",
|
||||
"author": "yutent <yutent.io@gmail.com>",
|
||||
"main": "index.js",
|
||||
"types": "index.d.ts",
|
||||
"dependencies": {
|
||||
"@gm5/session": "^2.0.0",
|
||||
"@gm5/request": "^2.0.3",
|
||||
"@gm5/response": "^2.0.1",
|
||||
"@gm5/controller": "^2.0.2",
|
||||
"@gm5/jwt": "^2.0.2",
|
||||
"@gm5/views": "^2.0.0",
|
||||
"crypto.js": "^3.1.2",
|
||||
"crypto.js": "^3.3.4",
|
||||
"es.shim": "^2.2.0",
|
||||
"iofs": "^1.5.3"
|
||||
},
|
||||
"devDependencies": {},
|
||||
"optionalDependencies": {
|
||||
"@gm5/session": "^3.0.0",
|
||||
"@gm5/jwt": "^3.0.1",
|
||||
"@gm5/views": "^3.0.0"
|
||||
},
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "https://git.wkit.fun/gm5/core.git"
|
||||
|
|
Loading…
Reference in New Issue