Compare commits

..

7 Commits

Author SHA1 Message Date
yutent 67a63bf67e 移除多余代码 2023-11-02 10:54:37 +08:00
yutent 98c1033392 依赖更新; 模块更新 2023-11-01 18:46:47 +08:00
yutent 566432e529 update 2023-10-31 18:52:54 +08:00
yutent e3ab578088 调整中间件的执行逻辑;调整路由的流程; 2023-10-31 14:40:59 +08:00
yutent 170ac89ba7 一波重构 2023-10-27 19:16:59 +08:00
yutent f939dcca39 调整代码结构 2023-10-25 18:48:55 +08:00
yutent 26bc8622d2 暂存 2023-10-24 15:24:55 +08:00
7 changed files with 223 additions and 252 deletions

View File

@ -22,33 +22,11 @@
* 为了方便下载安装及管理, 推荐使用 five-cli(这是一款专门为框架开发的脚本工具) 进行操作。
```bash
# 全局安装 five-cli
npm i -g @gm5/cli
# 进入项目目录
cd /project/demo
# 初始化一个项目,初始化完成会自动安装所需要的依赖
five-cli init
cd /project/
# 初始化完成之后, 执行以下命令即可启动了,如果需要修改配置,可以先修改好再启动
five-cli start
```
* 也可以自行通过 npm 安装, 自己构建启动配置
```bash
# 进入项目目录
cd /project/demo
npm i @gm5/core
mkdir apps public data views
touch app.js
# 自行编辑app.js, 然后通过node, pm2启动项目即可
#
# import Five from '@gm5/core'
# var app = new Five()
# app.repload('./apps')
# app.listen(8000)
npm create five
```
@ -58,38 +36,26 @@ touch app.js
建立启动文件, 如 app.js
```javascript
'use strict'
import Five from '@gm5/core'
import { createApp } from '@gm5/core'
var app = new Five()
const app = new createApp()
app.set({ website: 'www.your_domain.com' })
// 设置域cookie用到不设置则等同于website
// app.set({ domain: 'your_domain.com' })
// [可选], 但是要用到模板渲染页面时, 必须指定
// app.set({ views: { enabled: true, dir: './views/'} })
app.preload('./apps/') // [必须], 预加载应用目录
app.listen(3001) // 默认是3000
```
其他的配置和功能, 请参考 [文档](https://github.com/bytedo/gmf.core/wiki)。
其他的配置和功能, 请参考 [文档](/gm5/request/wiki)。
3. 启动应用。在项目根目录打开终端, 输入以下命令 `five-cli start`, 然后根据提示操作, 即可
3. 启动应用。在项目根目录打开终端, 输入以下命令 `npm create five`, 然后根据提示操作, 即可
```bash
# 初始化完成之后, 执行以下命令即可启动了,如果需要修改配置,可以先修改好再启动
five-cli start
不是使用five-cli创建的项目, 可使用node/pm2等启动项目
node app.js
# or
pm2 start app.js
pm2 start app.dev.yaml
# 正式环境执行
pm2 start app.yaml
```
@ -123,6 +89,7 @@ server {
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header Host $http_host;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_set_header X-NginX-Proxy true;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
@ -130,7 +97,7 @@ server {
proxy_max_temp_file_size 0;
proxy_pass http://five_upstream;
proxy_redirect off;
proxy_read_timeout 240s;
proxy_read_timeout 60s;
}
}
```

View File

@ -9,50 +9,19 @@ const ENV_DEV = 'development'
export default {
db: {},
session: {
enabled: false,
ttl: 3600 * 24 * 7,
domain: '', // NODESSID域, 默认等于domain
level: 0, // 校验级别, 0: 不校验客户端, 2: ua, 4: ip, 6: ua + ip
db: {
host: '127.0.0.1',
port: 6379,
db: 0
}
},
jwt: {
// jwt 开关
enabled: false,
ttl: 3600 * 24 * 7,
level: 0, // 校验级别, 0: 不校验客户端, 2: ua, 4: ip, 6: ua + ip
secret: 'it_is_secret_key' // jwt密钥, 使用时请修改
},
spa: false, // 单路由模式, 即无论是访问路径是什么, 永远只会调用 \apps\index\index()
website: 'localhost',
domain: '', // cookie域, 默认等于website
port: 3000,
env: process.env.NODE_ENV === ENV_PROD ? ENV_PROD : ENV_DEV,
debug: process.env.NODE_ENV === ENV_DEV, // debug模式
smtp: {
host: 'smtp.example.com',
port: 25,
mail: 'no-reply@example.com',
name: 'no-reply',
passwd: ''
},
views: {
enabled: false,
dir: '',
ext: '.htm'
},
cors: {
enabled: false,
credentials: false,
origin: [], // ['abc.com', 'a.foo.com']
maxAge: 14400
},
regexp: {
// 常用正则
regexp: {
email: /^[\w\.\-]+@\w+([\.\-]\w+)*\.\w+$/,
uname: /^[A-Za-z\d_]{4,16}$/,
passwd: /^\S{6,20}$/,

144
index.js
View File

@ -5,64 +5,48 @@
*/
import 'es.shim' // 加载拓展方法
import http from 'http'
import path from 'path'
import http from 'node:http'
import { parse, join } from 'node:path'
import fs from 'iofs'
import Request from '@gm5/request'
import Response from '@gm5/response'
import Views from '@gm5/views'
import { sessionPackage, sessionConnect } from '@gm5/session'
import { jwtPackage, jwtConnect } from '@gm5/jwt'
import { noop, readonlyProp } from './lib.js'
import config from './config/index.js'
import Routers from './middleware/router.js'
import Cors from './middleware/cors.js'
function hideProperty(host, name, value) {
Object.defineProperty(host, name, {
value: value,
enumerable: false
})
}
import { createCors } from './middleware/cors.js'
import { createRouter } from './middleware/router.js'
process.on('uncaughtException', err => {
console.error('UncaughtException: ', err)
})
export default class Five {
class Five {
#config = config
#modules = {}
#middlewares = [createCors()]
#server = null
constructor() {
hideProperty(this, '__FIVE__', config)
hideProperty(this, '__MODULES__', {})
hideProperty(this, '__MIDDLEWARE__', [Cors])
readonlyProp(this, 'state', Object.create(null))
}
__main__() {
var { domain, website, session, jwt } = this.__FIVE__
domain = domain || website
session.domain = session.domain || domain
this.set({ domain, session })
// 安装模板引擎
this.install(Views)
// 将jwt & session中间件提到最前
// 以便用户自定义的中间件可以直接操作session
if (session.enabled) {
this.install(sessionPackage)
this.__MIDDLEWARE__.unshift(sessionConnect)
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)
})
}
// 开启jwt
if (jwt) {
this.install(jwtPackage)
this.__MIDDLEWARE__.unshift(jwtConnect)
}
// 路由中间件要在最后
this.use(Routers)
/*------------------------------------------------------------------------*/
get server() {
return this.#server
}
/*------------------------------------------------------------------------*/
@ -71,17 +55,17 @@ export default class Five {
set(obj) {
for (let i in obj) {
if (typeof obj[i] === 'object' && !Array.isArray(obj[i])) {
if (!this.__FIVE__[i]) {
this.__FIVE__[i] = obj[i]
if (!this.#config[i]) {
this.#config[i] = obj[i]
} else {
try {
Object.assign(this.__FIVE__[i], obj[i])
Object.assign(this.#config[i], obj[i])
} catch (err) {
console.error(err)
}
}
} else {
this.__FIVE__[i] = obj[i]
this.#config[i] = obj[i]
}
}
return this
@ -89,16 +73,16 @@ export default class Five {
// 获取全局配置
get(key) {
return this.__FIVE__[key]
return this.#config[key]
}
// 加载中间件
// 与别的中间件用法有些不一样, 回调的传入参数中的req和res,
// 并非原生的request对象和response对象,
// 而是框架内部封装过的,可通过origin属性访问原生的对象
use(fn) {
use(fn = noop) {
if (typeof fn === 'function') {
this.__MIDDLEWARE__.push(fn)
this.#middlewares.push(fn)
return this
}
throw TypeError('argument must be a function')
@ -113,23 +97,25 @@ export default class Five {
// 预加载应用, 缓存以提高性能
preload(dir) {
var list = fs.ls(dir)
let list = fs.ls(dir)
if (list) {
list.forEach(item => {
var { name } = path.parse(item)
let { name } = parse(item)
if (name.startsWith('.')) {
return
}
// 如果是目录,则默认加载index.js, 其他文件不加载
// 交由index.js自行处理, 用于复杂的应用
if (fs.isdir(item)) {
item = path.join(item, './index.js')
item = join(item, './index.js')
}
this.__MODULES__[name] = import(item).catch(err => {
this.#modules[name] = import(item)
.then(r => r.default)
.catch(err => {
console.error(err)
return { default: null }
return null
})
})
}
@ -137,40 +123,52 @@ export default class Five {
return this
}
$load(name) {
return this.#modules[name]
}
// 启动http服务
listen(port) {
var _this = this
var server
this.set({ port })
return this
}
this.__main__()
run() {
this.#server = http.createServer()
server = http.createServer(function (req, res) {
var request = new Request(req, res)
var response = new Response(req, res)
// 路由中间件要在最后
this.use(createRouter())
var middleware = _this.__MIDDLEWARE__.concat()
var fn = middleware.shift()
this.#server
.on('request', (req, res) => {
let request = new Request(req, res)
let response = new Response(req, res)
if (response.rendered) {
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')
if (fn) {
;(async function next() {
await fn.call(_this, request, response, function () {
fn = middleware.shift()
if (fn) {
next()
this.#loop(request, response)
})
.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'))
}
})
})()
}
.on('error', err => {
console.error(err)
})
.listen(this.get('port'))
server.listen(port || this.get('port'))
return server
return this
}
}
export function createApp(conf = {}) {
let app = new Five()
app.set(conf)
return app
}

17
lib.js Normal file
View File

@ -0,0 +1,17 @@
/**
* {}
* @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,19 +4,20 @@
* @date 2020/09/18 14:55:49
*/
import url from 'url'
import { parse } from 'node:url'
export default function (req, res, next) {
var CORS = this.get('cors')
export function createCors() {
return function (req, res, next) {
let opts = this.get('cors')
if (CORS.enabled) {
var origin = req.header('origin') || req.header('referer') || ''
var headers = req.header('access-control-request-headers')
var { hostname, host, protocol } = url.parse(origin)
if (opts.enabled) {
let origin = req.header('origin') || req.header('referer') || ''
let headers = req.header('access-control-request-headers')
let { hostname, host, protocol } = parse(origin)
if (CORS.origin.length && hostname) {
var pass = false
for (let it of CORS.origin) {
if (opts.origin.length && hostname) {
let pass = false
for (let it of opts.origin) {
if (hostname.endsWith(it)) {
pass = true
break
@ -26,19 +27,19 @@ export default function (req, res, next) {
return res.end('')
}
}
if (CORS.credentials) {
if (opts.credentials) {
res.set('Access-Control-Allow-Credentials', 'true')
}
res.set('Access-Control-Allow-Origin', `${protocol}//${host}`)
res.set('Access-Control-Allow-Methods', 'GET,HEAD,POST,PUT,DELETE,PATCH')
res.set('Access-Control-Allow-Methods', req.method)
if (headers) {
res.set('Access-Control-Allow-Headers', headers)
}
if (CORS.maxAge) {
res.set('Access-Control-Max-Age', CORS.maxAge)
if (opts.maxAge) {
res.set('Access-Control-Max-Age', opts.maxAge)
}
if (req.method === 'OPTIONS') {
@ -46,4 +47,5 @@ export default function (req, res, next) {
}
}
next()
}
}

View File

@ -4,13 +4,16 @@
* @date 2020/09/18 15:16:29
*/
export default function (req, res, next) {
var debug = this.get('debug')
var spa = this.get('spa')
import { readonlyProp } from '../lib.js'
export function createRouter() {
return function (req, res, next) {
let debug = this.get('debug')
let spa = this.get('spa')
// 1. 先判断控制器是否存在
if (!this.__MODULES__[spa ? 'index' : req.app]) {
return res.error(`Controller [${req.app}] not found`, 404)
if (!this.$load(spa ? 'index' : req.controller)) {
return res.error(`Controller [${req.controller}] not found`, 404)
}
// 2. 默认二级路由为index
@ -19,19 +22,23 @@ export default function (req, res, next) {
}
// 3. 实例化控制器
this.__MODULES__[spa ? 'index' : req.app]
.then(async ({ default: Mod }) => {
let app, route, act
this.$load(spa ? 'index' : req.controller)
.then(async ModuleController => {
let ctrol, route, act
let err = ''
if (Mod) {
app = new Mod()
app.__f_i_v_e__(this, req, res)
if (ModuleController) {
ctrol = new ModuleController()
readonlyProp(ctrol, 'context', this)
readonlyProp(ctrol, 'request', req)
readonlyProp(ctrol, 'response', res)
readonlyProp(ctrol, 'name', req.controller)
// 4. 优先执行__main__方法
if (app.__main__) {
if (ctrol.__main__) {
try {
let r = await app.__main__()
let r = await ctrol.__main__()
if (r === false) {
return
}
@ -41,26 +48,28 @@ export default function (req, res, next) {
}
if (spa) {
return app.indexAction.apply(app, req.path)
return ctrol.indexAction.apply(ctrol, req.path)
} else {
route = req.path.shift()
act = route + 'Action'
if (app[act]) {
return app[act].apply(app, req.path)
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.app}] load error`)
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)
})
}
}

View File

@ -1,31 +1,40 @@
{
"name": "@gm5/core",
"version": "1.1.5",
"version": "2.0.0",
"type": "module",
"description": "Five.js, 一个轻量级的nodejs mvc框架 旨在简单易用, 5分钟即可上手",
"author": "yutent <yutent.io@gmail.com>",
"main": "index.js",
"dependencies": {
"@gm5/session": "^1.1.1",
"@gm5/request": "^1.2.3",
"@gm5/response": "^1.3.1",
"@gm5/controller": "^1.0.0",
"@gm5/jwt": "^1.1.0",
"@gm5/views": "^1.0.0",
"crypto.js": "^3.1.0",
"es.shim": "^2.0.1",
"@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",
"es.shim": "^2.2.0",
"iofs": "^1.5.3"
},
"devDependencies": {},
"repository": {
"type": "git",
"url": "https://github.com/bytedo/gmf.core.git"
"url": "https://git.wkit.fun/gm5/core.git"
},
"keywords": [
"five, fivejs, node-five, five.js, nodejs, mvc, koa, express"
"five",
"fivejs",
"node-five",
"five.js",
"gm5",
"gmf",
"nodejs",
"mvc",
"koa",
"express"
],
"engines": {
"node": ">=10.0.0"
"node": ">=16.0.0"
},
"license": "MIT"
}