Compare commits
No commits in common. "master" and "v2" have entirely different histories.
|
@ -11,10 +11,6 @@
|
|||
|
||||
框架要求 nodejs 版本在 12.0 或以上, 并且只支持使用`import/export`
|
||||
|
||||
## 文档
|
||||
|
||||
[文档](/gm5/core/wiki)
|
||||
|
||||
## 启用方法(步骤)
|
||||
|
||||
**注**
|
||||
|
@ -51,7 +47,7 @@ app.preload('./apps/') // [必须], 预加载应用目录
|
|||
app.listen(3001) // 默认是3000
|
||||
```
|
||||
|
||||
其他的配置和功能, 请参考 [文档](/gm5/core/wiki)。
|
||||
其他的配置和功能, 请参考 [文档](/gm5/request/wiki)。
|
||||
|
||||
|
||||
3. 启动应用。在项目根目录打开终端, 输入以下命令 `npm create five`, 然后根据提示操作, 即可
|
||||
|
|
|
@ -8,8 +8,8 @@ const ENV_PROD = 'production'
|
|||
const ENV_DEV = 'development'
|
||||
|
||||
export default {
|
||||
// 动态路由模式, 即无论是访问路径是什么, 永远只会调用 \apps\index\index()
|
||||
dynamic: false,
|
||||
db: {},
|
||||
spa: false, // 单路由模式, 即无论是访问路径是什么, 永远只会调用 \apps\index\index()
|
||||
port: 3000,
|
||||
env: process.env.NODE_ENV === ENV_PROD ? ENV_PROD : ENV_DEV,
|
||||
debug: process.env.NODE_ENV === ENV_DEV, // debug模式
|
||||
|
|
|
@ -1,32 +0,0 @@
|
|||
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
|
||||
}
|
135
index.js
135
index.js
|
@ -24,19 +24,15 @@ process.on('uncaughtException', err => {
|
|||
|
||||
class Five {
|
||||
#config = config
|
||||
#controllers = {}
|
||||
#modules = {}
|
||||
#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) {
|
||||
|
@ -47,33 +43,6 @@ 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() {
|
||||
|
@ -107,70 +76,78 @@ class Five {
|
|||
return this.#config[key]
|
||||
}
|
||||
|
||||
/**
|
||||
* 加载中间件
|
||||
* 与别的中间件用法有些不一样, 回调的传入参数中的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')
|
||||
// 加载中间件
|
||||
// 与别的中间件用法有些不一样, 回调的传入参数中的req和res,
|
||||
// 并非原生的request对象和response对象,
|
||||
// 而是框架内部封装过的,可通过origin属性访问原生的对象
|
||||
use(fn = noop) {
|
||||
if (typeof fn === 'function') {
|
||||
this.#middlewares.push(fn)
|
||||
return this
|
||||
}
|
||||
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
|
||||
}
|
||||
|
||||
/**
|
||||
* 注入中间件, 与use方法不同, install方法会立即执行
|
||||
* @deprecated 请使用use方法, 将在下个版本中移除
|
||||
*/
|
||||
install(middleware, args) {
|
||||
return this.#install(middleware, args)
|
||||
// 预加载应用, 缓存以提高性能
|
||||
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
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* 预加载应用, 缓存以提高性能
|
||||
* @deprecated 请使用use方法, 将在下个版本中移除
|
||||
*/
|
||||
preload(dir) {
|
||||
this.#preload(mount(dir))
|
||||
return this
|
||||
}
|
||||
|
||||
$load(name) {
|
||||
return this.#controllers[name]
|
||||
return this.#modules[name]
|
||||
}
|
||||
|
||||
// 启动http服务
|
||||
listen(port = 3000, callback = noop) {
|
||||
if (this.#online) {
|
||||
return console.error('Server already started')
|
||||
listen(port) {
|
||||
this.set({ port })
|
||||
return this
|
||||
}
|
||||
|
||||
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)
|
||||
|
@ -178,28 +155,18 @@ class Five {
|
|||
.on('listening', _ => {
|
||||
if (this.get('debug')) {
|
||||
console.log('Server successfully started ...')
|
||||
console.log('%s://%s:%d\n', 'http', '127.0.0.1', port)
|
||||
}
|
||||
// 未开启跨域时, 移除跨域中间件, 以提高性能
|
||||
if (!this.get('cors').enabled) {
|
||||
this.#middlewares.shift()
|
||||
console.log('%s://%s:%d\n', 'http', '127.0.0.1', this.get('port'))
|
||||
}
|
||||
})
|
||||
.on('error', err => {
|
||||
console.error(err)
|
||||
})
|
||||
.listen(port)
|
||||
.listen(this.get('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,20 +4,18 @@
|
|||
* @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')
|
||||
|
||||
if (opts.enabled) {
|
||||
let origin = req.headers['origin'] || req.headers['referer'] || ''
|
||||
let headers = req.headers['access-control-request-headers']
|
||||
let origin = req.header('origin') || req.header('referer') || ''
|
||||
let headers = req.header('access-control-request-headers')
|
||||
let { hostname, host, protocol } = parse(origin)
|
||||
|
||||
if (!origin) {
|
||||
return next()
|
||||
}
|
||||
let { hostname, host, protocol } = new URL(origin)
|
||||
|
||||
if (opts.origin.length) {
|
||||
if (opts.origin.length && hostname) {
|
||||
let pass = false
|
||||
for (let it of opts.origin) {
|
||||
if (hostname.endsWith(it)) {
|
||||
|
@ -26,7 +24,7 @@ export function createCors() {
|
|||
}
|
||||
}
|
||||
if (pass === false) {
|
||||
return (res.body = null)
|
||||
return res.end('')
|
||||
}
|
||||
}
|
||||
if (opts.credentials) {
|
||||
|
@ -34,7 +32,7 @@ export function createCors() {
|
|||
}
|
||||
|
||||
res.set('Access-Control-Allow-Origin', `${protocol}//${host}`)
|
||||
res.set('Access-Control-Allow-Methods', '*')
|
||||
res.set('Access-Control-Allow-Methods', req.method)
|
||||
|
||||
if (headers) {
|
||||
res.set('Access-Control-Allow-Headers', headers)
|
||||
|
@ -45,7 +43,7 @@ export function createCors() {
|
|||
}
|
||||
|
||||
if (req.method === 'OPTIONS') {
|
||||
return (res.body = null)
|
||||
return res.end('')
|
||||
}
|
||||
}
|
||||
next()
|
||||
|
|
|
@ -7,29 +7,28 @@
|
|||
import { readonlyProp } from '../lib.js'
|
||||
|
||||
export function createRouter() {
|
||||
return async function (req, res, next) {
|
||||
return 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()
|
||||
let spa = this.get('spa')
|
||||
|
||||
// 1. 先判断控制器是否存在
|
||||
if (!ModuleController) {
|
||||
return res.error(`Controller [${name}] not found`, 404)
|
||||
if (!this.$load(spa ? 'index' : req.controller)) {
|
||||
return res.error(`Controller [${req.controller}] not found`, 404)
|
||||
}
|
||||
|
||||
// 2. 默认二级路由为index
|
||||
if (actions.length < 1 && dynamic === false) {
|
||||
actions.push('index')
|
||||
if (req.path.length < 1 && spa === false) {
|
||||
req.path.push('index')
|
||||
}
|
||||
|
||||
// 3. 实例化控制器
|
||||
try {
|
||||
let route, act
|
||||
this.$load(spa ? 'index' : req.controller)
|
||||
.then(async ModuleController => {
|
||||
let ctrol, route, act
|
||||
let err = ''
|
||||
|
||||
let ctrol = new ModuleController()
|
||||
if (ModuleController) {
|
||||
ctrol = new ModuleController()
|
||||
|
||||
readonlyProp(ctrol, 'context', this)
|
||||
readonlyProp(ctrol, 'request', req)
|
||||
|
@ -48,23 +47,29 @@ export function createRouter() {
|
|||
}
|
||||
}
|
||||
|
||||
if (dynamic) {
|
||||
return ctrol.indexAction.apply(ctrol, actions)
|
||||
if (spa) {
|
||||
return ctrol.indexAction.apply(ctrol, req.path)
|
||||
} else {
|
||||
route = actions.shift()
|
||||
route = req.path.shift()
|
||||
act = route + 'Action'
|
||||
|
||||
if (ctrol[act]) {
|
||||
return ctrol[act].apply(ctrol, actions)
|
||||
return ctrol[act].apply(ctrol, req.path)
|
||||
} 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)
|
||||
} 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)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
|
14
package.json
14
package.json
|
@ -1,24 +1,22 @@
|
|||
{
|
||||
"name": "@gm5/core",
|
||||
"version": "3.0.0",
|
||||
"version": "2.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",
|
||||
"crypto.js": "^3.3.4",
|
||||
"@gm5/jwt": "^2.0.2",
|
||||
"@gm5/views": "^2.0.0",
|
||||
"crypto.js": "^3.1.2",
|
||||
"es.shim": "^2.2.0",
|
||||
"iofs": "^1.5.3"
|
||||
},
|
||||
"optionalDependencies": {
|
||||
"@gm5/session": "^3.0.0",
|
||||
"@gm5/jwt": "^3.0.1",
|
||||
"@gm5/views": "^3.0.0"
|
||||
},
|
||||
"devDependencies": {},
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "https://git.wkit.fun/gm5/core.git"
|
||||
|
|
Loading…
Reference in New Issue