import LRU from 'lru-cache'
import md5 from 'js-md5'
// const VueServerRender = require('vue-server-renderer')
let CACHED = ''
if (!process.browser) {
if (!process.__API__) {
// 給api加3秒緩存
CACHED = new LRU({
max: 1000,
maxAge: 1000 * 20
})
process.__API__ = CACHED
} else {
CACHED = process.__API__
}
}
// 在該中間件中,你甚至可以做渲染攔截,直接send你自定義的數據,非router中間件,全局中間件,像洋蔥一樣
// 先進後出
export default async function (req, res, next) {
res.original_send = res.send
res.original_end = res.end
res.original_json = res.json
res.original_redirect = res.redirect
// console.log(17, myCookie)
let myCookie = req.headers.cookie
let CookieObj = {}
if (myCookie) {
// lang country countryCode currencyCode currencySymbol threshold fare
// userToken userId app HomeCate NewCate TopCateId cookieCoutry
myCookie.split(';').forEach(item => {
if (!item) {
return
}
const arr = item.trim().split('=')
const key = arr[0]
const val = arr[1]
CookieObj[key] = val
})
}
const url = req.headers.referer
// res.redirect(301,'https://www.baidu.com')
// res.status(200).send('<p>12355</p>')
// lang country countryCode currencyCode currencySymbol threshold fare
// userToken userId app HomeCate NewCate TopCateId cookieCoutry
if (url === 'http://localhost:8003/' || url === 'http://localhost:8003/?lang=en') {
// lang country countryCode currencyCode currencySymbol threshold fare
// userToken userId app HomeCate NewCate TopCateId cookieCoutry
let BaseParams = {
lang: CookieObj['lang'] || '',
country: CookieObj['country'] || '',
countryCode: CookieObj['countryCode'] || '',
currencyCode: CookieObj['currencyCode'] || '',
currencySymbol: CookieObj['currencySymbol'] || '',
cookieCoutry: CookieObj['cookieCoutry'] || '',
threshold: CookieObj['threshold'] || '',
fare: CookieObj['fare'] || ''
// NewCate: CookieObj['NewCate'] || '', // 新品
// TopCateId: CookieObj['TopCateId'] || '', // activity top
}
let VBaseParams = Object.values(BaseParams)
if (!VBaseParams.includes('')) {
let ChangeParams = {
app: CookieObj['app'] || '',
HomeCate: CookieObj['HomeCate'] || ''
}
let Qs = require('qs')
let key = md5(url + Qs.stringify({ ...BaseParams, ...ChangeParams })) // 這裏的key不正確
if (CACHED.has(key)) {
// 緩存命中
console.log('page緩存命中', url)
// let cacheHtml = CACHED.get(key) || '<html><body><h1>Hello, World!</h1></body></html>'
// // console.log('page緩存命中', cacheHtml)
// // res.end(cacheHtml)
// res.end(cacheHtml, 'utf-8')
// console.log('返回page緩存', '<html><body><h1>Hello, World!</h1></body></html>')
const value = CACHED.get(key)
if (value) {
// returns the value immediately
if (value.isJson) {
res.json(value.body)
} else {
res.end(value.body)
}
return
}
return
} else { // 沒有緩存
console.log('page沒有設置緩存', url)
req.HibobiCacheKey = key
// CACHED.set(key, res)
let data = res.data
const body = data instanceof Buffer ? data.toString() : data
CACHED.set(key, { body: body })
// next()
return
}
} else {
next()
return
}
} else { // 直接跳過
next()
}
console.log(84)
}
nuxt緩存
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.