expressgy 10 months ago
commit f6a969a2b8
  1. 65
      .eslintrc.cjs
  2. 131
      .gitignore
  3. 5
      .idea/.gitignore
  4. 12
      .idea/initkoa.iml
  5. 8
      .idea/modules.xml
  6. 6
      .idea/prettier.xml
  7. 6
      .idea/vcs.xml
  8. 5
      .prettierrc.json
  9. 83
      bootstrap.js
  10. 22
      development.env.js
  11. 48
      package.json
  12. 2106
      pnpm-lock.yaml
  13. 33
      production.env.js
  14. 102
      src/app.js
  15. 28
      src/common/dto/index.js
  16. 89
      src/common/logger/index.js
  17. 28
      src/routes/index.dto.js
  18. 41
      src/routes/index.js
  19. 46
      src/routes/user/index.js
  20. 82
      test/ajvTest.js
  21. 286
      test/koa-body使用.md
  22. 104
      test/koa-compress说明.md
  23. 33
      test/koa-ratelimit限制批量请求工具的应用.md
  24. 46
      test/koa-send方法.md
  25. 39
      test/koa修改code.md
  26. 15
      winston-logs/.531a9d869ad78817b294bb10538cf39c768c399c-audit.json
  27. 15
      winston-logs/.73ddc5c05eabfb2fbd34531dacb4b30796a6a127-audit.json

@ -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
}
}

131
.gitignore vendored

@ -0,0 +1,131 @@
# ---> Node
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
lerna-debug.log*
.pnpm-debug.log*
# 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.*

5
.idea/.gitignore vendored

@ -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/initkoa.iml" filepath="$PROJECT_DIR$/.idea/initkoa.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="MANUAL" />
</component>
</project>

@ -0,0 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="VcsDirectoryMappings">
<mapping directory="" vcs="Git" />
</component>
</project>

@ -0,0 +1,5 @@
{
"singleQuote": true,
"trailingComma": "all",
"tabWidth": 4
}

83
bootstrap.js vendored

@ -0,0 +1,83 @@
// | ------------------------------------------------------------
// | @版本: 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";
// | 获取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;
} 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');
try {
const app = startApp();
app.listen(global.config.port);
console.log(
`Web服务 ${global.config.appName} 启动成功,访问: http://127.0.0.1:${global.config.port}`,
);
logger.info( `Web服务 ${global.config.appName} 启动成功,访问: http://127.0.0.1:${global.config.port}`)
} catch (e) {
console.error(e);
throw new Error(`Web服务启动失败`);
}

@ -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,48 @@
{
"name": "initkoa",
"version": "1.0.0",
"description": "",
"type": "module",
"main": "app.js",
"imports": {
"#root/*": "./*",
"#home/*": "./src/*",
"#routes/*": "./src/routes/*",
"#common/*": "./src/common/*",
"#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 bootstrap.js"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"ajv": "^8.12.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",
"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"
}
}

File diff suppressed because it is too large Load Diff

@ -0,0 +1,33 @@
// | ------------------------------------------------------------
// | @版本: 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: 'koa web application',
port: 3000,
zip: true,
upfile:{
maxFileSize: 200 * 1024 * 1024,
hashAlgorithm: false, // md5 sha1 sha256 sha512
},
request:{
maxFieldsSize: 2 * 1024 * 1024,// 请求体大小
},
ratelimit:{
status: true,
duration: 60 * 1000,
max: 100,
},
}
export default prodConfig

@ -0,0 +1,102 @@
// | ------------------------------------------------------------
// | @版本: 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) => {
// 返回错误的格式
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;
},
}),
);
if (global.zip === true) {
// | koa-compress 是一个 Koa 中间件,用于压缩 HTTP 响应。使用该中间件可减少 HTTP 响应的大小,从而提升应用程序的性能。
app.use(compress());
}
app.use(userAgent);
app.use(
koaBody({
multipart: 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(async (ctx, next) => {
// // console.log(ctx.request.files.file)
// // console.log(ctx.request.body)
// // console.log(ctx.userAgent)
// console.log(ctx.ip);
// ctx.throw(520, '欣赏欣赏');
// ctx.body = 'xs';
// });
app.use(rootRouter.routes());
app.use(rootRouter.allowedMethods());
// console.log(rootRouter)
// const routes = rootRouter.stack.map((route) => route.path);
return app;
}

@ -0,0 +1,28 @@
// | ------------------------------------------------------------
// | @版本: 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'
export default function makeDTO(data, schema){
const ajv = new 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,89 @@
// | ------------------------------------------------------------
// | @版本: 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.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,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 userRouter from '#home/routes/user/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('/api', apiRouter.routes());
export default rootRouter;

@ -0,0 +1,46 @@
// | ------------------------------------------------------------
// | @版本: version 0.1
// | @创建人: 【Nie-x7129】
// | @E-mail: x71291@outlook.com
// | @所在项目: initkoa
// | @文件描述: index.js -
// | @创建时间: 2023-11-26 01:42
// | @更新时间: 2023-11-26 01:42
// | @修改记录:
// | -*-*-*- (时间--修改人--修改说明) -*-*-*-
// | =
// | ------------------------------------------------------------
import Router from 'koa-router'
const userRouter = new Router();
userRouter.use(async (ctx, next) => {
console.log(1)
await next()
console.log(2)
})
userRouter.get('/', async ctx => {
ctx.body = 'USER'
})
userRouter.get('/:id', async ctx => {
console.log(ctx.params)
console.log(ctx.query)
ctx.body = 'USER'
})
userRouter.post('/:id/create', async ctx => {
console.log(ctx.params)
console.log(ctx.query)
console.log(ctx.request.body)
ctx.body = 'USER'
})
export default userRouter

@ -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。

@ -0,0 +1,15 @@
{
"keep": {
"days": true,
"amount": 365
},
"auditLog": "winston-logs\\.531a9d869ad78817b294bb10538cf39c768c399c-audit.json",
"files": [
{
"date": 1700982032692,
"name": "winston-logs\\2023-11-26-ERROR-winston.log",
"hash": "e5fced60631fffc215a2e3dff7375927cce2c3a08733d5248fcd62d38605d9cf"
}
],
"hashType": "sha256"
}

@ -0,0 +1,15 @@
{
"keep": {
"days": true,
"amount": 30
},
"auditLog": "winston-logs\\.73ddc5c05eabfb2fbd34531dacb4b30796a6a127-audit.json",
"files": [
{
"date": 1700982032690,
"name": "winston-logs\\2023-11-26-INFO--winston.log",
"hash": "cadad92fc4e02daa16a74f3393477d1660712c56e24b993c976cc386da130469"
}
],
"hashType": "sha256"
}
Loading…
Cancel
Save