Compare commits

..

No commits in common. "master" and "v1" have entirely different histories.
master ... v1

7 changed files with 256 additions and 238 deletions

View File

@ -11,10 +11,6 @@
框架要求 nodejs 版本在 12.0 或以上, 并且只支持使用`import/export`
## 文档
[文档](/gm5/core/wiki)
## 启用方法(步骤)
**注**
@ -26,11 +22,33 @@
* 为了方便下载安装及管理, 推荐使用 five-cli(这是一款专门为框架开发的脚本工具) 进行操作。
```bash
# 全局安装 five-cli
npm i -g @gm5/cli
# 进入项目目录
cd /project/
cd /project/demo
# 初始化一个项目,初始化完成会自动安装所需要的依赖
five-cli init
# 初始化完成之后, 执行以下命令即可启动了,如果需要修改配置,可以先修改好再启动
npm create five
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)
```
@ -40,26 +58,38 @@ npm create five
建立启动文件, 如 app.js
```javascript
'use strict'
import { createApp } from '@gm5/core'
import Five from '@gm5/core'
const app = new createApp()
var app = new Five()
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
```
其他的配置和功能, 请参考 [文档](/gm5/core/wiki)。
其他的配置和功能, 请参考 [文档](https://github.com/bytedo/gmf.core/wiki)。
3. 启动应用。在项目根目录打开终端, 输入以下命令 `npm create five`, 然后根据提示操作, 即可
3. 启动应用。在项目根目录打开终端, 输入以下命令 `five-cli start`, 然后根据提示操作, 即可
```bash
pm2 start app.dev.yaml
# 正式环境执行
pm2 start app.yaml
# 初始化完成之后, 执行以下命令即可启动了,如果需要修改配置,可以先修改好再启动
five-cli start
不是使用five-cli创建的项目, 可使用node/pm2等启动项目
node app.js
# or
pm2 start app.js
```
@ -93,7 +123,6 @@ 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";
@ -101,7 +130,7 @@ server {
proxy_max_temp_file_size 0;
proxy_pass http://five_upstream;
proxy_redirect off;
proxy_read_timeout 60s;
proxy_read_timeout 240s;
}
}
```

View File

@ -8,20 +8,51 @@ const ENV_PROD = 'production'
const ENV_DEV = 'development'
export default {
// 动态路由模式, 即无论是访问路径是什么, 永远只会调用 \apps\index\index()
dynamic: false,
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: {
// 常用正则
email: /^[\w\.\-]+@\w+([\.\-]\w+)*\.\w+$/,
uname: /^[A-Za-z\d_]{4,16}$/,
passwd: /^\S{6,20}$/,

144
index.js
View File

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

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

View File

@ -4,44 +4,34 @@
* @date 2020/09/18 15:16:29
*/
import { readonlyProp } from '../lib.js'
export function createRouter() {
return function (req, res, next) {
let debug = this.get('debug')
let dynamic = this.get('dynamic')
let name = dynamic ? 'index' : req.controller
let _module = this.$load(name)
let paths = req.path.concat()
export default function (req, res, next) {
var debug = this.get('debug')
var spa = this.get('spa')
// 1. 先判断控制器是否存在
if (!_module) {
return res.error(`Controller [${name}] not found`, 404)
if (!this.__MODULES__[spa ? 'index' : req.app]) {
return res.error(`Controller [${req.app}] not found`, 404)
}
// 2. 默认二级路由为index
if (paths.length < 1 && dynamic === false) {
paths.push('index')
if (req.path.length < 1 && spa === false) {
req.path.push('index')
}
// 3. 实例化控制器
_module
.then(async ModuleController => {
let ctrol, route, act
this.__MODULES__[spa ? 'index' : req.app]
.then(async ({ default: Mod }) => {
let app, route, act
let err = ''
if (ModuleController) {
ctrol = new ModuleController()
readonlyProp(ctrol, 'context', this)
readonlyProp(ctrol, 'request', req)
readonlyProp(ctrol, 'response', res)
readonlyProp(ctrol, 'name', req.controller)
if (Mod) {
app = new Mod()
app.__f_i_v_e__(this, req, res)
// 4. 优先执行__main__方法
if (ctrol.__main__) {
if (app.__main__) {
try {
let r = await ctrol.__main__()
let r = await app.__main__()
if (r === false) {
return
}
@ -50,29 +40,27 @@ export function createRouter() {
}
}
if (dynamic) {
return ctrol.indexAction.apply(ctrol, paths)
if (spa) {
return app.indexAction.apply(app, req.path)
} else {
route = paths.shift()
route = req.path.shift()
act = route + 'Action'
if (ctrol[act]) {
return ctrol[act].apply(ctrol, paths)
if (app[act]) {
return app[act].apply(app, req.path)
} else {
err = new Error(`Action [${route}] not found`)
err.status = 404
}
}
} else {
err = new Error(`Controller [${name}] load error`)
err = new Error(`Controller [${req.app}] 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,40 +1,31 @@
{
"name": "@gm5/core",
"version": "2.0.4",
"version": "1.1.5",
"type": "module",
"description": "Five.js, 一个轻量级的nodejs mvc框架 旨在简单易用, 5分钟即可上手",
"author": "yutent <yutent.io@gmail.com>",
"main": "index.js",
"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",
"es.shim": "^2.2.0",
"@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",
"iofs": "^1.5.3"
},
"devDependencies": {},
"repository": {
"type": "git",
"url": "https://git.wkit.fun/gm5/core.git"
"url": "https://github.com/bytedo/gmf.core.git"
},
"keywords": [
"five",
"fivejs",
"node-five",
"five.js",
"gm5",
"gmf",
"nodejs",
"mvc",
"koa",
"express"
"five, fivejs, node-five, five.js, nodejs, mvc, koa, express"
],
"engines": {
"node": ">=16.0.0"
"node": ">=10.0.0"
},
"license": "MIT"
}