Fastify Caching 插件使用教程
1. 项目的目录结构及介绍
Fastify Caching 插件的目录结构相对简单,主要包含以下文件和目录:
fastify-caching/
├── index.js
├── LICENSE
├── package.json
└── README.md
index.js
: 插件的主文件,包含了插件的主要逻辑。LICENSE
: 项目的许可证文件。package.json
: 项目的配置文件,包含了项目的依赖、脚本等信息。README.md
: 项目的说明文档,包含了插件的基本使用方法和示例。
2. 项目的启动文件介绍
Fastify Caching 插件的启动文件是 index.js
。该文件主要负责注册和配置插件,具体内容如下:
'use strict'
const fastifyPlugin = require('fastify-plugin')
const LRU = require('lru-cache')
function fastifyCaching (fastify, options, next) {
const { privacy, expiresIn, cache, name } = options
if (cache && !(cache instanceof LRU)) {
return next(new Error('cache must be an instance of lru-cache'))
}
const store = cache || new LRU({
maxAge: expiresIn
})
fastify.addHook('onRequest', async (request, reply) => {
reply.header('Cache-Control', `private, max-age=${expiresIn}`)
})
fastify.addHook('onSend', async (request, reply, payload) => {
if (reply.getHeader('Cache-Control') !== 'no-cache') {
store.set(request.url, payload)
}
})
fastify.addHook('onRequest', async (request, reply) => {
const cached = store.get(request.url)
if (cached) {
reply.header('X-Cache', 'HIT')
reply.send(cached)
}
})
next()
}
module.exports = fastifyPlugin(fastifyCaching, {
fastify: '>=3.0.0',
name: 'fastify-caching'
})
该文件主要做了以下几件事:
- 解析插件的配置选项。
- 初始化缓存存储(使用
lru-cache
)。 - 添加请求处理钩子,处理缓存的读取和写入。
3. 项目的配置文件介绍
Fastify Caching 插件的配置文件是 package.json
。该文件包含了项目的依赖、脚本等信息,具体内容如下:
{
"name": "fastify-caching",
"version": "7.0.0",
"description": "A plugin for Fastify to enable HTTP caching",
"main": "index.js",
"scripts": {
"test": "tap test/*.test.js",
"lint": "standard --fix"
},
"repository": {
"type": "git",
"url": "git+https://github.com/fastify/fastify-caching.git"
},
"keywords": [
"fastify",
"caching",
"http",
"cache"
],
"author": "Fastify Team",
"license": "MIT",
"bugs": {
"url": "https://github.com/fastify/fastify-caching/issues"
},
"homepage": "https://github.com/fastify/fastify-caching#readme",
"dependencies": {
"fastify-plugin": "^3.0.0",
"lru-cache": "^6.0.0"
},
"devDependencies": {
"fastify": "^3.0.0",
"standard": "^16.0.0",
"tap": "^15.0.0"
}
}
该文件主要包含以下信息:
name
: 项目的名称。version
: 项目的版本号。description
: 项目的描述。main
: 项目的入口文件。scripts
: 项目的脚本命令