Compare commits

..

No commits in common. "67a63bf67ee256dd5aa4a780d64b32b9475e2a19" and "04069523d352a7c05dec8ea4f701c2893b6e157b" have entirely different histories.

7 changed files with 253 additions and 224 deletions

View File

@ -22,11 +22,33 @@
* 为了方便下载安装及管理, 推荐使用 five-cli(这是一款专门为框架开发的脚本工具) 进行操作。 * 为了方便下载安装及管理, 推荐使用 five-cli(这是一款专门为框架开发的脚本工具) 进行操作。
```bash ```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)
``` ```
@ -36,26 +58,38 @@ npm create five
建立启动文件, 如 app.js 建立启动文件, 如 app.js
```javascript ```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.preload('./apps/') // [必须], 预加载应用目录
app.listen(3001) // 默认是3000 app.listen(3001) // 默认是3000
``` ```
其他的配置和功能, 请参考 [文档](/gm5/request/wiki)。 其他的配置和功能, 请参考 [文档](https://github.com/bytedo/gmf.core/wiki)。
3. 启动应用。在项目根目录打开终端, 输入以下命令 `npm create five`, 然后根据提示操作, 即可 3. 启动应用。在项目根目录打开终端, 输入以下命令 `five-cli start`, 然后根据提示操作, 即可
```bash ```bash
pm2 start app.dev.yaml # 初始化完成之后, 执行以下命令即可启动了,如果需要修改配置,可以先修改好再启动
# 正式环境执行 five-cli start
pm2 start app.yaml
不是使用five-cli创建的项目, 可使用node/pm2等启动项目
node app.js
# or
pm2 start app.js
``` ```
@ -89,7 +123,6 @@ server {
proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header Host $http_host; proxy_set_header Host $http_host;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_set_header X-NginX-Proxy true; proxy_set_header X-NginX-Proxy true;
proxy_set_header Upgrade $http_upgrade; proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade"; proxy_set_header Connection "upgrade";
@ -97,7 +130,7 @@ server {
proxy_max_temp_file_size 0; proxy_max_temp_file_size 0;
proxy_pass http://five_upstream; proxy_pass http://five_upstream;
proxy_redirect off; proxy_redirect off;
proxy_read_timeout 60s; proxy_read_timeout 240s;
} }
} }
``` ```

View File

@ -9,19 +9,50 @@ const ENV_DEV = 'development'
export default { export default {
db: {}, 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() spa: false, // 单路由模式, 即无论是访问路径是什么, 永远只会调用 \apps\index\index()
website: 'localhost',
domain: '', // cookie域, 默认等于website
port: 3000, port: 3000,
env: process.env.NODE_ENV === ENV_PROD ? ENV_PROD : ENV_DEV, env: process.env.NODE_ENV === ENV_PROD ? ENV_PROD : ENV_DEV,
debug: process.env.NODE_ENV === ENV_DEV, // debug模式 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: { cors: {
enabled: false, enabled: false,
credentials: false, credentials: false,
origin: [], // ['abc.com', 'a.foo.com'] origin: [], // ['abc.com', 'a.foo.com']
maxAge: 14400 maxAge: 14400
}, },
// 常用正则
regexp: { regexp: {
// 常用正则
email: /^[\w\.\-]+@\w+([\.\-]\w+)*\.\w+$/, email: /^[\w\.\-]+@\w+([\.\-]\w+)*\.\w+$/,
uname: /^[A-Za-z\d_]{4,16}$/, uname: /^[A-Za-z\d_]{4,16}$/,
passwd: /^\S{6,20}$/, passwd: /^\S{6,20}$/,

144
index.js
View File

@ -5,48 +5,64 @@
*/ */
import 'es.shim' // 加载拓展方法 import 'es.shim' // 加载拓展方法
import http from 'node:http' import http from 'http'
import { parse, join } from 'node:path' import path from 'path'
import fs from 'iofs' import fs from 'iofs'
import Request from '@gm5/request' import Request from '@gm5/request'
import Response from '@gm5/response' 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 config from './config/index.js'
import { createCors } from './middleware/cors.js' import Routers from './middleware/router.js'
import { createRouter } 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 => { process.on('uncaughtException', err => {
console.error('UncaughtException: ', err) console.error('UncaughtException: ', err)
}) })
class Five { export default class Five {
#config = config
#modules = {}
#middlewares = [createCors()]
#server = null
constructor() { constructor() {
readonlyProp(this, 'state', Object.create(null)) hideProperty(this, '__FIVE__', config)
hideProperty(this, '__MODULES__', {})
hideProperty(this, '__MIDDLEWARE__', [Cors])
} }
async #loop(req, res, idx = 0) { __main__() {
let fn = this.#middlewares[idx] var { domain, website, session, jwt } = this.__FIVE__
if (fn) {
await fn.call(this, req, res, _ => { domain = domain || website
idx++ session.domain = session.domain || domain
this.#loop(req, res, idx)
}) 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)
} }
/*------------------------------------------------------------------------*/ // 路由中间件要在最后
this.use(Routers)
get server() {
return this.#server
} }
/*------------------------------------------------------------------------*/ /*------------------------------------------------------------------------*/
@ -55,17 +71,17 @@ class Five {
set(obj) { set(obj) {
for (let i in obj) { for (let i in obj) {
if (typeof obj[i] === 'object' && !Array.isArray(obj[i])) { if (typeof obj[i] === 'object' && !Array.isArray(obj[i])) {
if (!this.#config[i]) { if (!this.__FIVE__[i]) {
this.#config[i] = obj[i] this.__FIVE__[i] = obj[i]
} else { } else {
try { try {
Object.assign(this.#config[i], obj[i]) Object.assign(this.__FIVE__[i], obj[i])
} catch (err) { } catch (err) {
console.error(err) console.error(err)
} }
} }
} else { } else {
this.#config[i] = obj[i] this.__FIVE__[i] = obj[i]
} }
} }
return this return this
@ -73,16 +89,16 @@ class Five {
// 获取全局配置 // 获取全局配置
get(key) { get(key) {
return this.#config[key] return this.__FIVE__[key]
} }
// 加载中间件 // 加载中间件
// 与别的中间件用法有些不一样, 回调的传入参数中的req和res, // 与别的中间件用法有些不一样, 回调的传入参数中的req和res,
// 并非原生的request对象和response对象, // 并非原生的request对象和response对象,
// 而是框架内部封装过的,可通过origin属性访问原生的对象 // 而是框架内部封装过的,可通过origin属性访问原生的对象
use(fn = noop) { use(fn) {
if (typeof fn === 'function') { if (typeof fn === 'function') {
this.#middlewares.push(fn) this.__MIDDLEWARE__.push(fn)
return this return this
} }
throw TypeError('argument must be a function') throw TypeError('argument must be a function')
@ -97,25 +113,23 @@ class Five {
// 预加载应用, 缓存以提高性能 // 预加载应用, 缓存以提高性能
preload(dir) { preload(dir) {
let list = fs.ls(dir) var list = fs.ls(dir)
if (list) { if (list) {
list.forEach(item => { list.forEach(item => {
let { name } = parse(item) var { name } = path.parse(item)
if (name.startsWith('.')) { if (name.startsWith('.')) {
return return
} }
// 如果是目录,则默认加载index.js, 其他文件不加载 // 如果是目录,则默认加载index.js, 其他文件不加载
// 交由index.js自行处理, 用于复杂的应用 // 交由index.js自行处理, 用于复杂的应用
if (fs.isdir(item)) { if (fs.isdir(item)) {
item = join(item, './index.js') item = path.join(item, './index.js')
} }
this.#modules[name] = import(item) this.__MODULES__[name] = import(item).catch(err => {
.then(r => r.default)
.catch(err => {
console.error(err) console.error(err)
return null return { default: null }
}) })
}) })
} }
@ -123,52 +137,40 @@ class Five {
return this return this
} }
$load(name) {
return this.#modules[name]
}
// 启动http服务 // 启动http服务
listen(port) { listen(port) {
this.set({ port }) var _this = this
return this var server
}
run() { this.__main__()
this.#server = http.createServer()
// 路由中间件要在最后 server = http.createServer(function (req, res) {
this.use(createRouter()) var request = new Request(req, res)
var response = new Response(req, res)
this.#server var middleware = _this.__MIDDLEWARE__.concat()
.on('request', (req, res) => { var fn = middleware.shift()
let request = new Request(req, res)
let response = new Response(req, res)
if (response.ended) { if (response.rendered) {
return 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) if (fn) {
}) ;(async function next() {
.on('listening', _ => { await fn.call(_this, request, response, function () {
if (this.get('debug')) { fn = middleware.shift()
console.log('Server successfully started ...') if (fn) {
console.log('%s://%s:%d\n', 'http', '127.0.0.1', this.get('port')) 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,20 +4,19 @@
* @date 2020/09/18 14:55:49 * @date 2020/09/18 14:55:49
*/ */
import { parse } from 'node:url' import url from 'url'
export function createCors() { export default function (req, res, next) {
return function (req, res, next) { var CORS = this.get('cors')
let opts = this.get('cors')
if (opts.enabled) { if (CORS.enabled) {
let origin = req.header('origin') || req.header('referer') || '' var origin = req.header('origin') || req.header('referer') || ''
let headers = req.header('access-control-request-headers') var headers = req.header('access-control-request-headers')
let { hostname, host, protocol } = parse(origin) var { hostname, host, protocol } = url.parse(origin)
if (opts.origin.length && hostname) { if (CORS.origin.length && hostname) {
let pass = false var pass = false
for (let it of opts.origin) { for (let it of CORS.origin) {
if (hostname.endsWith(it)) { if (hostname.endsWith(it)) {
pass = true pass = true
break break
@ -27,19 +26,19 @@ export function createCors() {
return res.end('') return res.end('')
} }
} }
if (opts.credentials) { if (CORS.credentials) {
res.set('Access-Control-Allow-Credentials', 'true') res.set('Access-Control-Allow-Credentials', 'true')
} }
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', 'GET,HEAD,POST,PUT,DELETE,PATCH')
if (headers) { if (headers) {
res.set('Access-Control-Allow-Headers', headers) res.set('Access-Control-Allow-Headers', headers)
} }
if (opts.maxAge) { if (CORS.maxAge) {
res.set('Access-Control-Max-Age', opts.maxAge) res.set('Access-Control-Max-Age', CORS.maxAge)
} }
if (req.method === 'OPTIONS') { if (req.method === 'OPTIONS') {
@ -47,5 +46,4 @@ export function createCors() {
} }
} }
next() next()
}
} }

View File

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

View File

@ -1,40 +1,31 @@
{ {
"name": "@gm5/core", "name": "@gm5/core",
"version": "2.0.0", "version": "1.1.5",
"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",
"dependencies": { "dependencies": {
"@gm5/session": "^2.0.0", "@gm5/session": "^1.1.1",
"@gm5/request": "^2.0.3", "@gm5/request": "^1.2.3",
"@gm5/response": "^2.0.1", "@gm5/response": "^1.3.1",
"@gm5/controller": "^2.0.2", "@gm5/controller": "^1.0.0",
"@gm5/jwt": "^2.0.2", "@gm5/jwt": "^1.1.0",
"@gm5/views": "^2.0.0", "@gm5/views": "^1.0.0",
"crypto.js": "^3.1.2", "crypto.js": "^3.1.0",
"es.shim": "^2.2.0", "es.shim": "^2.0.1",
"iofs": "^1.5.3" "iofs": "^1.5.3"
}, },
"devDependencies": {}, "devDependencies": {},
"repository": { "repository": {
"type": "git", "type": "git",
"url": "https://git.wkit.fun/gm5/core.git" "url": "https://github.com/bytedo/gmf.core.git"
}, },
"keywords": [ "keywords": [
"five", "five, fivejs, node-five, five.js, nodejs, mvc, koa, express"
"fivejs",
"node-five",
"five.js",
"gm5",
"gmf",
"nodejs",
"mvc",
"koa",
"express"
], ],
"engines": { "engines": {
"node": ">=16.0.0" "node": ">=10.0.0"
}, },
"license": "MIT" "license": "MIT"
} }