commit
82191217de
@ -0,0 +1,65 @@ |
||||
module.exports = { |
||||
"env": { |
||||
"browser": true, |
||||
"es2021": true, |
||||
"es2022": true, |
||||
"es2023": true, |
||||
}, |
||||
"extends": ["eslint:recommended"], |
||||
"overrides": [ |
||||
{ |
||||
"env": { |
||||
"node": true |
||||
}, |
||||
"files": [ |
||||
".eslintrc.{js,cjs}" |
||||
], |
||||
"parserOptions": { |
||||
"sourceType": "script" |
||||
} |
||||
} |
||||
], |
||||
"parserOptions": { |
||||
"ecmaVersion": "latest", |
||||
"sourceType": "module" |
||||
}, |
||||
"rules": { |
||||
indent: ['error', 4, { "SwitchCase": 1 }], // 用于指定代码缩进的方式,这里配置为使用四个空格进行缩进。 |
||||
// 'linebreak-style': [0, 'error', 'windows'], // 用于指定换行符的风格,这里配置为使用 Windows 风格的换行符(\r\n)。 |
||||
quotes: ['error', 'single'], // 用于指定字符串的引号风格,这里配置为使用单引号作为字符串的引号。 |
||||
semi: ['error', 'always'], //用于指定是否需要在语句末尾添加分号,这里配置为必须始终添加分号。 |
||||
"no-console": 2,//禁止使用console |
||||
"no-const-assign": 2,//禁止修改const声明的变量 |
||||
"no-empty": 2,//块语句中的内容不能为空 |
||||
"no-extra-parens": 2,//禁止非必要的括号 |
||||
"no-extra-semi": 2,//禁止多余的冒号 |
||||
"no-fallthrough": 1,//禁止switch穿透 |
||||
"no-func-assign": 2,//禁止重复的函数声明 |
||||
"no-inline-comments": 2,//禁止行内备注 |
||||
"no-irregular-whitespace": 2,//不能有不规则的空格 |
||||
"no-mixed-spaces-and-tabs": [2, false],//禁止混用tab和空格 |
||||
"no-multi-spaces": 1,//不能用多余的空格 |
||||
"no-multiple-empty-lines": [1, {"max": 2}],//空行最多不能超过2行 |
||||
"no-nested-ternary": 0,//禁止使用嵌套的三目运算 |
||||
"no-redeclare": 2,//禁止重复声明变量 |
||||
"no-shadow": 2,//外部作用域中的变量不能与它所包含的作用域中的变量或参数同名 |
||||
"no-trailing-spaces": 2,//一行结束后面不要有空格 |
||||
"no-unexpected-multiline": 2,//避免多行表达式 |
||||
"no-unused-vars": [2, {"vars": "all", "args": "after-used"}],//不能有声明后未被使用的变量或参数 |
||||
"no-use-before-define": 2,//未定义前不能使用 |
||||
"no-var": 2,//禁用var,用let和const代替 |
||||
"arrow-parens": 0,//箭头函数用小括号括起来 |
||||
"array-bracket-spacing": [2, "never"],//是否允许非空数组里面有多余的空格 |
||||
"camelcase": 2,//强制驼峰法命名 |
||||
"comma-style": [2, "last"],//逗号风格,换行时在行首还是行尾 |
||||
"comma-spacing": ["error", {"before": false, "after": true}],//对象字面量中冒号的前后空格 |
||||
"key-spacing": ["error", { "beforeColon": false, "afterColon": true }],// 冒号后面有空格 |
||||
"lines-around-comment": 0,//行前/行后备注 |
||||
"array-bracket-spacing": ["error", "always"],// 检查数组字面量中的元素之间的空格。 |
||||
}, |
||||
"globals": { |
||||
global: true, |
||||
Buffer: true, |
||||
process: true |
||||
} |
||||
} |
@ -0,0 +1,135 @@ |
||||
# ---> Node |
||||
# Logs |
||||
logs |
||||
*.log |
||||
npm-debug.log* |
||||
yarn-debug.log* |
||||
yarn-error.log* |
||||
lerna-debug.log* |
||||
pnpm-debug.log* |
||||
.pnpm-debug.log* |
||||
# log |
||||
winston-logs/* |
||||
|
||||
# Diagnostic reports (https://nodejs.org/api/report.html) |
||||
report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json |
||||
|
||||
# Runtime data |
||||
pids |
||||
*.pid |
||||
*.seed |
||||
*.pid.lock |
||||
|
||||
# Directory for instrumented libs generated by jscoverage/JSCover |
||||
lib-cov |
||||
|
||||
# Coverage directory used by tools like istanbul |
||||
coverage |
||||
*.lcov |
||||
|
||||
# nyc test coverage |
||||
.nyc_output |
||||
|
||||
# Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files) |
||||
.grunt |
||||
|
||||
# Bower dependency directory (https://bower.io/) |
||||
bower_components |
||||
|
||||
# node-waf configuration |
||||
.lock-wscript |
||||
|
||||
# Compiled binary addons (https://nodejs.org/api/addons.html) |
||||
build/Release |
||||
|
||||
# Dependency directories |
||||
node_modules/ |
||||
jspm_packages/ |
||||
|
||||
# Snowpack dependency directory (https://snowpack.dev/) |
||||
web_modules/ |
||||
|
||||
# TypeScript cache |
||||
*.tsbuildinfo |
||||
|
||||
# Optional npm cache directory |
||||
.npm |
||||
|
||||
# Optional eslint cache |
||||
.eslintcache |
||||
|
||||
# Optional stylelint cache |
||||
.stylelintcache |
||||
|
||||
# Microbundle cache |
||||
.rpt2_cache/ |
||||
.rts2_cache_cjs/ |
||||
.rts2_cache_es/ |
||||
.rts2_cache_umd/ |
||||
|
||||
# Optional REPL history |
||||
.node_repl_history |
||||
|
||||
# Output of 'npm pack' |
||||
*.tgz |
||||
|
||||
# Yarn Integrity file |
||||
.yarn-integrity |
||||
|
||||
# dotenv environment variable files |
||||
.env |
||||
.env.development.local |
||||
.env.test.local |
||||
.env.production.local |
||||
.env.local |
||||
|
||||
# parcel-bundler cache (https://parceljs.org/) |
||||
.cache |
||||
.parcel-cache |
||||
|
||||
# Next.js build output |
||||
.next |
||||
out |
||||
|
||||
# Nuxt.js build / generate output |
||||
.nuxt |
||||
dist |
||||
|
||||
# Gatsby files |
||||
.cache/ |
||||
# Comment in the public line in if your project uses Gatsby and not Next.js |
||||
# https://nextjs.org/blog/next-9-1#public-directory-support |
||||
# public |
||||
|
||||
# vuepress build output |
||||
.vuepress/dist |
||||
|
||||
# vuepress v2.x temp and cache directory |
||||
.temp |
||||
.cache |
||||
|
||||
# Docusaurus cache and generated files |
||||
.docusaurus |
||||
|
||||
# Serverless directories |
||||
.serverless/ |
||||
|
||||
# FuseBox cache |
||||
.fusebox/ |
||||
|
||||
# DynamoDB Local files |
||||
.dynamodb/ |
||||
|
||||
# TernJS port file |
||||
.tern-port |
||||
|
||||
# Stores VSCode versions used for testing VSCode extensions |
||||
.vscode-test |
||||
|
||||
# yarn v2 |
||||
.yarn/cache |
||||
.yarn/unplugged |
||||
.yarn/build-state.yml |
||||
.yarn/install-state.gz |
||||
.pnp.* |
||||
|
@ -0,0 +1,5 @@ |
||||
# 默认忽略的文件 |
||||
/shelf/ |
||||
/workspace.xml |
||||
# 基于编辑器的 HTTP 客户端请求 |
||||
/httpRequests/ |
@ -0,0 +1,12 @@ |
||||
<?xml version="1.0" encoding="UTF-8"?> |
||||
<module type="WEB_MODULE" version="4"> |
||||
<component name="NewModuleRootManager"> |
||||
<content url="file://$MODULE_DIR$"> |
||||
<excludeFolder url="file://$MODULE_DIR$/.tmp" /> |
||||
<excludeFolder url="file://$MODULE_DIR$/temp" /> |
||||
<excludeFolder url="file://$MODULE_DIR$/tmp" /> |
||||
</content> |
||||
<orderEntry type="inheritedJdk" /> |
||||
<orderEntry type="sourceFolder" forTests="false" /> |
||||
</component> |
||||
</module> |
@ -0,0 +1,8 @@ |
||||
<?xml version="1.0" encoding="UTF-8"?> |
||||
<project version="4"> |
||||
<component name="ProjectModuleManager"> |
||||
<modules> |
||||
<module fileurl="file://$PROJECT_DIR$/.idea/graphResource2.iml" filepath="$PROJECT_DIR$/.idea/graphResource2.iml" /> |
||||
</modules> |
||||
</component> |
||||
</project> |
@ -0,0 +1,6 @@ |
||||
<?xml version="1.0" encoding="UTF-8"?> |
||||
<project version="4"> |
||||
<component name="PrettierConfiguration"> |
||||
<option name="myConfigurationMode" value="AUTOMATIC" /> |
||||
</component> |
||||
</project> |
@ -0,0 +1,5 @@ |
||||
{ |
||||
"singleQuote": true, |
||||
"trailingComma": "all", |
||||
"tabWidth": 4 |
||||
} |
Binary file not shown.
@ -0,0 +1,106 @@ |
||||
// | ------------------------------------------------------------
|
||||
// | @版本: version 0.1
|
||||
// | @创建人: 【Nie-x7129】
|
||||
// | @E-mail: x71291@outlook.com
|
||||
// | @所在项目: initkoa
|
||||
// | @文件描述: bootstrap.js - Koa项目启动文件
|
||||
// | @创建时间: 2023-11-25 21:17
|
||||
// | @更新时间: 2023-11-25 21:17
|
||||
// | @修改记录:
|
||||
// | -*-*-*- (时间--修改人--修改说明) -*-*-*-
|
||||
// | =
|
||||
// | ------------------------------------------------------------
|
||||
|
||||
|
||||
import devConfig from '#root/development.env.js'; |
||||
import prodConfig from '#root/production.env.js'; |
||||
import startApp from '#home/app.js'; |
||||
import winston from "winston"; |
||||
import {logger, colorizer} from "#common/logger/index.js"; |
||||
import createDatabase from "#common/database/index.js"; |
||||
import {createCatch} from "#cache/index.js"; |
||||
// | 获取ENV
|
||||
const ENV = process.env.NODE_ENV && process.env.NODE_ENV.toLowerCase().trim(); |
||||
|
||||
if (ENV === 'development' || ENV === undefined) { |
||||
global.config = devConfig; |
||||
logger.add(new winston.transports.Console({ |
||||
format:winston.format.combine( |
||||
winston.format.printf( |
||||
(i) => { |
||||
return colorizer.colorize( |
||||
i.level, |
||||
i.message |
||||
); |
||||
}, |
||||
), |
||||
) |
||||
})) |
||||
} else if (ENV === 'production') { |
||||
global.config = prodConfig; |
||||
logger.exceptions.handle(new winston.transports.File({ filename: 'winston-logs/winston-exceptions.log' })); |
||||
logger.rejections.handle(new winston.transports.File({ filename: 'winston-logs/winston-rejections.log' })) |
||||
} else { |
||||
throw new Error(`未识别的环境变量${ENV}`); |
||||
} |
||||
global.logger = logger |
||||
global.ENV = ENV; |
||||
|
||||
// = 函数名: checkPort
|
||||
// = 描述: 检测服务端口是否正常
|
||||
// = 参数: None
|
||||
// = 返回值: undefined
|
||||
// = 创建人: nie
|
||||
// = 创建时间: 2023-11-25 21:49:22 -
|
||||
function checkPort() { |
||||
if ( |
||||
typeof global.config.port !== 'number' || |
||||
global.config.port > 65536 || |
||||
global.config.port < 3000 |
||||
) { |
||||
throw new Error(`服务监听端口不合法:${global.config.port}`); |
||||
} |
||||
} |
||||
checkPort(); |
||||
|
||||
// = 函数名: checkAppName
|
||||
// = 描述: 检测服务名是否正常
|
||||
// = 参数: None
|
||||
// = 返回值: undefined
|
||||
// = 创建人: nie
|
||||
// = 创建时间: 2023-11-25 21:51:03 -
|
||||
function checkAppName() { |
||||
if (!global.config.appName) { |
||||
throw new Error(`服务名不存在:${global.config.appName}`); |
||||
} |
||||
} |
||||
checkAppName() |
||||
// process.stdout.write('\u001b[2J\u001b[0;0H');
|
||||
async function createApp(){ |
||||
const sequelize = createDatabase(logger); |
||||
|
||||
await sequelize.sync({alter: true}) |
||||
await sequelize.authenticate().catch(e => { |
||||
console.error(`数据库连接失败, ${e}`); |
||||
throw new Error(e) |
||||
}); |
||||
logger.info(`== 已成功与数据库建立连接。 ==`); |
||||
|
||||
createCatch(sequelize) |
||||
|
||||
|
||||
|
||||
const app = startApp(); |
||||
|
||||
sequelize.getQueryInterface().showAllTables().then(data => { |
||||
// console.log(data)
|
||||
}).catch(e => { |
||||
console.error(e) |
||||
}) |
||||
|
||||
app.context.sequelize = sequelize |
||||
app.listen(config.port); |
||||
logger.info( `Web服务 ${global.config.appName} 启动成功,访问: http://127.0.0.1:${global.config.port}`) |
||||
} |
||||
createApp() |
||||
|
@ -0,0 +1,22 @@ |
||||
// | ------------------------------------------------------------
|
||||
// | @版本: version 0.1
|
||||
// | @创建人: 【Nie-x7129】
|
||||
// | @E-mail: x71291@outlook.com
|
||||
// | @所在项目: initkoa
|
||||
// | @文件描述: development.env.js -
|
||||
// | @创建时间: 2023-11-25 21:36
|
||||
// | @更新时间: 2023-11-25 21:36
|
||||
// | @修改记录:
|
||||
// | -*-*-*- (时间--修改人--修改说明) -*-*-*-
|
||||
// | =
|
||||
// | ------------------------------------------------------------
|
||||
|
||||
import prodConfig from "#root/production.env.js"; |
||||
|
||||
const config = { |
||||
port: 3000, |
||||
} |
||||
|
||||
const devConfig = {...prodConfig, ...config} |
||||
|
||||
export default devConfig |
@ -0,0 +1,38 @@ |
||||
var DataTypes = require("sequelize").DataTypes; |
||||
var _lauchuser = require("./lauchuser"); |
||||
var _lauchuserexpandfield = require("./lauchuserexpandfield"); |
||||
var _lauchuserexpandrecord = require("./lauchuserexpandrecord"); |
||||
var _lauchuserloginrecord = require("./lauchuserloginrecord"); |
||||
var _lauchuserpasswd = require("./lauchuserpasswd"); |
||||
var _lauchuserstructauthority = require("./lauchuserstructauthority"); |
||||
var _lauchuserstructorganization = require("./lauchuserstructorganization"); |
||||
var _lauchuserstructrelationorganizationaccent = require("./lauchuserstructrelationorganizationaccent"); |
||||
var _lauchuserstructrelationorganizationauthority = require("./lauchuserstructrelationorganizationauthority"); |
||||
|
||||
function initModels(sequelize) { |
||||
var lauchuser = _lauchuser(sequelize, DataTypes); |
||||
var lauchuserexpandfield = _lauchuserexpandfield(sequelize, DataTypes); |
||||
var lauchuserexpandrecord = _lauchuserexpandrecord(sequelize, DataTypes); |
||||
var lauchuserloginrecord = _lauchuserloginrecord(sequelize, DataTypes); |
||||
var lauchuserpasswd = _lauchuserpasswd(sequelize, DataTypes); |
||||
var lauchuserstructauthority = _lauchuserstructauthority(sequelize, DataTypes); |
||||
var lauchuserstructorganization = _lauchuserstructorganization(sequelize, DataTypes); |
||||
var lauchuserstructrelationorganizationaccent = _lauchuserstructrelationorganizationaccent(sequelize, DataTypes); |
||||
var lauchuserstructrelationorganizationauthority = _lauchuserstructrelationorganizationauthority(sequelize, DataTypes); |
||||
|
||||
|
||||
return { |
||||
lauchuser, |
||||
lauchuserexpandfield, |
||||
lauchuserexpandrecord, |
||||
lauchuserloginrecord, |
||||
lauchuserpasswd, |
||||
lauchuserstructauthority, |
||||
lauchuserstructorganization, |
||||
lauchuserstructrelationorganizationaccent, |
||||
lauchuserstructrelationorganizationauthority, |
||||
}; |
||||
} |
||||
module.exports = initModels; |
||||
module.exports.initModels = initModels; |
||||
module.exports.default = initModels; |
@ -0,0 +1,58 @@ |
||||
const Sequelize = require('sequelize'); |
||||
module.exports = function (sequelize, DataTypes) { |
||||
return sequelize.define('lauchuser', { |
||||
uuid: { |
||||
type: DataTypes.UUID, |
||||
allowNull: false, |
||||
primaryKey: true, |
||||
comment: "用户唯一ID" |
||||
}, |
||||
username: { |
||||
type: DataTypes.STRING(255), |
||||
allowNull: false, |
||||
comment: "用户名" |
||||
}, |
||||
email: { |
||||
type: DataTypes.STRING(255), |
||||
allowNull: false |
||||
}, |
||||
createTime: { |
||||
type: DataTypes.DATE, |
||||
allowNull: false, |
||||
comment: "创建时间" |
||||
}, |
||||
status: { |
||||
type: DataTypes.INTEGER.UNSIGNED.ZEROFILL, |
||||
allowNull: false, |
||||
defaultValue: 0000000000, |
||||
comment: "0正常1注销2停用" |
||||
}, |
||||
selfSequence: { |
||||
type: DataTypes.INTEGER, |
||||
allowNull: false, |
||||
autoIncrement: true, |
||||
comment: "自增序列" |
||||
} |
||||
}, { |
||||
sequelize, |
||||
tableName: 'lauchuser', |
||||
timestamps: false, |
||||
indexes: [ |
||||
{ |
||||
name: "PRIMARY", |
||||
unique: true, |
||||
using: "BTREE", |
||||
fields: [ |
||||
{name: "uuid"}, |
||||
] |
||||
}, |
||||
{ |
||||
name: "selfSequence", |
||||
using: "BTREE", |
||||
fields: [ |
||||
{name: "selfSequence"}, |
||||
] |
||||
}, |
||||
] |
||||
}); |
||||
}; |
@ -0,0 +1,82 @@ |
||||
const Sequelize = require('sequelize'); |
||||
module.exports = function(sequelize, DataTypes) { |
||||
return sequelize.define('lauchuserexpandfield', { |
||||
expandFieldId: { |
||||
autoIncrement: true, |
||||
type: DataTypes.INTEGER, |
||||
allowNull: false, |
||||
primaryKey: true, |
||||
comment: "拓展字段ID" |
||||
}, |
||||
fieldIdentify: { |
||||
type: DataTypes.STRING(255), |
||||
allowNull: false, |
||||
comment: "字段标识" |
||||
}, |
||||
displayName: { |
||||
type: DataTypes.STRING(255), |
||||
allowNull: false, |
||||
comment: "字段名" |
||||
}, |
||||
fieldDescribe: { |
||||
type: DataTypes.STRING(255), |
||||
allowNull: false, |
||||
comment: "字段描述" |
||||
}, |
||||
defaultValue: { |
||||
type: DataTypes.STRING(255), |
||||
allowNull: true, |
||||
comment: "默认值" |
||||
}, |
||||
storageType: { |
||||
type: DataTypes.STRING(255), |
||||
allowNull: false, |
||||
comment: "存储类型" |
||||
}, |
||||
storageLength: { |
||||
type: DataTypes.INTEGER, |
||||
allowNull: false, |
||||
comment: "存储长度" |
||||
}, |
||||
isRequired: { |
||||
type: DataTypes.BOOLEAN, |
||||
allowNull: true, |
||||
comment: "是否必填" |
||||
}, |
||||
isRepeat: { |
||||
type: DataTypes.BOOLEAN, |
||||
allowNull: true, |
||||
comment: "是否可以重复" |
||||
}, |
||||
isEnable: { |
||||
type: DataTypes.BOOLEAN, |
||||
allowNull: true, |
||||
comment: "是否启用" |
||||
}, |
||||
createTime: { |
||||
type: DataTypes.DATE, |
||||
allowNull: false, |
||||
comment: "创建时间" |
||||
}, |
||||
isDelete: { |
||||
type: DataTypes.STRING(64), |
||||
allowNull: false, |
||||
defaultValue: "", |
||||
comment: "删除时间" |
||||
} |
||||
}, { |
||||
sequelize, |
||||
tableName: 'lauchuserexpandfield', |
||||
timestamps: false, |
||||
indexes: [ |
||||
{ |
||||
name: "PRIMARY", |
||||
unique: true, |
||||
using: "BTREE", |
||||
fields: [ |
||||
{ name: "expandFieldId" }, |
||||
] |
||||
}, |
||||
] |
||||
}); |
||||
}; |
@ -0,0 +1,52 @@ |
||||
const Sequelize = require('sequelize'); |
||||
module.exports = function(sequelize, DataTypes) { |
||||
return sequelize.define('lauchuserexpandrecord', { |
||||
expandRecordId: { |
||||
autoIncrement: true, |
||||
type: DataTypes.INTEGER, |
||||
allowNull: false, |
||||
primaryKey: true, |
||||
comment: "记录ID" |
||||
}, |
||||
uuid: { |
||||
type: DataTypes.INTEGER, |
||||
allowNull: false, |
||||
comment: "用户ID" |
||||
}, |
||||
expandField: { |
||||
type: DataTypes.STRING(255), |
||||
allowNull: false, |
||||
comment: "多占字段ID" |
||||
}, |
||||
expandFieldValue: { |
||||
type: DataTypes.STRING(255), |
||||
allowNull: false, |
||||
comment: "拓展字段值" |
||||
}, |
||||
createTime: { |
||||
type: DataTypes.DATE, |
||||
allowNull: false, |
||||
comment: "创建时间" |
||||
}, |
||||
isDelete: { |
||||
type: DataTypes.STRING(64), |
||||
allowNull: false, |
||||
defaultValue: "", |
||||
comment: "删除时间" |
||||
} |
||||
}, { |
||||
sequelize, |
||||
tableName: 'lauchuserexpandrecord', |
||||
timestamps: false, |
||||
indexes: [ |
||||
{ |
||||
name: "PRIMARY", |
||||
unique: true, |
||||
using: "BTREE", |
||||
fields: [ |
||||
{ name: "expandRecordId" }, |
||||
] |
||||
}, |
||||
] |
||||
}); |
||||
}; |
@ -0,0 +1,37 @@ |
||||
const Sequelize = require('sequelize'); |
||||
module.exports = function(sequelize, DataTypes) { |
||||
return sequelize.define('lauchuserloginrecord', { |
||||
loginRecordId: { |
||||
autoIncrement: true, |
||||
type: DataTypes.INTEGER, |
||||
allowNull: false, |
||||
primaryKey: true |
||||
}, |
||||
uuid: { |
||||
type: DataTypes.UUID, |
||||
allowNull: false |
||||
}, |
||||
recoredJson: { |
||||
type: DataTypes.TEXT, |
||||
allowNull: false |
||||
}, |
||||
createTime: { |
||||
type: DataTypes.DATE, |
||||
allowNull: false |
||||
} |
||||
}, { |
||||
sequelize, |
||||
tableName: 'lauchuserloginrecord', |
||||
timestamps: false, |
||||
indexes: [ |
||||
{ |
||||
name: "PRIMARY", |
||||
unique: true, |
||||
using: "BTREE", |
||||
fields: [ |
||||
{ name: "loginRecordId" }, |
||||
] |
||||
}, |
||||
] |
||||
}); |
||||
}; |
@ -0,0 +1,41 @@ |
||||
const Sequelize = require('sequelize'); |
||||
module.exports = function(sequelize, DataTypes) { |
||||
return sequelize.define('lauchuserpasswd', { |
||||
passwdId: { |
||||
autoIncrement: true, |
||||
type: DataTypes.INTEGER, |
||||
allowNull: false, |
||||
primaryKey: true, |
||||
comment: "密码记录ID" |
||||
}, |
||||
uuid: { |
||||
type: DataTypes.UUID, |
||||
allowNull: false, |
||||
comment: "用户ID" |
||||
}, |
||||
passwd: { |
||||
type: DataTypes.STRING(255), |
||||
allowNull: false, |
||||
comment: "用户密码" |
||||
}, |
||||
createTime: { |
||||
type: DataTypes.DATE, |
||||
allowNull: false, |
||||
comment: "创建时间" |
||||
} |
||||
}, { |
||||
sequelize, |
||||
tableName: 'lauchuserpasswd', |
||||
timestamps: false, |
||||
indexes: [ |
||||
{ |
||||
name: "PRIMARY", |
||||
unique: true, |
||||
using: "BTREE", |
||||
fields: [ |
||||
{ name: "passwdId" }, |
||||
] |
||||
}, |
||||
] |
||||
}); |
||||
}; |
@ -0,0 +1,64 @@ |
||||
const Sequelize = require('sequelize'); |
||||
module.exports = function(sequelize, DataTypes) { |
||||
return sequelize.define('lauchuserstructauthority', { |
||||
authorityStructId: { |
||||
autoIncrement: true, |
||||
type: DataTypes.INTEGER, |
||||
allowNull: false, |
||||
primaryKey: true |
||||
}, |
||||
authorityType: { |
||||
type: DataTypes.STRING(255), |
||||
allowNull: false, |
||||
comment: "按钮、页面、接口" |
||||
}, |
||||
authorityName: { |
||||
type: DataTypes.STRING(255), |
||||
allowNull: false |
||||
}, |
||||
authorityIdentify: { |
||||
type: DataTypes.STRING(255), |
||||
allowNull: false |
||||
}, |
||||
authorityDescribe: { |
||||
type: DataTypes.STRING(255), |
||||
allowNull: false |
||||
}, |
||||
father: { |
||||
type: DataTypes.INTEGER, |
||||
allowNull: false |
||||
}, |
||||
avatar: { |
||||
type: DataTypes.STRING(255), |
||||
allowNull: false |
||||
}, |
||||
status: { |
||||
type: DataTypes.STRING(255), |
||||
allowNull: false, |
||||
comment: "禁用启用" |
||||
}, |
||||
createTime: { |
||||
type: DataTypes.DATE, |
||||
allowNull: false |
||||
}, |
||||
isDelete: { |
||||
type: DataTypes.STRING(64), |
||||
allowNull: false, |
||||
defaultValue: "" |
||||
} |
||||
}, { |
||||
sequelize, |
||||
tableName: 'lauchuserstructauthority', |
||||
timestamps: false, |
||||
indexes: [ |
||||
{ |
||||
name: "PRIMARY", |
||||
unique: true, |
||||
using: "BTREE", |
||||
fields: [ |
||||
{ name: "authorityStructId" }, |
||||
] |
||||
}, |
||||
] |
||||
}); |
||||
}; |
@ -0,0 +1,54 @@ |
||||
const Sequelize = require('sequelize'); |
||||
module.exports = function(sequelize, DataTypes) { |
||||
return sequelize.define('lauchuserstructorganization', { |
||||
organizationStructId: { |
||||
autoIncrement: true, |
||||
type: DataTypes.INTEGER, |
||||
allowNull: false, |
||||
primaryKey: true |
||||
}, |
||||
organizationType: { |
||||
type: DataTypes.STRING(255), |
||||
allowNull: false |
||||
}, |
||||
organizationName: { |
||||
type: DataTypes.STRING(255), |
||||
allowNull: false |
||||
}, |
||||
organizationDescribe: { |
||||
type: DataTypes.STRING(255), |
||||
allowNull: false |
||||
}, |
||||
father: { |
||||
type: DataTypes.INTEGER.UNSIGNED.ZEROFILL, |
||||
allowNull: false |
||||
}, |
||||
isDefault: { |
||||
type: DataTypes.STRING(255), |
||||
allowNull: false |
||||
}, |
||||
createTime: { |
||||
type: DataTypes.DATE, |
||||
allowNull: false |
||||
}, |
||||
isDelete: { |
||||
type: DataTypes.STRING(64), |
||||
allowNull: false, |
||||
defaultValue: "" |
||||
} |
||||
}, { |
||||
sequelize, |
||||
tableName: 'lauchuserstructorganization', |
||||
timestamps: false, |
||||
indexes: [ |
||||
{ |
||||
name: "PRIMARY", |
||||
unique: true, |
||||
using: "BTREE", |
||||
fields: [ |
||||
{ name: "organizationStructId" }, |
||||
] |
||||
}, |
||||
] |
||||
}); |
||||
}; |
@ -0,0 +1,42 @@ |
||||
const Sequelize = require('sequelize'); |
||||
module.exports = function(sequelize, DataTypes) { |
||||
return sequelize.define('lauchuserstructrelationorganizationaccent', { |
||||
organizationRelationAccentId: { |
||||
autoIncrement: true, |
||||
type: DataTypes.INTEGER, |
||||
allowNull: false, |
||||
primaryKey: true |
||||
}, |
||||
uuid: { |
||||
type: DataTypes.UUID, |
||||
allowNull: false |
||||
}, |
||||
organizationStruct: { |
||||
type: DataTypes.INTEGER, |
||||
allowNull: false |
||||
}, |
||||
createTime: { |
||||
type: DataTypes.DATE, |
||||
allowNull: false |
||||
}, |
||||
isDelete: { |
||||
type: DataTypes.STRING(64), |
||||
allowNull: false, |
||||
defaultValue: "" |
||||
} |
||||
}, { |
||||
sequelize, |
||||
tableName: 'lauchuserstructrelationorganizationaccent', |
||||
timestamps: false, |
||||
indexes: [ |
||||
{ |
||||
name: "PRIMARY", |
||||
unique: true, |
||||
using: "BTREE", |
||||
fields: [ |
||||
{ name: "organizationRelationAccentId" }, |
||||
] |
||||
}, |
||||
] |
||||
}); |
||||
}; |
@ -0,0 +1,42 @@ |
||||
const Sequelize = require('sequelize'); |
||||
module.exports = function(sequelize, DataTypes) { |
||||
return sequelize.define('lauchuserstructrelationorganizationauthority', { |
||||
organizationRelationAuthorityId: { |
||||
autoIncrement: true, |
||||
type: DataTypes.INTEGER, |
||||
allowNull: false, |
||||
primaryKey: true |
||||
}, |
||||
organizationStruct: { |
||||
type: DataTypes.INTEGER, |
||||
allowNull: false |
||||
}, |
||||
authorityStruct: { |
||||
type: DataTypes.INTEGER, |
||||
allowNull: false |
||||
}, |
||||
createTime: { |
||||
type: DataTypes.DATE, |
||||
allowNull: false |
||||
}, |
||||
isDelete: { |
||||
type: DataTypes.STRING(64), |
||||
allowNull: false, |
||||
defaultValue: "" |
||||
} |
||||
}, { |
||||
sequelize, |
||||
tableName: 'lauchuserstructrelationorganizationauthority', |
||||
timestamps: false, |
||||
indexes: [ |
||||
{ |
||||
name: "PRIMARY", |
||||
unique: true, |
||||
using: "BTREE", |
||||
fields: [ |
||||
{ name: "organizationRelationAuthorityId" }, |
||||
] |
||||
}, |
||||
] |
||||
}); |
||||
}; |
@ -0,0 +1 @@ |
||||
sequelize-auto -h 数据库的IP地址 -d 数据库名 -u 用户名 -x 密码 -p 端口 -t 表名 |
Binary file not shown.
@ -0,0 +1,56 @@ |
||||
{ |
||||
"name": "initkoa", |
||||
"version": "1.0.0", |
||||
"description": "", |
||||
"type": "module", |
||||
"main": "app.js", |
||||
"imports": { |
||||
"#root/*": "./*", |
||||
"#home/*": "./src/*", |
||||
"#routes/*": "./src/routes/*", |
||||
"#common/*": "./src/common/*", |
||||
"#dataModels/*": "./src/common/database/dataModels/*", |
||||
"#cache/*": "./src/cache/*", |
||||
"#config": "./config/config.js", |
||||
"#task/*": "./src/task/*", |
||||
"#workers/*": "./src/workers/*", |
||||
"#protocol/*": "./src/protocol/*", |
||||
"#processes/*": "./src/processes/*" |
||||
}, |
||||
"scripts": { |
||||
"test": "echo \"Error: no test specified\" && exit 1", |
||||
"format": "prettier --write \"src/**/*.js\"", |
||||
"start": "cross-env NODE_ENV=production node bootstrap.js", |
||||
"start:dev": "cross-env NODE_ENV=development nodemon --unhandled-rejections=throw bootstrap.js", |
||||
"test:dev": "cross-env NODE_ENV=development node bootstrap.js", |
||||
"genmodel": "cd gen-Model && sequelize-auto -h 127.0.0.1 -d lauch -u root -x root -p 3306" |
||||
}, |
||||
"keywords": [], |
||||
"author": "", |
||||
"license": "ISC", |
||||
"dependencies": { |
||||
"ajv": "^8.12.0", |
||||
"ajv-errors": "^3.0.0", |
||||
"koa": "^2.14.2", |
||||
"koa-body": "^6.0.1", |
||||
"koa-compress": "^5.1.1", |
||||
"koa-json-error": "^3.1.2", |
||||
"koa-logger": "^3.2.1", |
||||
"koa-ratelimit": "^5.0.1", |
||||
"koa-router": "^12.0.1", |
||||
"koa-useragent": "^4.1.0", |
||||
"mysql2": "^3.6.5", |
||||
"sequelize": "^6.35.1", |
||||
"winston": "^3.11.0", |
||||
"winston-daily-rotate-file": "^4.7.1" |
||||
}, |
||||
"devDependencies": { |
||||
"cross-env": "^7.0.3", |
||||
"eslint": "^8.52.0", |
||||
"eslint-config-prettier": "^9.0.0", |
||||
"eslint-plugin-prettier": "^5.0.0", |
||||
"nodemon": "^3.0.1", |
||||
"prettier": "^3.0.3", |
||||
"sequelize-auto": "^0.8.8" |
||||
} |
||||
} |
File diff suppressed because it is too large
Load Diff
@ -0,0 +1,43 @@ |
||||
// | ------------------------------------------------------------
|
||||
// | @版本: version 0.1
|
||||
// | @创建人: 【Nie-x7129】
|
||||
// | @E-mail: x71291@outlook.com
|
||||
// | @所在项目: initkoa
|
||||
// | @文件描述: production.env.js -
|
||||
// | @创建时间: 2023-11-25 21:36
|
||||
// | @更新时间: 2023-11-25 21:36
|
||||
// | @修改记录:
|
||||
// | -*-*-*- (时间--修改人--修改说明) -*-*-*-
|
||||
// | =
|
||||
// | ------------------------------------------------------------
|
||||
|
||||
|
||||
const prodConfig = { |
||||
appName: 'graphResource2', |
||||
port: 3000, |
||||
zip: true, |
||||
upfile:{ |
||||
maxFileSize: 200 * 1024 * 1024, |
||||
hashAlgorithm: false, // md5 sha1 sha256 sha512
|
||||
}, |
||||
request:{ |
||||
maxFieldsSize: 2 * 1024 * 1024,// 请求体大小
|
||||
}, |
||||
ratelimit:{ |
||||
// 同设备(IP)限制登陆次数
|
||||
status: true, |
||||
duration: 60 * 1000, |
||||
max: 3, |
||||
}, |
||||
database:{ |
||||
mysql:{ |
||||
host: '127.0.0.1', |
||||
port: 3306, |
||||
username: 'root', |
||||
password: 'root', |
||||
database: 'graph_resource2' |
||||
} |
||||
} |
||||
} |
||||
|
||||
export default prodConfig |
@ -0,0 +1,125 @@ |
||||
// | ------------------------------------------------------------
|
||||
// | @版本: version 0.1
|
||||
// | @创建人: 【Nie-x7129】
|
||||
// | @E-mail: x71291@outlook.com
|
||||
// | @所在项目: initkoa
|
||||
// | @文件描述: app.js - Koa项目的入口文件
|
||||
// | @创建时间: 2023-11-25 20:58
|
||||
// | @更新时间: 2023-11-25 20:58
|
||||
// | @修改记录:
|
||||
// | -*-*-*- (时间--修改人--修改说明) -*-*-*-
|
||||
// | =
|
||||
// | ------------------------------------------------------------
|
||||
|
||||
import Koa from 'koa'; |
||||
import koaLogger from 'koa-logger'; |
||||
import compress from 'koa-compress'; |
||||
import ratelimit from 'koa-ratelimit'; |
||||
import handleError from 'koa-json-error'; |
||||
import { koaBody } from 'koa-body'; |
||||
import { userAgent } from 'koa-useragent'; |
||||
|
||||
import rootRouter from '#routes/index.js'; |
||||
|
||||
export default function startApp() { |
||||
const app = new Koa(); |
||||
if (global.ENV === 'development') { |
||||
// | 开启自带日志
|
||||
app.use(koaLogger()); |
||||
} |
||||
|
||||
if (config.ratelimit.status) { |
||||
// | 限制同一用户的频繁请求
|
||||
app.use( |
||||
ratelimit({ |
||||
driver: 'memory', // 存储限流数据的驱动,这里使用内存驱动
|
||||
db: new Map(), // 存储被限制的客户端信息的数据结构
|
||||
duration: config.ratelimit.duration, // 时间窗口,单位毫秒
|
||||
max: config.ratelimit.max, // 时间窗口内允许的最大请求数量
|
||||
id: (ctx) => ctx.ip, // 提取每个请求的唯一标识符,默认使用请求的 IP 地址
|
||||
}), |
||||
); |
||||
} |
||||
|
||||
app.use( |
||||
handleError({ |
||||
format: (err) => { |
||||
// 返回错误的格式
|
||||
switch (err.status) { |
||||
case 400: { |
||||
return { |
||||
code: err.status, |
||||
message: err.e, |
||||
}; |
||||
break; |
||||
} |
||||
default: { |
||||
return { |
||||
code: err.status, |
||||
message: err.message, |
||||
result: ENV === 'development' && err.stack, |
||||
}; |
||||
} |
||||
} |
||||
}, |
||||
postFormat: (err, obj) => { |
||||
//根据不同环境,返回不同格式的错误信息
|
||||
const { result, ...rest } = obj; |
||||
return process.env.NODE_ENV == 'production' ? rest : obj; |
||||
}, |
||||
}), |
||||
); |
||||
|
||||
// 响应封装中间件
|
||||
async function responseHandler(ctx, next) { |
||||
// 执行后续中间件
|
||||
await next(); |
||||
// 如果有响应且没有错误状态码
|
||||
if (ctx.response.is('json') && ![404, 204].includes(ctx.status)) { |
||||
// 封装响应体为标准格式
|
||||
ctx.body = { |
||||
code: ctx.status, |
||||
success: true, |
||||
data: ctx.body, |
||||
}; |
||||
} |
||||
} |
||||
|
||||
// 在路由之前加载响应封装中间件
|
||||
app.use(responseHandler); |
||||
|
||||
if (global.zip === true) { |
||||
// | koa-compress 是一个 Koa 中间件,用于压缩 HTTP 响应。使用该中间件可减少 HTTP 响应的大小,从而提升应用程序的性能。
|
||||
app.use(compress()); |
||||
} |
||||
app.use(userAgent); |
||||
|
||||
app.use( |
||||
koaBody({ |
||||
multipart: true, // 支持文件上传
|
||||
detectJSON: true, |
||||
gzip: true, |
||||
// encoding: 'gzip',
|
||||
formidable: { |
||||
// uploadDir:path.join(__dirname,'public/upload/'), // 设置文件上传目录
|
||||
keepExtensions: true, // 保持文件的后缀
|
||||
maxFileSize: config.upfile.maxFileSize, // 文件上传大小
|
||||
maxFieldsSize: config.request.maxFieldsSize, // 除文件外的数据大小
|
||||
onFileBegin: (name, file) => { |
||||
// 文件上传前的设置
|
||||
}, |
||||
hashAlgorithm: config.upfile.hashAlgorithm, |
||||
}, |
||||
}), |
||||
); |
||||
|
||||
app.use(rootRouter.routes()); |
||||
app.use(rootRouter.allowedMethods()); |
||||
|
||||
// console.log(rootRouter)
|
||||
|
||||
const routes = rootRouter.stack.map((route) => route.path); |
||||
// console.log(routes);
|
||||
|
||||
return app; |
||||
} |
@ -0,0 +1,43 @@ |
||||
// | ------------------------------------------------------------
|
||||
// | @版本: version 0.1
|
||||
// | @创建人: 【Nie-x7129】
|
||||
// | @E-mail: x71291@outlook.com
|
||||
// | @所在项目: graphResource2
|
||||
// | @文件描述: index.js -
|
||||
// | @创建时间: 2023-12-01 21:38
|
||||
// | @更新时间: 2023-12-01 21:38
|
||||
// | @修改记录:
|
||||
// | -*-*-*- (时间--修改人--修改说明) -*-*-*-
|
||||
// | =
|
||||
// | ------------------------------------------------------------
|
||||
import {Op} from "sequelize"; |
||||
|
||||
export async function createCatch(sequelize){ |
||||
global.resourceCache = {} |
||||
// atomModelCache
|
||||
const atomModelPoolStartTime = performance.now() |
||||
const atomModelPool = await makeAtomModelCache(sequelize) |
||||
global.resourceCache.atomModelPool = atomModelPool |
||||
const atomModelPoolEndTime = performance.now() |
||||
logger.fatal(`元分类/模型缓存加载完毕: atomModelPool - ${atomModelPoolEndTime - atomModelPoolStartTime} ms`) |
||||
} |
||||
|
||||
async function makeAtomModelCache(sequelize){ |
||||
const atomModelList = await sequelize.models.AtomModel.findAll({ |
||||
attributes:['*'], |
||||
where: { |
||||
isDelete:{ |
||||
[Op.is]: null, |
||||
} |
||||
}, |
||||
raw: true, // 原始数据
|
||||
mapToModel: true, // 将下划线变成驼峰
|
||||
}); |
||||
const atomModelPool = { |
||||
length: atomModelList.length, |
||||
createtime: new Date().getTime(), |
||||
updatetime: new Date().getTime(), |
||||
data: atomModelList |
||||
} |
||||
return atomModelPool |
||||
} |
@ -0,0 +1,61 @@ |
||||
// | ------------------------------------------------------------
|
||||
// | @版本: version 0.1
|
||||
// | @创建人: 【Nie-x7129】
|
||||
// | @E-mail: x71291@outlook.com
|
||||
// | @所在项目: graphResource2
|
||||
// | @文件描述: atomModel.dataModel.js -
|
||||
// | @创建时间: 2023-12-01 13:45
|
||||
// | @更新时间: 2023-12-01 13:45
|
||||
// | @修改记录:
|
||||
// | -*-*-*- (时间--修改人--修改说明) -*-*-*-
|
||||
// | =
|
||||
// | ------------------------------------------------------------
|
||||
|
||||
import {Model} from 'sequelize'; |
||||
|
||||
export function mountAtomModel(sequelize, DataTypes) { |
||||
class AtomModel extends Model { |
||||
} |
||||
|
||||
AtomModel.init({ |
||||
// 在这里定义模型属性
|
||||
atomModelId: { |
||||
type: DataTypes.INTEGER, |
||||
autoIncrement: true, |
||||
primaryKey: true, |
||||
allowNull: false, |
||||
comment: '元分类/模型ID' |
||||
}, |
||||
atomModelName: { |
||||
type: DataTypes.STRING, |
||||
allowNull: false, |
||||
comment: '元分类/模型名称' |
||||
}, |
||||
atomModelDescribe: { |
||||
type: DataTypes.STRING(2048), |
||||
allowNull: false, |
||||
comment: '元分类/模型描述' |
||||
}, |
||||
creator:{ |
||||
type: DataTypes.STRING, |
||||
comment: "创建人" |
||||
}, |
||||
isDelete:{ |
||||
type: DataTypes.STRING(64), |
||||
comment: "删除时间" |
||||
} |
||||
}, { |
||||
// 这是其他模型参数
|
||||
sequelize, // 我们需要传递连接实例
|
||||
modelName: 'AtomModel', // 我们需要选择模型名称
|
||||
// tableName: 'atom_model',
|
||||
comment: "元分类/模型表", |
||||
timestamps: true, // 不要忘记启用时间戳!
|
||||
createdAt: 'createTimestamp', // 不想要 createdAt
|
||||
// 想要 updatedAt 但是希望名称叫做 updateTimestamp
|
||||
updatedAt: 'updateTimestamp', |
||||
underscored: true, // 改成下划线格式
|
||||
}); |
||||
|
||||
return AtomModel |
||||
} |
@ -0,0 +1,83 @@ |
||||
// | ------------------------------------------------------------
|
||||
// | @版本: version 0.1
|
||||
// | @创建人: 【Nie-x7129】
|
||||
// | @E-mail: x71291@outlook.com
|
||||
// | @所在项目: graphResource2
|
||||
// | @文件描述: baseDict.dataModel.js -
|
||||
// | @创建时间: 2023-12-01 14:37
|
||||
// | @更新时间: 2023-12-01 14:37
|
||||
// | @修改记录:
|
||||
// | -*-*-*- (时间--修改人--修改说明) -*-*-*-
|
||||
// | =
|
||||
// | ------------------------------------------------------------
|
||||
|
||||
import {Model} from 'sequelize'; |
||||
|
||||
export function mountBaseDict(sequelize, DataTypes) { |
||||
class BaseDict extends Model { |
||||
} |
||||
|
||||
BaseDict.init({ |
||||
// 在这里定义模型属性
|
||||
baseDictId: { |
||||
type: DataTypes.INTEGER, |
||||
autoIncrement: true, |
||||
primaryKey: true, |
||||
allowNull: false, |
||||
comment: '基础字典Id' |
||||
}, |
||||
atomModel: { |
||||
type: DataTypes.INTEGER, |
||||
allowNull: true, |
||||
comment: '元分类/模型Id' |
||||
}, |
||||
baseDictIsBase: { |
||||
type: DataTypes.INTEGER, |
||||
allowNull: false, |
||||
comment: '是否为基础字典(0是自定义,1是基础)', |
||||
defaultValue: 0, |
||||
}, |
||||
baseDictOriginType: { |
||||
type: DataTypes.INTEGER, |
||||
allowNull: false, |
||||
comment: '模型数据来源(0是系统内,1是系统外)', |
||||
defaultValue: 0, |
||||
}, |
||||
baseDictName:{ |
||||
type: DataTypes.STRING, |
||||
allowNull: false, |
||||
comment: "字典项名称" |
||||
}, |
||||
baseDictDescribe:{ |
||||
type: DataTypes.STRING(2048), |
||||
comment: "字典项名描述" |
||||
}, |
||||
baseDictFather:{ |
||||
type: DataTypes.INTEGER, |
||||
allowNull: false, |
||||
comment: "字典项父级", |
||||
defaultValue: 0, |
||||
}, |
||||
creator:{ |
||||
type: DataTypes.STRING, |
||||
comment: "创建人" |
||||
}, |
||||
isDelete:{ |
||||
type: DataTypes.STRING(64), |
||||
comment: "删除时间" |
||||
} |
||||
}, { |
||||
// 这是其他模型参数
|
||||
sequelize, // 我们需要传递连接实例
|
||||
modelName: 'BaseDict', // 我们需要选择模型名称
|
||||
// tableName: 'baseDict',
|
||||
comment: "基础字典表", |
||||
timestamps: true, // 不要忘记启用时间戳!
|
||||
createdAt: 'createTimestamp', // 不想要 createdAt
|
||||
// 想要 updatedAt 但是希望名称叫做 updateTimestamp
|
||||
updatedAt: 'updateTimestamp', |
||||
underscored: true, // 改成下划线格式
|
||||
}); |
||||
|
||||
return BaseDict |
||||
} |
@ -0,0 +1,103 @@ |
||||
// | ------------------------------------------------------------
|
||||
// | @版本: version 0.1
|
||||
// | @创建人: 【Nie-x7129】
|
||||
// | @E-mail: x71291@outlook.com
|
||||
// | @所在项目: graphResource2
|
||||
// | @文件描述: resourceClassBase.dataModel.js -
|
||||
// | @创建时间: 2023-12-01 14:56
|
||||
// | @更新时间: 2023-12-01 14:56
|
||||
// | @修改记录:
|
||||
// | -*-*-*- (时间--修改人--修改说明) -*-*-*-
|
||||
// | =
|
||||
// | ------------------------------------------------------------
|
||||
|
||||
// | ------------------------------------------------------------
|
||||
// | @版本: version 0.1
|
||||
// | @创建人: 【Nie-x7129】
|
||||
// | @E-mail: x71291@outlook.com
|
||||
// | @所在项目: graphResource2
|
||||
// | @文件描述: atomModel.dataModel.js -
|
||||
// | @创建时间: 2023-12-01 13:45
|
||||
// | @更新时间: 2023-12-01 13:45
|
||||
// | @修改记录:
|
||||
// | -*-*-*- (时间--修改人--修改说明) -*-*-*-
|
||||
// | =
|
||||
// | ------------------------------------------------------------
|
||||
|
||||
import { Model } from 'sequelize'; |
||||
|
||||
export function mountResourceClassBase(sequelize, DataTypes) { |
||||
class ResourceClassBase extends Model {} |
||||
|
||||
ResourceClassBase.init( |
||||
{ |
||||
// 在这里定义模型属性
|
||||
resourceClassBaseId: { |
||||
type: DataTypes.INTEGER, |
||||
autoIncrement: true, |
||||
primaryKey: true, |
||||
allowNull: false, |
||||
comment: '资源类ID', |
||||
}, |
||||
atomModel: { |
||||
type: DataTypes.INTEGER, |
||||
allowNull: false, |
||||
comment: '元分类/模型Id', |
||||
}, |
||||
resourceClassBaseDefine:{ |
||||
type: DataTypes.INTEGER, |
||||
comment: "对资源类的定义,方便建立资源结构,来源于基础字典。" |
||||
}, |
||||
resourceClassBaseIdentify:{ |
||||
type: DataTypes.STRING(8), |
||||
allowNull: false, |
||||
comment: '资源类标识', |
||||
}, |
||||
resourceClassBaseName:{ |
||||
type: DataTypes.STRING, |
||||
allowNull: false, |
||||
comment: '资源类名', |
||||
}, |
||||
resourceClassBaseDescribe: { |
||||
type: DataTypes.STRING(2048), |
||||
comment: '资源类描述', |
||||
}, |
||||
resourceClassBaseType:{ |
||||
type: DataTypes.INTEGER, |
||||
allowNull: false, |
||||
comment: "对资源类的分类,0实体、1虚拟、2管理。", |
||||
defaultValue: 0, |
||||
}, |
||||
resourceClassBaseColor:{ |
||||
type: DataTypes.STRING, |
||||
comment: '资源类名', |
||||
}, |
||||
resourceClassBaseAvatar:{ |
||||
type: DataTypes.STRING, |
||||
comment: '资源类图标', |
||||
}, |
||||
creator: { |
||||
type: DataTypes.STRING, |
||||
comment: '创建人', |
||||
}, |
||||
isDelete: { |
||||
type: DataTypes.STRING(64), |
||||
comment: '删除时间', |
||||
}, |
||||
}, |
||||
{ |
||||
// 这是其他模型参数
|
||||
sequelize, // 我们需要传递连接实例
|
||||
modelName: 'ResourceClassBase', // 我们需要选择模型名称
|
||||
// tableName: 'ResourceClassBase',
|
||||
comment: '资源类基础表', |
||||
timestamps: true, // 不要忘记启用时间戳!
|
||||
createdAt: 'createTimestamp', // 不想要 createdAt
|
||||
// 想要 updatedAt 但是希望名称叫做 updateTimestamp
|
||||
updatedAt: 'updateTimestamp', |
||||
underscored: true, // 改成下划线格式
|
||||
}, |
||||
); |
||||
|
||||
return ResourceClassBase; |
||||
} |
@ -0,0 +1,83 @@ |
||||
// | ------------------------------------------------------------
|
||||
// | @版本: version 0.1
|
||||
// | @创建人: 【Nie-x7129】
|
||||
// | @E-mail: x71291@outlook.com
|
||||
// | @所在项目: graphResource2
|
||||
// | @文件描述: resourceClassExpandField.dataModel.js -
|
||||
// | @创建时间: 2023-12-01 15:12
|
||||
// | @更新时间: 2023-12-01 15:12
|
||||
// | @修改记录:
|
||||
// | -*-*-*- (时间--修改人--修改说明) -*-*-*-
|
||||
// | =
|
||||
// | ------------------------------------------------------------
|
||||
|
||||
import { Model } from 'sequelize'; |
||||
|
||||
export function mountResourceClassExpandField(sequelize, DataTypes) { |
||||
class ResourceClassExpandField extends Model {} |
||||
|
||||
ResourceClassExpandField.init( |
||||
{ |
||||
// 在这里定义模型属性
|
||||
resourceClassExpandFieldId: { |
||||
type: DataTypes.INTEGER, |
||||
autoIncrement: true, |
||||
primaryKey: true, |
||||
allowNull: false, |
||||
comment: '资源类拓展字段ID', |
||||
}, |
||||
resourceClassBase: { |
||||
type: DataTypes.INTEGER, |
||||
allowNull: false, |
||||
comment: '资源类ID', |
||||
}, |
||||
resourceClassExpandFieldName: { |
||||
type: DataTypes.STRING, |
||||
allowNull: false, |
||||
comment: '资源类拓展字段名', |
||||
}, |
||||
resourceClassExpandFieldIdentify: { |
||||
type: DataTypes.STRING(64), |
||||
allowNull: false, |
||||
comment: '资源类拓展字段标识', |
||||
}, |
||||
resourceClassExpandFieldDisplayType: { |
||||
type: DataTypes.INTEGER, |
||||
allowNull: false, |
||||
comment: '显示类型,后期在字典添加', |
||||
defaultValue:0 |
||||
}, |
||||
resourceClassExpandFieldRelationType: { |
||||
type: DataTypes.INTEGER, |
||||
comment: '拓展字段关联类型,0字典,1资源类', |
||||
}, |
||||
resourceClassExpandFieldValue: { |
||||
type: DataTypes.STRING, |
||||
allowNull: false, |
||||
comment: '资源类拓展字段值', |
||||
}, |
||||
creator: { |
||||
type: DataTypes.STRING, |
||||
comment: '创建人', |
||||
}, |
||||
isDelete: { |
||||
type: DataTypes.STRING(64), |
||||
comment: '删除时间', |
||||
}, |
||||
}, |
||||
{ |
||||
// 这是其他模型参数
|
||||
sequelize, // 我们需要传递连接实例
|
||||
modelName: 'ResourceClassExpandField', // 我们需要选择模型名称
|
||||
// tableName: 'ResourceClassExpandField',
|
||||
comment: '资源类拓展字段表', |
||||
timestamps: true, // 不要忘记启用时间戳!
|
||||
createdAt: 'createTimestamp', // 不想要 createdAt
|
||||
// 想要 updatedAt 但是希望名称叫做 updateTimestamp
|
||||
updatedAt: 'updateTimestamp', |
||||
underscored: true, // 改成下划线格式
|
||||
}, |
||||
); |
||||
|
||||
return ResourceClassExpandField; |
||||
} |
@ -0,0 +1,60 @@ |
||||
// | ------------------------------------------------------------
|
||||
// | @版本: version 0.1
|
||||
// | @创建人: 【Nie-x7129】
|
||||
// | @E-mail: x71291@outlook.com
|
||||
// | @所在项目: graphResource2
|
||||
// | @文件描述: resourceClassRelation.dataModel.js -
|
||||
// | @创建时间: 2023-12-01 15:23
|
||||
// | @更新时间: 2023-12-01 15:23
|
||||
// | @修改记录:
|
||||
// | -*-*-*- (时间--修改人--修改说明) -*-*-*-
|
||||
// | =
|
||||
// | ------------------------------------------------------------
|
||||
import {Model} from 'sequelize'; |
||||
|
||||
export function mountResourceClassRelation(sequelize, DataTypes) { |
||||
class ResourceClassRelation extends Model { |
||||
} |
||||
|
||||
ResourceClassRelation.init({ |
||||
// 在这里定义模型属性
|
||||
resourceClassRelationId: { |
||||
type: DataTypes.INTEGER, |
||||
autoIncrement: true, |
||||
primaryKey: true, |
||||
allowNull: false, |
||||
comment: '资源类关系ID' |
||||
}, |
||||
resourceClassRelationTarget: { |
||||
type: DataTypes.INTEGER, |
||||
allowNull: false, |
||||
comment: '目标资源类ID' |
||||
}, |
||||
resourceClassRelationFather: { |
||||
type: DataTypes.INTEGER, |
||||
allowNull: false, |
||||
comment: '父资源类ID' |
||||
}, |
||||
creator:{ |
||||
type: DataTypes.STRING, |
||||
comment: "创建人" |
||||
}, |
||||
isDelete:{ |
||||
type: DataTypes.STRING(64), |
||||
comment: "删除时间" |
||||
} |
||||
}, { |
||||
// 这是其他模型参数
|
||||
sequelize, // 我们需要传递连接实例
|
||||
modelName: 'ResourceClassRelation', // 我们需要选择模型名称
|
||||
// tableName: 'ResourceClassRelation',
|
||||
comment: "资源类关系表", |
||||
timestamps: true, // 不要忘记启用时间戳!
|
||||
createdAt: 'createTimestamp', // 不想要 createdAt
|
||||
// 想要 updatedAt 但是希望名称叫做 updateTimestamp
|
||||
updatedAt: 'updateTimestamp', |
||||
underscored: true, // 改成下划线格式
|
||||
}); |
||||
|
||||
return ResourceClassRelation |
||||
} |
@ -0,0 +1,60 @@ |
||||
// | ------------------------------------------------------------
|
||||
// | @版本: version 0.1
|
||||
// | @创建人: 【Nie-x7129】
|
||||
// | @E-mail: x71291@outlook.com
|
||||
// | @所在项目: graphResource2
|
||||
// | @文件描述: resourceEntityRelation.dataModel.js -
|
||||
// | @创建时间: 2023-12-01 15:23
|
||||
// | @更新时间: 2023-12-01 15:23
|
||||
// | @修改记录:
|
||||
// | -*-*-*- (时间--修改人--修改说明) -*-*-*-
|
||||
// | =
|
||||
// | ------------------------------------------------------------
|
||||
import {Model} from 'sequelize'; |
||||
|
||||
export function mountResourceEntityRelation(sequelize, DataTypes) { |
||||
class ResourceEntityRelation extends Model { |
||||
} |
||||
|
||||
ResourceEntityRelation.init({ |
||||
// 在这里定义模型属性
|
||||
resourceEntityRelationId: { |
||||
type: DataTypes.INTEGER, |
||||
autoIncrement: true, |
||||
primaryKey: true, |
||||
allowNull: false, |
||||
comment: '资源关系ID' |
||||
}, |
||||
resourceEntityRelationTarget: { |
||||
type: DataTypes.INTEGER, |
||||
allowNull: false, |
||||
comment: '目标资源ID' |
||||
}, |
||||
resourceEntityRelationFather: { |
||||
type: DataTypes.INTEGER, |
||||
allowNull: false, |
||||
comment: '父资源ID' |
||||
}, |
||||
creator:{ |
||||
type: DataTypes.STRING, |
||||
comment: "创建人" |
||||
}, |
||||
isDelete:{ |
||||
type: DataTypes.STRING(64), |
||||
comment: "删除时间" |
||||
} |
||||
}, { |
||||
// 这是其他模型参数
|
||||
sequelize, // 我们需要传递连接实例
|
||||
modelName: 'ResourceEntityRelation', // 我们需要选择模型名称
|
||||
// tableName: 'ResourceEntityRelation',
|
||||
comment: "资源实体关系表", |
||||
timestamps: true, // 不要忘记启用时间戳!
|
||||
createdAt: 'createTimestamp', // 不想要 createdAt
|
||||
// 想要 updatedAt 但是希望名称叫做 updateTimestamp
|
||||
updatedAt: 'updateTimestamp', |
||||
underscored: true, // 改成下划线格式
|
||||
}); |
||||
|
||||
return ResourceEntityRelation |
||||
} |
@ -0,0 +1,130 @@ |
||||
// | ------------------------------------------------------------
|
||||
// | @版本: version 0.1
|
||||
// | @创建人: 【Nie-x7129】
|
||||
// | @E-mail: x71291@outlook.com
|
||||
// | @所在项目: graphResource2
|
||||
// | @文件描述: resourceEntityStruct.dataModel.js -
|
||||
// | @创建时间: 2023-12-01 15:38
|
||||
// | @更新时间: 2023-12-01 15:38
|
||||
// | @修改记录:
|
||||
// | -*-*-*- (时间--修改人--修改说明) -*-*-*-
|
||||
// | =
|
||||
// | ------------------------------------------------------------
|
||||
import {Model} from 'sequelize'; |
||||
|
||||
export function mountResourceEntityStruct(sequelize, DataTypes) { |
||||
class ResourceEntityStruct extends Model { |
||||
} |
||||
|
||||
ResourceEntityStruct.init({ |
||||
// 在这里定义模型属性
|
||||
resourceEntityStructId: { |
||||
type: DataTypes.INTEGER, |
||||
// type: DataTypes.STRING,
|
||||
autoIncrement: true, |
||||
primaryKey: true, |
||||
allowNull: false, |
||||
comment: '元分类/模型ID' |
||||
}, |
||||
resourceClassBase: { |
||||
type: DataTypes.INTEGER, |
||||
allowNull: false, |
||||
comment: '资源类ID', |
||||
}, |
||||
resourceEntityStructName:{ |
||||
type: DataTypes.STRING, |
||||
allowNull: false, |
||||
comment: '资源实体字段名', |
||||
}, |
||||
resourceEntityStructIdentify:{ |
||||
type: DataTypes.STRING(64), |
||||
allowNull: false, |
||||
comment: '资源实体字段标识', |
||||
}, |
||||
resourceEntityStructNickname:{ |
||||
type: DataTypes.STRING, |
||||
comment: '资源实体字段别名', |
||||
}, |
||||
resourceEntityStructDescribe:{ |
||||
type: DataTypes.STRING(2048), |
||||
comment: '资源实体字段描述', |
||||
}, |
||||
resourceEntityStructRank:{ |
||||
type: DataTypes.INTEGER, |
||||
comment: '资源实体字段排序', |
||||
default:0, |
||||
}, |
||||
resourceEntityStructStorageType:{ |
||||
type: DataTypes.INTEGER, |
||||
allowNull: false, |
||||
comment: '资源实体字段在数据库中存储的类型', |
||||
}, |
||||
resourceEntityStructStorageLength:{ |
||||
type: DataTypes.INTEGER, |
||||
allowNull: false, |
||||
comment: '资源实体字段在数据库中存储的长度', |
||||
defaultValue: 20, |
||||
}, |
||||
resourceEntityStructDisplayType:{ |
||||
type: DataTypes.INTEGER, |
||||
allowNull: false, |
||||
comment: '资源实体字段显示类型', |
||||
defaultValue: 0, |
||||
}, |
||||
resourceEntityStructIsGather:{ |
||||
type: DataTypes.BOOLEAN, |
||||
allowNull: false, |
||||
comment: '资源实体字段是否采集(0是采集、1是不采集)', |
||||
defaultValue: 0, |
||||
}, |
||||
resourceEntityStructAppIsShow:{ |
||||
type: DataTypes.BOOLEAN, |
||||
allowNull: false, |
||||
comment: '资源实体字段是否显示在APP上(0是显示、1是不显示)', |
||||
defaultValue: 0, |
||||
}, |
||||
resourceEntityStructWebIsShow:{ |
||||
type: DataTypes.BOOLEAN, |
||||
allowNull: false, |
||||
comment: '资源实体字段是否显示在Web上(0是显示、1是不显示)', |
||||
defaultValue: 0, |
||||
}, |
||||
resourceEntityStructAppNickname:{ |
||||
type: DataTypes.STRING, |
||||
comment: '资源实体字段APP别名', |
||||
}, |
||||
resourceEntityStructWebNickname:{ |
||||
type: DataTypes.STRING, |
||||
comment: '资源实体字段Web别名', |
||||
}, |
||||
resourceEntityStructRelationType:{ |
||||
type: DataTypes.INTEGER, |
||||
comment: '资源实体字段关联类型', |
||||
}, |
||||
resourceEntityStructRelationValue:{ |
||||
type: DataTypes.INTEGER, |
||||
comment: '资源实体字段关联值', |
||||
}, |
||||
creator:{ |
||||
type: DataTypes.STRING, |
||||
comment: "创建人" |
||||
}, |
||||
isDelete:{ |
||||
type: DataTypes.STRING(64), |
||||
comment: "删除时间" |
||||
} |
||||
}, { |
||||
// 这是其他模型参数
|
||||
sequelize, // 我们需要传递连接实例
|
||||
modelName: 'ResourceEntityStruct', // 我们需要选择模型名称
|
||||
// tableName: 'ResourceEntityStruct',
|
||||
comment: "资源实体字段结构表", |
||||
timestamps: true, // 不要忘记启用时间戳!
|
||||
createdAt: 'createTimestamp', // 不想要 createdAt
|
||||
// 想要 updatedAt 但是希望名称叫做 updateTimestamp
|
||||
updatedAt: 'updateTimestamp', |
||||
underscored: true, // 改成下划线格式
|
||||
}); |
||||
|
||||
return ResourceEntityStruct |
||||
} |
@ -0,0 +1,60 @@ |
||||
// | ------------------------------------------------------------
|
||||
// | @版本: version 0.1
|
||||
// | @创建人: 【Nie-x7129】
|
||||
// | @E-mail: x71291@outlook.com
|
||||
// | @所在项目: expressgy-web-lauch
|
||||
// | @文件描述: index.js -
|
||||
// | @创建时间: 2023-11-28 22:27
|
||||
// | @更新时间: 2023-11-28 22:27
|
||||
// | @修改记录:
|
||||
// | -*-*-*- (时间--修改人--修改说明) -*-*-*-
|
||||
// | =
|
||||
// | ------------------------------------------------------------
|
||||
|
||||
import { Sequelize, DataTypes } from 'sequelize'; |
||||
|
||||
import { mountAtomModel } from '#dataModels/atomModel.dataModel.js'; |
||||
import { mountBaseDict } from '#dataModels/baseDict.dataModel.js'; |
||||
import { mountResourceClassBase } from '#dataModels/resourceClassBase.dataModel.js'; |
||||
import { mountResourceClassExpandField } from '#dataModels/resourceClassExpandField.dataModel.js'; |
||||
import {mountResourceClassRelation} from "#dataModels/resourceClassRelation.dataModel.js"; |
||||
import {mountResourceEntityStruct} from "#dataModels/resourceEntityStruct.dataModel.js"; |
||||
import {mountResourceEntityRelation} from "#dataModels/resourceEntityRelation.dataModel.js"; |
||||
|
||||
// import prodConfig from "#root/production.env.js";
|
||||
//
|
||||
// global.config = prodConfig
|
||||
|
||||
export default function createDatabase(logger) { |
||||
const { database, username, password, host, port } = |
||||
global.config.database.mysql; |
||||
console.log(database, username, password, host, port); |
||||
const sequelize = new Sequelize(database, username, password, { |
||||
host, |
||||
dialect: 'mysql', // 根据你的数据库类型修改
|
||||
underscored: true, |
||||
timezone: '+08:00', // 时区设置为东八区
|
||||
dialectOptions: { |
||||
dateStrings: true, // 将所有日期字段值转换成字符串格式
|
||||
typeCast: true, // 允许将字符串类型的日期字段值自动转换为 Date 类型
|
||||
}, |
||||
// 以下为一些额外配置选项
|
||||
// pool: {
|
||||
// max: 5,
|
||||
// min: 0,
|
||||
// acquire: 30000,
|
||||
// idle: 10000
|
||||
// },
|
||||
logging: logger.debug.bind(logger), |
||||
}); |
||||
|
||||
mountAtomModel(sequelize, DataTypes); |
||||
mountBaseDict(sequelize, DataTypes); |
||||
mountResourceClassBase(sequelize, DataTypes); |
||||
mountResourceClassExpandField(sequelize, DataTypes); |
||||
mountResourceClassRelation(sequelize, DataTypes) |
||||
mountResourceEntityStruct(sequelize,DataTypes) |
||||
mountResourceEntityRelation(sequelize,DataTypes) |
||||
return sequelize; |
||||
} |
||||
// createDatabase()
|
@ -0,0 +1,36 @@ |
||||
// | ------------------------------------------------------------
|
||||
// | @版本: version 0.1
|
||||
// | @创建人: 【Nie-x7129】
|
||||
// | @E-mail: x71291@outlook.com
|
||||
// | @所在项目: initkoa
|
||||
// | @文件描述: index.js -
|
||||
// | @创建时间: 2023-11-26 15:41
|
||||
// | @更新时间: 2023-11-26 15:41
|
||||
// | @修改记录:
|
||||
// | -*-*-*- (时间--修改人--修改说明) -*-*-*-
|
||||
// | =
|
||||
// | ------------------------------------------------------------
|
||||
import Ajv from 'ajv'; |
||||
import addAjvErrors from 'ajv-errors'; |
||||
|
||||
export default function makeDTO(data, schema) { |
||||
const ajv = new Ajv({ |
||||
allErrors: true, //多错误消息
|
||||
// jsonPointers: true, // 消息写在内部吗?? JSON 指针是一个字符串表示法,用于在 JSON 文档中指定特定的路径。它采用一种类似于文件路径的结构,通过使用斜杠 / 来分隔层级,例如 /path/to/property
|
||||
coerceTypes: true, // 类型转换
|
||||
useDefaults: true |
||||
}); |
||||
|
||||
addAjvErrors(ajv); |
||||
const validate = ajv.compile(schema); |
||||
const valid = validate(data); |
||||
const message = { |
||||
status: true, |
||||
error: null, |
||||
}; |
||||
if (!valid) { |
||||
message.status = false; |
||||
message.error = validate.errors; |
||||
} |
||||
return message; |
||||
} |
@ -0,0 +1,91 @@ |
||||
// | ------------------------------------------------------------
|
||||
// | @版本: version 0.1
|
||||
// | @创建人: 【Nie-x7129】
|
||||
// | @E-mail: x71291@outlook.com
|
||||
// | @所在项目: initkoa
|
||||
// | @文件描述: index.js -
|
||||
// | @创建时间: 2023-11-26 14:51
|
||||
// | @更新时间: 2023-11-26 14:51
|
||||
// | @修改记录:
|
||||
// | -*-*-*- (时间--修改人--修改说明) -*-*-*-
|
||||
// | =
|
||||
// | ------------------------------------------------------------
|
||||
|
||||
import winston from "winston"; |
||||
import "winston-daily-rotate-file" |
||||
|
||||
|
||||
// 自定义日志等级和颜色
|
||||
const myCustomLevels = { |
||||
levels:{ |
||||
fatal: 0, |
||||
error: 1, |
||||
warn: 2, |
||||
info: 3, |
||||
debug: 4, |
||||
trace: 5 |
||||
}, |
||||
// 字体样式:bold, dim,italic, underline, inverse, hidden, strikethrough
|
||||
// 字体背景颜色:black, red, green, yellow, blue, magenta紫色, cyan青色, white, gray, grey
|
||||
// 背景颜色:blackBG, redBG, greenBG, yellowBG, blueBG, magentaBG, cyanBG, whiteBG
|
||||
levelsColor:{ |
||||
fatal: 'bold red cyanBG italic underline', |
||||
error: 'bold magenta', |
||||
warn: 'yellow', |
||||
info: 'green', |
||||
debug: 'cyan', |
||||
trace: 'white' |
||||
} |
||||
} |
||||
// 创建颜色方法
|
||||
export const colorizer = winston.format.colorize(); |
||||
colorizer.addColors(myCustomLevels.levelsColor) |
||||
|
||||
export const logger = winston.createLogger({ |
||||
level: 'trace', // 日志打印等级
|
||||
levels: myCustomLevels.levels,// 日志等级列表
|
||||
exitOnError: false,// 如果为false,处理异常不会导致process.exit
|
||||
silent: false, // 如果为true,所有日志被抑制
|
||||
format: winston.format.combine( |
||||
winston.format.errors({ stack: true }), |
||||
winston.format.json(), |
||||
winston.format.timestamp({ format: "YYYY-MM-DD HH:mm:ss:SSS" }), |
||||
// winston.format.printf(
|
||||
// (i) => {
|
||||
// // const splatList = Array.from(Object.getOwnPropertySymbols(i))
|
||||
// // const splat = splatList && splatList.filter(item => item.toString() === 'Symbol(splat)')
|
||||
// // const splatName = splat.length == 1 ? splat[0] : null
|
||||
// // const data = splatName ? JSON.stringify([i.message, ...i[splatName]]) : JSON.stringify({message:i.message})
|
||||
// return `${i.timestamp} [${i.level.padEnd(5, ' ').toUpperCase()}] ${i.message}`
|
||||
// },
|
||||
// ),
|
||||
), |
||||
transports: [ |
||||
new winston.transports.DailyRotateFile({ |
||||
filename: "winston-logs/%DATE%-INFO--winston.log", |
||||
level: "info", |
||||
datePattern: "YYYY-MM-DD", |
||||
zippedArchive: true,// 启用压缩
|
||||
maxSize: "10m",// 单文件大小
|
||||
maxFiles: "30d",// 存储时间
|
||||
}), |
||||
new winston.transports.DailyRotateFile({ |
||||
filename: "winston-logs/%DATE%-ERROR-winston.log", |
||||
level: "error", |
||||
datePattern: "YYYY-MM-DD", |
||||
zippedArchive: true, |
||||
maxSize: "10m", |
||||
maxFiles: "365d", |
||||
}), |
||||
], |
||||
// winston可以捕获和记录异常
|
||||
// exceptionHandlers: [
|
||||
// new winston.transports.File({ filename: 'winston-logs/winston-exceptions.log' })
|
||||
// ],
|
||||
// 捕获uncaughtRejection事件
|
||||
// rejectionHandlers: [
|
||||
// new winston.transports.File({ filename: 'winston-logs/rejections.log' })
|
||||
// ]
|
||||
}); |
||||
// 后续加入记录器,这里可以加入环境变量的判断,当为生产模式时,取消控制台的打印操作。
|
||||
|
@ -0,0 +1,20 @@ |
||||
// | ------------------------------------------------------------
|
||||
// | @版本: version 0.1
|
||||
// | @创建人: 【Nie-x7129】
|
||||
// | @E-mail: x71291@outlook.com
|
||||
// | @所在项目: graphResource2
|
||||
// | @文件描述: getArrayPage.js -
|
||||
// | @创建时间: 2023-12-01 22:48
|
||||
// | @更新时间: 2023-12-01 22:48
|
||||
// | @修改记录:
|
||||
// | -*-*-*- (时间--修改人--修改说明) -*-*-*-
|
||||
// | =
|
||||
// | ------------------------------------------------------------
|
||||
|
||||
export default function getPage(array, pageSize, pageNumber){ |
||||
const startIndex = (pageNumber - 1) * pageSize; |
||||
|
||||
// 使用 slice() 方法获取分页内容
|
||||
const pageContent = array.slice(startIndex, startIndex + pageSize); |
||||
return pageContent |
||||
} |
@ -0,0 +1,16 @@ |
||||
// | ------------------------------------------------------------
|
||||
// | @版本: version 0.1
|
||||
// | @创建人: 【Nie-x7129】
|
||||
// | @E-mail: x71291@outlook.com
|
||||
// | @所在项目: graphResource2
|
||||
// | @文件描述: getNoSpacesStr.js -
|
||||
// | @创建时间: 2023-12-01 22:54
|
||||
// | @更新时间: 2023-12-01 22:54
|
||||
// | @修改记录:
|
||||
// | -*-*-*- (时间--修改人--修改说明) -*-*-*-
|
||||
// | =
|
||||
// | ------------------------------------------------------------
|
||||
|
||||
export default function getNoSpacesStr(str){ |
||||
return str.replace(/\s/g, ''); |
||||
} |
@ -0,0 +1,180 @@ |
||||
// | ------------------------------------------------------------
|
||||
// | @版本: version 0.1
|
||||
// | @创建人: 【Nie-x7129】
|
||||
// | @E-mail: x71291@outlook.com
|
||||
// | @所在项目: graphResource2
|
||||
// | @文件描述: index.dto.js -
|
||||
// | @创建时间: 2023-12-01 18:13
|
||||
// | @更新时间: 2023-12-01 18:13
|
||||
// | @修改记录:
|
||||
// | -*-*-*- (时间--修改人--修改说明) -*-*-*-
|
||||
// | =
|
||||
// | ------------------------------------------------------------
|
||||
|
||||
import makeDTO from '#common/dto/index.js'; |
||||
|
||||
export function CreateAtomModelItemDTO(data) { |
||||
const schema = { |
||||
type: 'object', |
||||
properties: { |
||||
atomModelName: { |
||||
type: 'string', |
||||
minLength: 1, |
||||
maxLength: 255, |
||||
pattern: "^[a-zA-Z\\s]+$", |
||||
errorMessage: { |
||||
type: '元分类/模型名称必须是一个字符串', |
||||
maxLength: '元分类/模型名称长度超出限制255', |
||||
minLength: '元分类/模型名称长度过短', |
||||
pattern: '元分类/模型名称必须为纯英文' |
||||
}, |
||||
}, |
||||
atomModelDescribe: { |
||||
type: 'string', |
||||
minLength: 1, |
||||
maxLength: 2048, |
||||
errorMessage: { |
||||
type: '元分类/模型描述必须是一个字符串', |
||||
maxLength: '元分类/模型描述长度超出限制2048', |
||||
minLength: '元分类/模型描述长度过短', |
||||
}, |
||||
}, |
||||
}, |
||||
required: ['atomModelName', 'atomModelDescribe'], |
||||
errorMessage: { |
||||
required: { |
||||
atomModelName: '元分类/模型名称为必填项', |
||||
atomModelDescribe: '元分类/模型描述为必填项', |
||||
}, |
||||
}, |
||||
}; |
||||
return makeDTO(data, schema); |
||||
} |
||||
|
||||
export function DeleteAtomModelItemDTO(data) { |
||||
const schema = { |
||||
type: 'object', |
||||
properties: { |
||||
atomModelId: { |
||||
type: 'integer', |
||||
errorMessage: { |
||||
type: '元分类/模型id必须是整数', |
||||
}, |
||||
}, |
||||
}, |
||||
required: ['atomModelId'], |
||||
errorMessage: { |
||||
required: { |
||||
atomModelId: '元分类/模型ID为为必填项', |
||||
}, |
||||
}, |
||||
}; |
||||
return makeDTO(data, schema); |
||||
} |
||||
|
||||
export function EditAtomModelItemDTO(data) { |
||||
const schema = { |
||||
type: 'object', |
||||
properties: { |
||||
atomModelId: { |
||||
type: 'integer', |
||||
errorMessage: { |
||||
type: '元分类/模型id必须是整数', |
||||
}, |
||||
}, |
||||
atomModelName: { |
||||
type: 'string', |
||||
minLength: 1, |
||||
maxLength: 255, |
||||
errorMessage: { |
||||
type: '元分类/模型名称必须是一个字符串', |
||||
maxLength: '元分类/模型名称长度超出限制255', |
||||
minLength: '元分类/模型名称长度过短', |
||||
}, |
||||
}, |
||||
atomModelDescribe: { |
||||
type: 'string', |
||||
minLength: 1, |
||||
maxLength: 2048, |
||||
errorMessage: { |
||||
type: '元分类/模型描述必须是一个字符串', |
||||
maxLength: '元分类/模型描述长度超出限制2048', |
||||
minLength: '元分类/模型描述长度过短', |
||||
}, |
||||
}, |
||||
}, |
||||
required: ['atomModelName', 'atomModelDescribe', 'atomModelId'], |
||||
errorMessage: { |
||||
required: { |
||||
atomModelName: '元分类/模型名称为必填项', |
||||
atomModelDescribe: '元分类/模型描述为必填项', |
||||
atomModelId: '元分类/模型ID为为必填项', |
||||
}, |
||||
}, |
||||
}; |
||||
return makeDTO(data, schema); |
||||
} |
||||
|
||||
export function CheckAtomModelItemNameDTO(data) { |
||||
const schema = { |
||||
type: 'object', |
||||
properties: { |
||||
atomModelName: { |
||||
type: 'string', |
||||
minLength: 1, |
||||
maxLength: 255, |
||||
pattern: "^[a-zA-Z\\s]+$", |
||||
errorMessage: { |
||||
type: '元分类/模型名称必须是一个字符串', |
||||
maxLength: '元分类/模型名称长度超出限制255', |
||||
minLength: '元分类/模型名称长度过短', |
||||
pattern: '元分类/模型名称必须为纯英文' |
||||
}, |
||||
}, |
||||
}, |
||||
required: ['atomModelName'], |
||||
errorMessage: { |
||||
required: { |
||||
atomModelName: '元分类/模型名称为必填项', |
||||
}, |
||||
}, |
||||
}; |
||||
return makeDTO(data, schema); |
||||
} |
||||
|
||||
export function GetAtomModelPageDTO(data) { |
||||
const schema = { |
||||
type: 'object', |
||||
properties: { |
||||
pageSize: { |
||||
type: 'integer', |
||||
minimum: 1, |
||||
maximum: 200, |
||||
default:10, |
||||
errorMessage: { |
||||
type: '每页数量必须是一个数字', |
||||
minimum: '每页数量最少是1', |
||||
maximum: '每页数量最多是200', |
||||
}, |
||||
}, |
||||
pageNum: { |
||||
type: 'integer', |
||||
minimum:1, |
||||
default: 1, |
||||
errorMessage: { |
||||
type: '页码必须是数字类型', |
||||
minimum: '页码最小是1', |
||||
}, |
||||
}, |
||||
searchData: { |
||||
type: 'string', |
||||
maxLength: 255, |
||||
errorMessage: { |
||||
type: '查询内容必须是一个字符串', |
||||
maxLength: '查询内容长度超出限制255', |
||||
}, |
||||
}, |
||||
}, |
||||
}; |
||||
return makeDTO(data, schema); |
||||
} |
@ -0,0 +1,180 @@ |
||||
// | ------------------------------------------------------------
|
||||
// | @版本: version 0.1
|
||||
// | @创建人: 【Nie-x7129】
|
||||
// | @E-mail: x71291@outlook.com
|
||||
// | @所在项目: graphResource2
|
||||
// | @文件描述: index.js -
|
||||
// | @创建时间: 2023-12-01 17:50
|
||||
// | @更新时间: 2023-12-01 17:50
|
||||
// | @修改记录:
|
||||
// | -*-*-*- (时间--修改人--修改说明) -*-*-*-
|
||||
// | =
|
||||
// | ------------------------------------------------------------
|
||||
|
||||
import Router from 'koa-router'; |
||||
|
||||
import { |
||||
CheckAtomModelItemNameDTO, |
||||
CreateAtomModelItemDTO, |
||||
DeleteAtomModelItemDTO, |
||||
EditAtomModelItemDTO, |
||||
GetAtomModelPageDTO, |
||||
} from '#routes/graphResource2/atomModel/index.dto.js'; |
||||
import getPage from '#common/tools/getArrayPage.js'; |
||||
import getNoSpacesStr from '#common/tools/getNoSpacesStr.js'; |
||||
|
||||
const atomModel = new Router(); |
||||
|
||||
// @ 获取元分类模型页
|
||||
atomModel.get('/getAtomModelPage', async (ctx, next) => { |
||||
const verif = GetAtomModelPageDTO(ctx.query); |
||||
if (!verif.status) { |
||||
ctx.throw(400, { e: verif.error.map((i) => i.message) }); |
||||
return; |
||||
} |
||||
let list = resourceCache.atomModelPool.data; |
||||
if (ctx.query.searchData) { |
||||
const searchData = ctx.query.searchData; |
||||
list = list.filter((i) => { |
||||
return (i.atomModelName + i.atomModelDescribe).includes(searchData); |
||||
}); |
||||
} |
||||
const total = list.length; |
||||
list = getPage(list, ctx.query.pageSize, ctx.query.pageNum); |
||||
ctx.body = { |
||||
total, |
||||
data: list, |
||||
}; |
||||
}); |
||||
|
||||
// @ 获取元分类列表
|
||||
atomModel.get('/getAtomModelList', async (ctx, next) => { |
||||
ctx.body = resourceCache.atomModelPool.data.map((i) => ({ |
||||
atomModelId: i.atomModelId, |
||||
atomModelName: i.atomModelName, |
||||
})); |
||||
}); |
||||
|
||||
// @ 新建元分类
|
||||
atomModel.post('/createAtomModelItem', async (ctx, next) => { |
||||
const verif = CreateAtomModelItemDTO(ctx.request.body); |
||||
if (!verif.status) { |
||||
ctx.throw(400, { e: verif.error.map((i) => i.message) }); |
||||
return; |
||||
} |
||||
let { atomModelName, atomModelDescribe } = ctx.request.body; |
||||
atomModelName = getNoSpacesStr(atomModelName).toUpperCase(); |
||||
if (checkName(atomModelName) == -1) { |
||||
const newAtomModel = await ctx.sequelize.models.AtomModel.create({ |
||||
atomModelName, |
||||
atomModelDescribe, |
||||
}); |
||||
resourceCache.atomModelPool.data.push(newAtomModel.dataValues); |
||||
resourceCache.atomModelPool.length++; |
||||
resourceCache.atomModelPool.updatetime = new Date().getTime(); |
||||
ctx.body = { |
||||
message: '新建元分类成功。', |
||||
data: newAtomModel.dataValues, |
||||
}; |
||||
} else { |
||||
ctx.throw(400, { e: `元分类/模型重名: ${atomModelName}` }); |
||||
} |
||||
}); |
||||
|
||||
// @ 编辑元分类
|
||||
atomModel.post('/editAtomModelItem', async (ctx, next) => { |
||||
const verif = EditAtomModelItemDTO(ctx.request.body); |
||||
if (!verif.status) { |
||||
ctx.throw(400, { e: verif.error.map((i) => i.message) }); |
||||
return; |
||||
} |
||||
let { atomModelName, atomModelDescribe, atomModelId } = ctx.request.body; |
||||
console.log(atomModelName) |
||||
atomModelName = getNoSpacesStr(atomModelName).toUpperCase() |
||||
const index= checkName(atomModelName) |
||||
if([-1, atomModelId].includes(resourceCache.atomModelPool.data[index].atomModelId)){ |
||||
if(resourceCache.atomModelPool.data[index].atomModelDescribe == atomModelDescribe && resourceCache.atomModelPool.data[index].atomModelName == atomModelName){ |
||||
ctx.body = { |
||||
message: '编辑元分类/模型成功', |
||||
}; |
||||
return |
||||
} |
||||
resourceCache.atomModelPool.data[index].atomModelDescribe = atomModelDescribe; |
||||
resourceCache.atomModelPool.data[index].atomModelName = atomModelName |
||||
resourceCache.atomModelPool.updatetime = new Date().getTime(); |
||||
ctx.body = { |
||||
message: '编辑元分类/模型成功', |
||||
}; |
||||
await next(); |
||||
await ctx.sequelize.models.AtomModel.update( |
||||
{ atomModelName, atomModelDescribe, }, |
||||
{ where: { atomModelId } }, |
||||
); |
||||
}else{ |
||||
ctx.throw(400, {e: '元分类/模型名称重复'}) |
||||
} |
||||
|
||||
}); |
||||
|
||||
// @ 查重元分类名称
|
||||
atomModel.get('/checkAtomModelItemName', async (ctx, next) => { |
||||
const verif = CheckAtomModelItemNameDTO(ctx.query); |
||||
if (!verif.status) { |
||||
ctx.throw(400, { e: verif.error.map((i) => i.message) }); |
||||
return; |
||||
} |
||||
let { atomModelName } = ctx.query; |
||||
atomModelName = getNoSpacesStr(atomModelName).toUpperCase(); |
||||
if (checkName(atomModelName) == -1) { |
||||
ctx.body = { message: '元分类/模型名称可用' }; |
||||
} else { |
||||
ctx.throw(400, { e: '元分类/模型名称重复' }); |
||||
} |
||||
}); |
||||
|
||||
// @ 删除元分类
|
||||
atomModel.delete('/deleteAtomModelItem', async (ctx, next) => { |
||||
const verif = DeleteAtomModelItemDTO(ctx.query); |
||||
if (!verif.status) { |
||||
ctx.throw(400, { e: verif.error.map((i) => i.message) }); |
||||
return; |
||||
} |
||||
const { atomModelId } = ctx.query; |
||||
let index = -1; |
||||
for (let i in resourceCache.atomModelPool.data) { |
||||
if (resourceCache.atomModelPool.data[i].atomModelId == atomModelId) { |
||||
index = i; |
||||
break; |
||||
} |
||||
} |
||||
if (index == -1) { |
||||
ctx.throw(400, { e: '不存在此元分类/模型记录。' }); |
||||
return; |
||||
} |
||||
resourceCache.atomModelPool.data.splice(index, 1); |
||||
resourceCache.atomModelPool.length--; |
||||
resourceCache.atomModelPool.updatetime = new Date().getTime(); |
||||
ctx.body = { message: '删除元分类/模型成功。' }; |
||||
await next(); |
||||
await ctx.sequelize.models.AtomModel.update( |
||||
{ isDelete: new Date().toISOString() }, |
||||
{ where: { atomModelId } }, |
||||
); |
||||
}); |
||||
|
||||
export default atomModel; |
||||
|
||||
// = 函数名: checkName
|
||||
// = 描述: 查重模型名称
|
||||
// = 参数: None
|
||||
// = 返回值: undefined
|
||||
// = 创建人: expressgy
|
||||
// = 创建时间: 2023-12-01 22:56:12 -
|
||||
function checkName(name) { |
||||
for (let i in resourceCache.atomModelPool.data) { |
||||
if (name == resourceCache.atomModelPool.data[i].atomModelName) { |
||||
return i; |
||||
} |
||||
} |
||||
return -1; |
||||
} |
@ -0,0 +1,206 @@ |
||||
// | ------------------------------------------------------------
|
||||
// | @版本: version 0.1
|
||||
// | @创建人: 【Nie-x7129】
|
||||
// | @E-mail: x71291@outlook.com
|
||||
// | @所在项目: graphResource2
|
||||
// | @文件描述: index.dto.js -
|
||||
// | @创建时间: 2023-12-02 00:21
|
||||
// | @更新时间: 2023-12-02 00:21
|
||||
// | @修改记录:
|
||||
// | -*-*-*- (时间--修改人--修改说明) -*-*-*-
|
||||
// | =
|
||||
// | ------------------------------------------------------------
|
||||
|
||||
import makeDTO from '#common/dto/index.js'; |
||||
|
||||
export function GetBaseDictTreeDTO(data) { |
||||
const schema = { |
||||
type: 'object', |
||||
properties: { |
||||
atomModelId: { |
||||
type: ['integer', 'null'], |
||||
minimum: 0, |
||||
errorMessage: { |
||||
type: '元分类/模型ID必须是整数', |
||||
minimum: '元分类/模型ID是一个正整数', |
||||
}, |
||||
}, |
||||
}, |
||||
}; |
||||
return makeDTO(data, schema); |
||||
} |
||||
|
||||
export function GetBaseDictListDTO(data) { |
||||
const schema = { |
||||
type: 'object', |
||||
properties: { |
||||
atomModelId: { |
||||
type: ['integer', 'null'], |
||||
minimum: 0, |
||||
errorMessage: { |
||||
type: '元分类/模型ID必须是整数', |
||||
minimum: '元分类/模型ID是一个正整数', |
||||
}, |
||||
}, |
||||
searchData: { |
||||
type: 'string', |
||||
maxLength: 255, |
||||
errorMessage: { |
||||
type: '查询内容必须是一个字符串', |
||||
maxLength: '查询内容长度超出限制255', |
||||
}, |
||||
}, |
||||
}, |
||||
}; |
||||
return makeDTO(data, schema); |
||||
} |
||||
|
||||
|
||||
export function GetBaseDictStructForBaseDictIdDTO(data) { |
||||
const schema = { |
||||
type: 'object', |
||||
properties: { |
||||
baseDictId: { |
||||
type: 'integer', |
||||
minimum: 0, |
||||
errorMessage: { |
||||
type: '字典ID必须是整数', |
||||
minimum: '字典ID是一个正整数', |
||||
}, |
||||
}, |
||||
}, |
||||
required: ['baseDictId'], |
||||
errorMessage: { |
||||
required: { |
||||
baseDictId: '字典ID为必填项', |
||||
}, |
||||
}, |
||||
}; |
||||
return makeDTO(data, schema); |
||||
} |
||||
|
||||
|
||||
|
||||
export function DeleteBaseDictItemDTO(data) { |
||||
const schema = { |
||||
type: 'object', |
||||
properties: { |
||||
baseDictId: { |
||||
type: 'integer', |
||||
minimum: 0, |
||||
errorMessage: { |
||||
type: '字典ID必须是整数', |
||||
minimum: '字典ID是一个正整数', |
||||
}, |
||||
}, |
||||
}, |
||||
required: ['baseDictId'], |
||||
errorMessage: { |
||||
required: { |
||||
baseDictId: '字典ID为必填项', |
||||
}, |
||||
}, |
||||
}; |
||||
return makeDTO(data, schema); |
||||
} |
||||
|
||||
|
||||
|
||||
|
||||
export function CreateBaseDictItemDTO(data) { |
||||
const schema = { |
||||
type: 'object', |
||||
properties: { |
||||
atomModelId: { |
||||
type: ['integer', 'null'], |
||||
minimum: 0, |
||||
errorMessage: { |
||||
type: '元分类/模型ID必须是整数', |
||||
minimum: '元分类/模型ID是一个正整数', |
||||
}, |
||||
}, |
||||
baseDictName:{ |
||||
type: 'string', |
||||
minLength: 1, |
||||
maxLength: 255, |
||||
errorMessage: { |
||||
type: '字典项名称必须是一个字符串', |
||||
maxLength: '字典项名称长度超出限制255', |
||||
minLength: '字典项名称长度过短', |
||||
}, |
||||
}, |
||||
baseDictFather:{ |
||||
type: ['integer', 'null'], |
||||
minimum: 0, |
||||
default: 0, |
||||
errorMessage: { |
||||
type: '字典项父ID必须是整数', |
||||
minimum: '字典项父ID是一个正整数', |
||||
}, |
||||
}, |
||||
baseDictDescribe:{ |
||||
type: 'string', |
||||
minLength: 1, |
||||
maxLength: 2048, |
||||
errorMessage: { |
||||
type: '字典项名称必须是一个字符串', |
||||
maxLength: '字典项名称长度超出限制2048', |
||||
minLength: '字典项名称长度过短', |
||||
}, |
||||
} |
||||
}, |
||||
required: ['baseDictName', 'baseDictDescribe'], |
||||
errorMessage: { |
||||
required: { |
||||
baseDictName: '字典项名称为必填项', |
||||
baseDictDescribe: '字典项描述为必填项' |
||||
}, |
||||
}, |
||||
}; |
||||
return makeDTO(data, schema); |
||||
} |
||||
|
||||
export function EditBaseDictItemDTO(data) { |
||||
const schema = { |
||||
type: 'object', |
||||
properties: { |
||||
baseDictId: { |
||||
type: 'integer', |
||||
minimum: 0, |
||||
errorMessage: { |
||||
type: '字典ID必须是整数', |
||||
minimum: '字典ID是一个正整数', |
||||
}, |
||||
}, |
||||
baseDictName:{ |
||||
type: 'string', |
||||
minLength: 1, |
||||
maxLength: 255, |
||||
errorMessage: { |
||||
type: '字典项名称必须是一个字符串', |
||||
maxLength: '字典项名称长度超出限制255', |
||||
minLength: '字典项名称长度过短', |
||||
}, |
||||
}, |
||||
baseDictDescribe:{ |
||||
type: 'string', |
||||
minLength: 1, |
||||
maxLength: 2048, |
||||
errorMessage: { |
||||
type: '字典项名称必须是一个字符串', |
||||
maxLength: '字典项名称长度超出限制2048', |
||||
minLength: '字典项名称长度过短', |
||||
}, |
||||
} |
||||
}, |
||||
required: ['baseDictName', 'baseDictDescribe', 'baseDictId'], |
||||
errorMessage: { |
||||
required: { |
||||
baseDictName: '字典项名称为必填项', |
||||
baseDictDescribe: '字典项描述为必填项', |
||||
baseDictId: '字典ID为必填项', |
||||
}, |
||||
}, |
||||
}; |
||||
return makeDTO(data, schema); |
||||
} |
@ -0,0 +1,93 @@ |
||||
// | ------------------------------------------------------------
|
||||
// | @版本: version 0.1
|
||||
// | @创建人: 【Nie-x7129】
|
||||
// | @E-mail: x71291@outlook.com
|
||||
// | @所在项目: graphResource2
|
||||
// | @文件描述: index.js -
|
||||
// | @创建时间: 2023-12-02 00:15
|
||||
// | @更新时间: 2023-12-02 00:15
|
||||
// | @修改记录:
|
||||
// | -*-*-*- (时间--修改人--修改说明) -*-*-*-
|
||||
// | =
|
||||
// | ------------------------------------------------------------
|
||||
|
||||
import Router from 'koa-router'; |
||||
import { |
||||
CreateBaseDictItemDTO, |
||||
DeleteBaseDictItemDTO, EditBaseDictItemDTO, |
||||
GetBaseDictListDTO, |
||||
GetBaseDictStructForBaseDictIdDTO, |
||||
GetBaseDictTreeDTO |
||||
} from '#routes/graphResource2/baseDict/index.dto.js'; |
||||
import {DeleteAtomModelItemDTO} from "#routes/graphResource2/atomModel/index.dto.js"; |
||||
|
||||
const baseDict = new Router(); |
||||
|
||||
// @ 获取字典树
|
||||
baseDict.get('/getBaseDictTree', async (ctx, next) => { |
||||
const data = ctx.query; |
||||
const verif = GetBaseDictTreeDTO(data); |
||||
if (!verif.status) { |
||||
ctx.throw(400, { e: verif.error.map((i) => i.message) }); |
||||
return; |
||||
} |
||||
ctx.body = 1 |
||||
}); |
||||
|
||||
// @ 获取字典名列表
|
||||
baseDict.get('/getBaseDictList', async (ctx, next) => { |
||||
const data = ctx.query; |
||||
console.log(data) |
||||
const verif = GetBaseDictListDTO(data); |
||||
if (!verif.status) { |
||||
ctx.throw(400, { e: verif.error.map((i) => i.message) }); |
||||
return; |
||||
} |
||||
ctx.body = 2 |
||||
}); |
||||
|
||||
// @ 通过字典ID获取完整字典结构
|
||||
baseDict.get('/getBaseDictStructForBaseDictId', async (ctx, next) => { |
||||
const data = ctx.query; |
||||
const verif = GetBaseDictStructForBaseDictIdDTO(data); |
||||
if (!verif.status) { |
||||
ctx.throw(400, { e: verif.error.map((i) => i.message) }); |
||||
return; |
||||
} |
||||
ctx.body = 3 |
||||
}); |
||||
|
||||
// @ 删除字典项
|
||||
baseDict.delete('/deleteBaseDictItem', async (ctx, next) => { |
||||
const data = ctx.query; |
||||
const verif = DeleteBaseDictItemDTO(data); |
||||
if (!verif.status) { |
||||
ctx.throw(400, { e: verif.error.map((i) => i.message) }); |
||||
return; |
||||
} |
||||
ctx.body = 4 |
||||
}); |
||||
|
||||
// @ 新建字典项
|
||||
baseDict.post('/createBaseDictItem', async (ctx, next) => { |
||||
const data = ctx.request.body; |
||||
const verif = CreateBaseDictItemDTO(data); |
||||
if (!verif.status) { |
||||
ctx.throw(400, { e: verif.error.map((i) => i.message) }); |
||||
return; |
||||
} |
||||
ctx.body = 5 |
||||
}); |
||||
|
||||
// @ 编辑字典项
|
||||
baseDict.post('/editBaseDictItem', async (ctx, next) => { |
||||
const data = ctx.request.body; |
||||
const verif = EditBaseDictItemDTO(data); |
||||
if (!verif.status) { |
||||
ctx.throw(400, { e: verif.error.map((i) => i.message) }); |
||||
return; |
||||
} |
||||
ctx.body = 6 |
||||
}); |
||||
|
||||
export default baseDict; |
@ -0,0 +1,63 @@ |
||||
// | ------------------------------------------------------------
|
||||
// | @版本: version 0.1
|
||||
// | @创建人: 【Nie-x7129】
|
||||
// | @E-mail: x71291@outlook.com
|
||||
// | @所在项目: graphResource2
|
||||
// | @文件描述: index.js -
|
||||
// | @创建时间: 2023-12-01 17:48
|
||||
// | @更新时间: 2023-12-01 17:48
|
||||
// | @修改记录:
|
||||
// | -*-*-*- (时间--修改人--修改说明) -*-*-*-
|
||||
// | =
|
||||
// | ------------------------------------------------------------
|
||||
|
||||
import Router from 'koa-router'; |
||||
import atomModel from "#routes/graphResource2/atomModel/index.js"; |
||||
import testDTO from "#routes/index.dto.js"; |
||||
import rootRouter from "#routes/index.js"; |
||||
import baseDict from "#routes/graphResource2/baseDict/index.js"; |
||||
|
||||
const graphResource2 = new Router(); |
||||
|
||||
graphResource2.get('/', async (ctx) => { |
||||
const data = testDTO({ |
||||
name: 'hexi', |
||||
age: 32, |
||||
email: 'expressgy', |
||||
}); |
||||
console.log(data); |
||||
ctx.body = 'Hello graphResource2!'; |
||||
}); |
||||
graphResource2.use('/atomModel', atomModel.routes()); |
||||
graphResource2.use('/baseDict', baseDict.routes()); |
||||
|
||||
|
||||
// graphResource2.use(async (ctx, next) => {
|
||||
//
|
||||
// console.log(1)
|
||||
// await next()
|
||||
// console.log(2)
|
||||
// })
|
||||
//
|
||||
// graphResource2.get('/', async ctx => {
|
||||
// ctx.body = 'USER'
|
||||
// })
|
||||
//
|
||||
//
|
||||
// graphResource2.get('/:id', async ctx => {
|
||||
// console.log(ctx.params)
|
||||
// console.log(ctx.query)
|
||||
// ctx.body = 'USER'
|
||||
// })
|
||||
//
|
||||
// graphResource2.post('/:id/create', async ctx => {
|
||||
// console.log(ctx.params)
|
||||
// console.log(ctx.query)
|
||||
// console.log(ctx.request.body)
|
||||
// ctx.body = 'USER'
|
||||
// })
|
||||
|
||||
|
||||
|
||||
|
||||
export default graphResource2 |
@ -0,0 +1,28 @@ |
||||
// | ------------------------------------------------------------
|
||||
// | @版本: version 0.1
|
||||
// | @创建人: 【Nie-x7129】
|
||||
// | @E-mail: x71291@outlook.com
|
||||
// | @所在项目: initkoa
|
||||
// | @文件描述: index.dto.js -
|
||||
// | @创建时间: 2023-11-26 15:10
|
||||
// | @更新时间: 2023-11-26 15:10
|
||||
// | @修改记录:
|
||||
// | -*-*-*- (时间--修改人--修改说明) -*-*-*-
|
||||
// | =
|
||||
// | ------------------------------------------------------------
|
||||
|
||||
import makeDTO from "#common/dto/index.js"; |
||||
|
||||
export default function testDTO(data){ |
||||
const schema = { |
||||
"type": "object", |
||||
"properties": { |
||||
"name": { "type": "string" }, |
||||
"age": { "type": "number" }, |
||||
"email": { "type": "string", |
||||
"pattern": "^\\S+@\\S+\\.\\S+$" } |
||||
}, |
||||
"required": ["name", "age"] |
||||
} |
||||
return makeDTO(data, schema) |
||||
} |
@ -0,0 +1,41 @@ |
||||
// | ------------------------------------------------------------
|
||||
// | @版本: version 0.1
|
||||
// | @创建人: 【Nie-x7129】
|
||||
// | @E-mail: x71291@outlook.com
|
||||
// | @所在项目: initkoa
|
||||
// | @文件描述: index.js -
|
||||
// | @创建时间: 2023-11-26 01:34
|
||||
// | @更新时间: 2023-11-26 01:34
|
||||
// | @修改记录:
|
||||
// | -*-*-*- (时间--修改人--修改说明) -*-*-*-
|
||||
// | =
|
||||
// | ------------------------------------------------------------
|
||||
|
||||
import Router from 'koa-router'; |
||||
|
||||
import graphResource2 from "#routes/graphResource2/index.js"; |
||||
import testDTO from '#routes/index.dto.js'; |
||||
|
||||
// const rootRouter = new Router({
|
||||
// prefix: '/api', // 添加前缀
|
||||
// });
|
||||
|
||||
// const apiRouter = new Router();
|
||||
// apiRouter.get('/', async (ctx) => {
|
||||
// ctx.body = 'Hello /API!';
|
||||
// });
|
||||
// apiRouter.use('/user', userRouter.routes());
|
||||
|
||||
const rootRouter = new Router(); |
||||
rootRouter.get('/', async (ctx) => { |
||||
const data = testDTO({ |
||||
name: 'hexi', |
||||
age: 32, |
||||
email: 'expressgy', |
||||
}); |
||||
console.log(data); |
||||
ctx.body = 'Hello World!'; |
||||
}); |
||||
rootRouter.use('/graphResource2', graphResource2.routes()); |
||||
|
||||
export default rootRouter; |
@ -0,0 +1,82 @@ |
||||
// | ------------------------------------------------------------
|
||||
// | @版本: version 0.1
|
||||
// | @创建人: 【Nie-x7129】
|
||||
// | @E-mail: x71291@outlook.com
|
||||
// | @所在项目: initkoa
|
||||
// | @文件描述: ajvTest.js -
|
||||
// | @创建时间: 2023-11-25 21:59
|
||||
// | @更新时间: 2023-11-25 21:59
|
||||
// | @修改记录:
|
||||
// | -*-*-*- (时间--修改人--修改说明) -*-*-*-
|
||||
// | =
|
||||
// | ------------------------------------------------------------
|
||||
const Ajv = require('ajv'); |
||||
const ajv = new Ajv({ allErrors: true }); |
||||
|
||||
const schema = { |
||||
type: 'object', |
||||
properties: { |
||||
name: { type: 'string' }, |
||||
age: { type: 'integer', minimum: 18 }, |
||||
}, |
||||
required: ['name', 'age'], |
||||
errorMessage: { |
||||
type: '数据应该是一个对象', // 整体 schema 错误消息
|
||||
required: '对象缺少必要属性', // 缺少必要属性错误消息
|
||||
properties: { |
||||
name: '姓名应该是一个字符串', |
||||
age: '年龄应该是一个大于或等于 18 的整数', |
||||
}, |
||||
}, |
||||
}; |
||||
|
||||
const validate = ajv.compile(schema); |
||||
|
||||
const data = { |
||||
name: 123, |
||||
age: 17, |
||||
}; |
||||
|
||||
validate(data); |
||||
if (validate.errors) { |
||||
console.log(validate.errors); // 输出自定义错误消息
|
||||
} |
||||
|
||||
// ================================
|
||||
|
||||
const Ajv = require('ajv'); |
||||
const ajv = new Ajv({ allErrors: true }); |
||||
|
||||
// 添加自定义关键字
|
||||
ajv.addKeyword('isOldEnough', { |
||||
validate: function (schema, data) { |
||||
ajv.errors = [ |
||||
{ |
||||
keyword: 'isOldEnough', |
||||
message: '年龄必须大于18岁', |
||||
params: { keyword: 'isOldEnough' }, |
||||
}, |
||||
]; |
||||
return data >= 18; |
||||
}, |
||||
errors: true, // 使用自定义的错误列表
|
||||
}); |
||||
|
||||
const schema = { |
||||
type: 'object', |
||||
properties: { |
||||
age: { type: 'integer', isOldEnough: true }, |
||||
}, |
||||
required: ['age'], |
||||
}; |
||||
|
||||
const validate = ajv.compile(schema); |
||||
|
||||
const data = { |
||||
age: 17, |
||||
}; |
||||
|
||||
validate(data); |
||||
if (validate.errors) { |
||||
console.log(validate.errors); // 输出自定义错误消息
|
||||
} |
@ -0,0 +1,286 @@ |
||||
`koa-body` 是一个流行的 Koa 请求体解析中间件,支持解析常见的请求体数据类型,包括 JSON 数据、表单数据,以及文件上传。下面是 `koa-body` 的详细配置和使用方式: |
||||
|
||||
## 安装 |
||||
|
||||
使用 npm 安装 `koa-body` 中间件: |
||||
|
||||
``` |
||||
npm install koa-body --save |
||||
``` |
||||
|
||||
## 使用 |
||||
|
||||
要使用 `koa-body` 中间件,只需要在 Koa 应用程序中使用 `app.use` 方法将其注册,然后可以在请求处理程序和中间件中使用 `ctx.request.body` 来访问已解析的请求体数据。 |
||||
|
||||
以下是一个使用 `koa-body` 中间件的示例: |
||||
|
||||
```javascript |
||||
const Koa = require('koa'); |
||||
const koaBody = require('koa-body'); |
||||
|
||||
const app = new Koa(); |
||||
|
||||
// 将 koaBody 中间件注册到应用程序中 |
||||
app.use( |
||||
koaBody({ |
||||
multipart: true, |
||||
formidable: { |
||||
maxFileSize: 100 * 1024 * 1024, |
||||
}, |
||||
}) |
||||
); |
||||
|
||||
// 处理请求 |
||||
app.use((ctx) => { |
||||
// 访问已解析的请求体数据 |
||||
console.log(ctx.request.body); |
||||
ctx.body = 'Hello Koa'; |
||||
}); |
||||
|
||||
// 启动应用程序 |
||||
app.listen(3000, () => { |
||||
console.log('Server started on http://localhost:3000'); |
||||
}); |
||||
``` |
||||
|
||||
在上面的示例中,我们将 `koa-body` 中间件注册到应用程序中,并通过参数对象配置解析器。其中,`multipart` 选项是用于启用文件上传支持的选项,`formidable` 对象包括有关文件上传的配置选项,例如 `maxFileSize`,用于限制文件的大小。 |
||||
|
||||
在请求处理程序中,我们可以使用 `ctx.request.body` 访问已解析的请求体数据。 |
||||
|
||||
## 配置选项 |
||||
|
||||
下面是 `koa-body` 可用的配置选项及其默认值: |
||||
|
||||
- `form`:是否解析 `application/x-www-form-urlencoded` 格式的请求体数据,默认为 `true` |
||||
- `json`:是否解析 `application/json` 格式的请求体数据,默认为 `true` |
||||
- `text`:是否解析 `text/*` 格式的请求体数据,默认为 `true` |
||||
- `encoding`:请求体的编码方式,默认为 `'utf-8'` |
||||
- `xml`:是否解析 `application/xml` 和 `text/xml` 格式的请求体数据,默认为 `false` |
||||
- `jsonLimit`:限制解析 `application/json` 格式请求体数据的大小(以字节为单位),默认为 `1mb` |
||||
- `formLimit`:限制解析 `application/x-www-form-urlencoded` 格式的请求体数据大小(以字节为单位),默认为 `56kb` |
||||
- `textLimit`:限制解析 `text/*` 格式的请求体数据大小(以字节为单位),默认为 `56kb` |
||||
- `xmlLimit`:限制解析 `application/xml` 和 `text/xml` 格式的请求体数据大小(以字节为单位),默认为 `1mb` |
||||
- `multipart`:是否解析 `multipart/*` 格式的请求体数据(用于文件上传),默认为 `false` |
||||
- `multiples`:是否解析多个文件上传,默认为 `false` |
||||
- `onError`:错误处理程序,用于处理请求体解析错误,默认为 `ctx.throw` |
||||
- `includeUnparsed`:是否将未解析的请求体数据存储在 `ctx.request.body` 中,默认为 `false` |
||||
- `textLimit`:限制解析 `text/*` 格式的请求体数据大小(以字节为单位),默认为 `56kb` |
||||
|
||||
## 示例 |
||||
|
||||
### 解析表单数据和 JSON 数据 |
||||
|
||||
以下示例演示如何将 `koa-body` 中间件配置为仅解析表单数据和 JSON 数据: |
||||
|
||||
```javascript |
||||
const Koa = require('koa'); |
||||
const koaBody = require('koa-body'); |
||||
|
||||
const app = new Koa(); |
||||
|
||||
// 仅解析表单数据和 JSON 数据 |
||||
app.use(koaBody({ form: true, json: true })); |
||||
|
||||
app.use((ctx) => { |
||||
console.log(ctx.request.body); |
||||
ctx.body = 'Hello Koa'; |
||||
}); |
||||
|
||||
app.listen(3000, () => { |
||||
console.log('Server started on http://localhost:3000'); |
||||
}); |
||||
``` |
||||
|
||||
在上面的示例中,我们将 `koa-body` 中间件配置为仅解析表单数据和 JSON 数据。我们可以在请求处理程序中使用 `ctx.request.body` 访问已解析的请求体数据。 |
||||
|
||||
### 解析文件上传 |
||||
|
||||
以下示例演示如何使用 `koa-body` 中间件解析文件上传: |
||||
|
||||
```javascript |
||||
const Koa = require('koa'); |
||||
const koaBody = require('koa-body'); |
||||
|
||||
const app = new Koa(); |
||||
|
||||
// 启用文件上传支持 |
||||
app.use( |
||||
koaBody({ |
||||
multipart: true, |
||||
formidable: { |
||||
maxFileSize: 100 * 1024 * 1024, |
||||
}, |
||||
}) |
||||
); |
||||
|
||||
app.use((ctx) => { |
||||
// 文件上传信息存储在 ctx.request.files 中 |
||||
console.log(ctx.request.files); |
||||
ctx.body = 'Hello Koa'; |
||||
}); |
||||
|
||||
app.listen(3000, () => { |
||||
console.log('Server started on http://localhost:3000'); |
||||
}); |
||||
``` |
||||
|
||||
在上面的示例中,我们将 `koa-body` 中间件配置为启用文件上传支持,并使用 `formidable` 对象配置文件上传选项。在请求处理程序中,我们可以使用 `ctx.request.files` 访问文件上传信息。 |
||||
|
||||
### 错误处理 |
||||
|
||||
`koa-body` 中间件的默认错误处理程序是 `ctx.throw`,它会抛出一个 HTTP 400 错误响应。你可以自定义一个错误处理程序来处理请求体解析错误。 |
||||
|
||||
以下示例演示如何自定义错误处理程序: |
||||
|
||||
```javascript |
||||
const Koa = require('koa'); |
||||
const koaBody = require('koa-body'); |
||||
|
||||
const app = new Koa(); |
||||
|
||||
app.use( |
||||
koaBody({ |
||||
onError: (err, ctx) => { |
||||
ctx.throw('Body parse error', 422); |
||||
}, |
||||
}) |
||||
); |
||||
|
||||
app.use((ctx) => { |
||||
console.log(ctx.request.body); |
||||
ctx.body = 'Hello Koa'; |
||||
}); |
||||
|
||||
app.listen(3000, () => { |
||||
console.log('Server started on http://localhost:3000'); |
||||
}); |
||||
``` |
||||
|
||||
在上面的示例中,我们自定义了一个错误处理程序,当发生请求体解析错误时,它会抛出一个 HTTP 422 错误响应。 |
||||
|
||||
## 总结 |
||||
|
||||
`koa-body` 是一个流行的 Koa 请求体解析中间件,它支持解析常见的请求体数据类型,包括 JSON 数据、表单数据,以及文件上传。你可以通过配置选项来自定义解析器的行为,并使用 `ctx.request.body` 和 `ctx.request.files` 在请求处理程序中访问已解析的请求体数据和上传的文件信息。同时,你也可以自定义错误处理程序来处理请求体解析错误。 |
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
一、需求 |
||||
之前使用 koa2 的时候,处理 post 请求使用的是 koa-bodyparser,同时如果是图片上传使用的是 koa-multer。 |
||||
|
||||
这两者的组合没什么问题,不过 koa-multer 和 koa-route(注意不是 koa-router) 存在不兼容的问题。 |
||||
|
||||
这个问题已经在这篇文章中说明了: |
||||
|
||||
使用koa-multer实现文件上传并自定义文件名和目录 |
||||
关于 koa-bodyparser 的使用,见下面文章: |
||||
|
||||
手动实现koa2 body-parser中间件及koa-boayparser的使用 |
||||
但是这两者可以通过 koa-body 代替,并且只是用 koa-body 即可。 |
||||
|
||||
koa-body 主要是下面两个依赖: |
||||
|
||||
"co-body": "^5.1.1", |
||||
"formidable": "^1.1.1" |
||||
具体的实现可以在 github 上查看 : https://github.com/dlau/koa-body |
||||
|
||||
二、koa-body 的基本使用 |
||||
在 koa2 中使用 koa-body,我使用的是全局引入,而不是路由级别的引入,因为考虑到很多地方都有 post 请求或者是文件上传请求,没必要只在路由级别引入。 |
||||
|
||||
1、安装依赖 |
||||
yarn add koa-body |
||||
## npm i koa-body -S |
||||
2、app.js |
||||
省略了 koa 的一些基本代码 |
||||
|
||||
const koaBody = require('koa-body'); |
||||
const app = new koa(); |
||||
app.use(koaBody({ |
||||
multipart:true, // 支持文件上传 |
||||
encoding:'gzip', |
||||
formidable:{ |
||||
uploadDir:path.join(__dirname,'public/upload/'), // 设置文件上传目录 |
||||
keepExtensions: true, // 保持文件的后缀 |
||||
maxFieldsSize:2 * 1024 * 1024, // 文件上传大小 |
||||
onFileBegin:(name,file) => { // 文件上传前的设置 |
||||
// console.log(`name: ${name}`); |
||||
// console.log(file); |
||||
}, |
||||
} |
||||
})); |
||||
3、有用的参数 |
||||
1)koa-body 的基本参数 |
||||
|
||||
参数名 描述 类型 默认值 |
||||
patchNode 将请求体打到原生 node.js 的ctx.req中 Boolean false |
||||
patchKoa 将请求体打到 koa 的 ctx.request 中 Boolean true |
||||
jsonLimit JSON 数据体的大小限制 String / Integer 1mb |
||||
formLimit 限制表单请求体的大小 String / Integer 56kb |
||||
textLimit 限制 text body 的大小 String / Integer 56kb |
||||
encoding 表单的默认编码 String utf-8 |
||||
multipart 是否支持 multipart-formdate 的表单 Boolean false |
||||
urlencoded 是否支持 urlencoded 的表单 Boolean true |
||||
text 是否解析 text/plain 的表单 Boolean true |
||||
json 是否解析 json 请求体 Boolean true |
||||
jsonStrict 是否使用 json 严格模式,true 会只处理数组和对象 Boolean true |
||||
formidable 配置更多的关于 multipart 的选项 Object {} |
||||
onError 错误处理 Function function(){} |
||||
stict 严格模式,启用后不会解析 GET, HEAD, DELETE 请求 Boolean true |
||||
2)formidable 的相关配置参数 |
||||
|
||||
参数名 描述 类型 默认值 |
||||
maxFields 限制字段的数量 Integer 1000 |
||||
maxFieldsSize 限制字段的最大大小 Integer 2 * 1024 * 1024 |
||||
uploadDir 文件上传的文件夹 String os.tmpDir() |
||||
keepExtensions 保留原来的文件后缀 Boolean false |
||||
hash 如果要计算文件的 hash,则可以选择 md5/sha1 String false |
||||
multipart 是否支持多文件上传 Boolean true |
||||
onFileBegin 文件上传前的一些设置操作 Function function(name,file){} |
||||
关于 onFileBegin 的更多信息可以查看: |
||||
|
||||
https://github.com/felixge/node-formidable#filebegin |
||||
4、获取文件上传后的信息 |
||||
这些代码是在路由中体现的 |
||||
|
||||
需要注意的是,如果是获取上传后文件的信息,则需要在 ctx.request.files 中获取。 |
||||
|
||||
如果是获取其他的表单字段,则需要在 ctx.request.body 中获取,这是由 co-body 决定的(默认情况)。 |
||||
|
||||
router.get('/', async (ctx) => { |
||||
await ctx.render('index'); |
||||
}); |
||||
|
||||
router.post('/',async (ctx)=>{ |
||||
console.log(ctx.request.files); |
||||
console.log(ctx.request.body); |
||||
ctx.body = JSON.stringify(ctx.request.files); |
||||
}); |
||||
三、结果 |
||||
|
||||
|
||||
因为默认开启多个文件上传,因此 ctx.request.files 是一个对象, |
||||
|
||||
而且是通过表单的 name=photo 属性作为对象的 key,值便是一个 File 对象,有用的字段如下: |
||||
|
||||
字段名 描述 |
||||
size 文件大小 |
||||
path 文件上传后的目录 |
||||
name 文件的原始名称 |
||||
type 文件类型 |
||||
lastModifiedDate 上次更新的时间 |
||||
|
||||
|
||||
http://www.ptbird.cn/koa-body.html |
||||
———————————————— |
||||
版权声明:本文为CSDN博主「after you」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。 |
||||
原文链接:https://blog.csdn.net/gwdgwd123/article/details/103561817 |
@ -0,0 +1,104 @@ |
||||
|
||||
|
||||
koa-compress 是一个 Koa 中间件,用于压缩 HTTP 响应。使用该中间件可减少 HTTP 响应的大小,从而提升应用程序的性能。 |
||||
|
||||
下面是使用 koa-compress 的简单示例: |
||||
|
||||
```javascript |
||||
const Koa = require('koa'); |
||||
const compress = require('koa-compress'); |
||||
|
||||
const app = new Koa(); |
||||
|
||||
// 注册中间件 |
||||
app.use(compress()); |
||||
|
||||
// 定义路由 |
||||
app.use(async (ctx) => { |
||||
ctx.body = 'Hello, world!'; |
||||
}); |
||||
|
||||
app.listen(3000, () => { |
||||
console.log('Server started on 3000'); |
||||
}); |
||||
``` |
||||
|
||||
在上面的示例中,我们首先通过 `require` 引入了 Koa 和 koa-compress,然后创建了一个 Koa 应用程序实例。 |
||||
|
||||
在注册中间件时,我们使用了 `compress()` 函数来创建 koa-compress 中间件的实例,并将其添加到应用程序中间件栈中。 |
||||
|
||||
最后,我们定义了一个非常简单的路由,在该路由中,我们设置了响应的正文内容为 "Hello, world!"。由于我们已经注册了 koa-compress 中间件,因此响应的内容将被压缩后返回给客户端。 |
||||
|
||||
需要注意的是,koa-compress 的默认配置已经适用于大多数情况。如果需要对其进行个性化配置,请参阅 koa-compress 的文档。 |
||||
|
||||
|
||||
虽然 koa-compress 是一个非常有用的中间件,但它也有一些缺点,包括: |
||||
|
||||
1. CPU 开销:压缩和解压缩数据需要消耗一定的 CPU 资源。对于大量并发请求的应用程序,尤其是在处理大型响应时,这可能会占用大量的 CPU 时间,并可能成为性能瓶颈。 |
||||
|
||||
2. 内存消耗:压缩和解压缩数据可能会占用一定的内存。对于包含大量压缩数据的响应,这可能会导致应用程序的内存占用增加。 |
||||
|
||||
3. 配置复杂性:虽然 koa-compress 的默认配置适用于大多数情况,但某些情况下可能需要进行个性化的配置。配置复杂性可能会增加,特别是在需要针对不同的响应类型或路径进行不同的压缩设置时。 |
||||
|
||||
4. 不适用于动态内容:由于压缩是在响应生成后进行的,因此对于动态内容(如实时数据或流式响应)无法实时压缩。这可能会导致传输过程中的数据量较大,影响网络传输速度。 |
||||
|
||||
总体来说,koa-compress 是一个功能强大的中间件,可以提高应用程序的性能和网络传输效率。然而,在使用它时,需要权衡使用压缩所带来的性能消耗和配置复杂性,以确保最佳的应用程序性能和用户体验。 |
||||
|
||||
koa-compress 提供了一系列的配置选项,可以根据需要进行个性化的配置。下面是常用的一些选项: |
||||
|
||||
- `filter`:指定哪些 HTTP 响应需要被压缩。可以是一个布尔值、字符串、正则表达式或一个自定义函数。默认为压缩所有响应。 |
||||
|
||||
- `threshold`:指定响应正文的大小下限,只有当响应正文大小超过指定值时才会进行压缩。默认为 `1024` 字节。 |
||||
|
||||
- `gzip`:指定是否启用 Gzip 压缩。默认为 `true`。 |
||||
|
||||
- `deflate`:指定是否启用 Deflate 压缩。默认为 `true`。 |
||||
|
||||
- `br`:指定是否启用 Brotli 压缩。默认为 `false`。 |
||||
|
||||
- `chunkSize`:指定压缩块的大小。默认为 `16 * 1024` 字节。 |
||||
|
||||
- `mimeTypes`:指定要压缩的 MIME 类型。默认为 `['text/*']`。 |
||||
|
||||
- `enableTypes`:指定要启用压缩的 MIME 类型。默认为所有 MIME 类型。 |
||||
|
||||
- `skip`:指定一个自定义函数,以跳过指定的请求或响应。默认为 `null`。 |
||||
|
||||
下面是一个配置示例: |
||||
|
||||
```javascript |
||||
const Koa = require('koa'); |
||||
const compress = require('koa-compress'); |
||||
|
||||
const app = new Koa(); |
||||
|
||||
// 注册中间件并进行个性化配置 |
||||
app.use(compress({ |
||||
filter (content_type) { |
||||
return /text/i.test(content_type) |
||||
}, |
||||
threshold: 1024, |
||||
gzip: true, |
||||
deflate: false, |
||||
br: false, |
||||
chunkSize: 16 * 1024, |
||||
mimeTypes: ['text/plain', 'application/json'], |
||||
enableTypes: ['text/plain', 'application/json'], |
||||
skip (ctx) { |
||||
return ctx.path === '/healthcheck'; |
||||
} |
||||
})); |
||||
|
||||
// 定义路由 |
||||
app.use(async (ctx) => { |
||||
ctx.body = 'Hello, world!'; |
||||
}); |
||||
|
||||
app.listen(3000, () => { |
||||
console.log('Server started on 3000'); |
||||
}); |
||||
``` |
||||
|
||||
在上面的示例中,我们使用了一些常见的配置选项。我们指定了只对文本类型的响应进行压缩,并且启用了 Gzip 压缩。我们还指定了要启用的 MIME 类型和要跳过的路径,以及其他一些选项。 |
||||
|
||||
需要注意的是,配置选项可以根据需要进行个性化的调整。可以根据实际情况进行选择。在使用 koa-compress 时,确保在经过测试和评估后再进行个性化的配置。 |
@ -0,0 +1,33 @@ |
||||
要限制同一个客户端的请求数量,可以使用 `koa-ratelimit` 插件。该插件可以按照一定的速率限制客户端的请求数量。以下是使用 `koa-ratelimit` 的示例代码: |
||||
|
||||
```javascript |
||||
const Koa = require('koa'); |
||||
const ratelimit = require('koa-ratelimit'); |
||||
|
||||
const app = new Koa(); |
||||
|
||||
app.use(ratelimit({ |
||||
driver: 'memory', // 存储限流数据的驱动,这里使用内存驱动 |
||||
db: new Map(), // 存储被限制的客户端信息的数据结构 |
||||
duration: 60000, // 时间窗口,单位毫秒 |
||||
max: 10, // 时间窗口内允许的最大请求数量 |
||||
id: ctx => ctx.ip, // 提取每个请求的唯一标识符,默认使用请求的 IP 地址 |
||||
})); |
||||
|
||||
// 添加其他中间件和路由 |
||||
|
||||
app.listen(3000, () => { |
||||
console.log('Server started on http://localhost:3000'); |
||||
}); |
||||
``` |
||||
|
||||
在上述代码中,我们使用 `koa-ratelimit` 插件来限制同一个客户端的请求数量。插件配置中的关键参数如下: |
||||
- `driver`:存储限流数据的驱动,可以选择内存 (`memory`)、Redis (`redis`)、MongoDB (`mongodb`) 等。在示例中我们使用内存驱动。 |
||||
- `db`:存储被限制的客户端信息的数据结构,这里我们使用 `Map`。 |
||||
- `duration`:时间窗口的持续时间,单位为毫秒。 |
||||
- `max`:时间窗口内允许的最大请求数量。 |
||||
- `id`:提取每个请求的唯一标识符,默认使用请求的 IP 地址。 |
||||
|
||||
当某个客户端超过设定的最大请求数量时,该插件会返回 HTTP 状态码 429 Too Many Requests,并且设置 `Retry-After` 头部,表示重新尝试请求的时间。 |
||||
|
||||
通过使用 `koa-ratelimit` 插件,可以有效地限制同一个客户端的请求数量,从而保护服务器免受过多的请求负载。同时,你也可以根据实际需求调整时间窗口和最大请求数量的配置。 |
@ -0,0 +1,46 @@ |
||||
`koa-send` 是一个 Koa 中间件,用于发送文件或目录响应给客户端。它提供了一种简单的方式来处理静态文件的发送。下面是一个使用示例: |
||||
|
||||
```javascript |
||||
const Koa = require('koa'); |
||||
const send = require('koa-send'); |
||||
const app = new Koa(); |
||||
|
||||
app.use(async (ctx, next) => { |
||||
// 使用 koa-send 发送文件 |
||||
await send(ctx, 'path/to/file.txt'); |
||||
}); |
||||
|
||||
app.listen(3000, () => { |
||||
console.log('Server started on 3000'); |
||||
}); |
||||
``` |
||||
|
||||
在上面的示例中,`koa-send` 中间件用于处理所有的请求,并将文件 `path/to/file.txt` 发送给客户端。 |
||||
|
||||
除了发送单个文件外,你还可以发送整个目录: |
||||
|
||||
```javascript |
||||
app.use(async (ctx, next) => { |
||||
// 使用 koa-send 发送目录 |
||||
await send(ctx, 'path/to/directory'); |
||||
}); |
||||
``` |
||||
|
||||
这将发送指定目录下的文件,可以在请求的 URL 中指定特定的文件。 |
||||
|
||||
`koa-send` 还提供了一些选项,用于设置发送文件时的行为。例如,你可以指定根目录、设置缓存控制头、设置内容类型等。以下是一个使用选项的示例: |
||||
|
||||
```javascript |
||||
app.use(async (ctx, next) => { |
||||
await send(ctx, 'path/to/file.txt', { |
||||
root: 'public', // 设置根目录 |
||||
maxage: 1 * 24 * 60 * 60 * 1000, // 设置缓存时间 |
||||
immutable: true, // 设置不可变性(immutable) |
||||
contentType: 'text/plain' // 设置内容类型 |
||||
}); |
||||
}); |
||||
``` |
||||
|
||||
在上面的示例中,我们将根目录设置为 `public`,将缓存时间设置为 1 天,启用不可变性,并设置内容类型为 `text/plain`。 |
||||
|
||||
通过这些选项,你可以对发送的文件进行更细致的控制。更多的选项和详细的使用方式可以查看 `koa-send` 的文档。 |
@ -0,0 +1,39 @@ |
||||
要在 Koa 中修改 HTTP 响应的状态码(code),可以简单地通过 ctx.status 属性进行修改。例如,将响应状态码修改为 404: |
||||
|
||||
```js |
||||
app.use(async (ctx, next) => { |
||||
ctx.status = 404; |
||||
// 继续执行后续中间件,并在之后对响应进行修改 |
||||
await next(); |
||||
}); |
||||
``` |
||||
|
||||
在上述代码中,我们将响应状态码设置为 404,并在之后继续执行后续中间件。这意味着你可以在后续中间件中进一步修改响应内容,比如设置响应体、设置 headers 等。 |
||||
|
||||
如果你想要在响应发送之前中止中间件的执行,可以通过 ctx.throw 方法或在抛出一个 Error 对象,同时设置其 status 或者 statusCode 属性: |
||||
|
||||
```js |
||||
app.use(async (ctx, next) => { |
||||
if (someCondition) { |
||||
ctx.throw(400, 'Bad Request'); |
||||
} else { |
||||
await next(); |
||||
} |
||||
}); |
||||
``` |
||||
|
||||
或者: |
||||
|
||||
```js |
||||
app.use(async (ctx, next) => { |
||||
if (someCondition) { |
||||
const err = new Error('Bad Request'); |
||||
err.status = 400; |
||||
throw err; |
||||
} else { |
||||
await next(); |
||||
} |
||||
}); |
||||
``` |
||||
|
||||
在上述代码中,当 someCondition 符合时,我们通过 ctx.throw 或抛出 Error 对象来中止中间件执行,并将响应状态码设置为 400。 |
Loading…
Reference in new issue