Files
RSSHub/lib/middleware/cache/index.js
T
Tony 6d901cb7dc style(eslint): add eslint-unicorn (#14257)
* style: add eslint-unicorn

* style: fix unicorn/no-useless-spread

* style: fix unicorn/no-useless-promise-resolve-reject

* style: fix unicorn/no-for-loop

* fix: codeql bad HTML filtering regexp

* fix: codeql incomplete replace

* fix: unicorn/no-abusive-eslint-disable

* style: fix unicorn/no-new-array

* style: fix unicorn/no-typeof-undefined

* style: fix unicorn/no-zero-fractions

* style: fix unicorn/no-empty-file

* style: fix unicorn/prefer-date-now

* revert: auto fix unicorn/prefer-switch on lib/v2/kuaidi100/utils.js

* style: fix unicorn/prefer-array-find

* style: fix unicorn/prefer-array-flat

* style: fix unicorn/prefer-array-flat-map

* style: fix unicorn/prefer-at

* style: fix unicorn/prefer-string-starts-ends-with

* style: fix unicorn/prefer-includes

* fix: codeql URL substring sanitization

* style: fix unicorn/prefer-optional-catch-binding

* style: fix unicorn/catch-error-name

* style: fix unicorn/escape-case

* style: fix unicorn/prefer-native-coercion-functions

* style: fix unicorn/prefer-regexp-test

* style: fix unicorn/require-array-join-separator

* style: fix unicorn/prefer-math-trunc

* style: fix unicorn/prefer-negative-index

* style: fix unicorn/prefer-dom-node-dataset

* style: fix unicorn/prefer-dom-node-text-content

* style: fix unicorn/prefer-query-selector

* style: fix unicorn/no-array-for-each

* style: fix unicorn/no-negated-condition

* style: fix unicorn/prefer-add-event-listener

* style: fix unicorn/import-style

* style: fix prefer-regex-literals

* style: disable unicorn/no-useless-switch-case

* style: disable unicorn/text-encoding-identifier-case

* style: fix unicorn/prefer-set-has

* style: fix unicorn/prefer-spread

* revert: auto fix on lib/routes/universities/ynnu/edu/base64.js

* style: fix unicorn/no-useless-undefined

* style: fix unicorn/no-array-push-push

* style: fix unicorn/no-useless-undefined again

* style: fix unicorn/no-lonely-if

* style: fix unicorn/prefer-reflect-apply

* style: fix unicorn/switch-case-braces

* style: fix unicorn/prefer-switch

* style: fix unicorn/prefer-array-some

* fix: deepscan UNUSED_VAR_ASSIGN

* style: fix unicorn/prefer-ternary

* fix: follow-up of unicorn/prefer-ternary

* revert: auto fix of unicorn/prefer-string-slice for substring()

* style: disable unicorn/prefer-string-slice

fix: auto fix slice over deprecated substr

* style: fix unicorn/throw-new-error

* style: fix unicorn/filename-case

* test: fix dateParser renaming

* style: fix unicorn/better-regex

* style: fix unicorn/prefer-string-replace-all

* fix(deps): add sanitize-html

* style: fix no-prototype-builtins

* style: fix unicorn/consistent-destructuring

* style: fix unicorn/consistent-function-scoping

* style: fix unicorn/prefer-regexp-test

* style: fix unicorn/prefer-logical-operator-over-ternary

* style: fix unicorn/no-array-callback-reference

* style: add prefer-object-has-own

* style: warn unicorn/no-empty-file

* style: fix unicorn/prefer-number-properties

* style: fix no-useless-undefined again

* style: fix unicorn/numeric-separators-style

* style: disable unicorn/no-array-callback-reference

false postive with cheerio
2024-01-18 20:43:40 +08:00

140 lines
4.4 KiB
JavaScript

const xxhash = require('xxhash-wasm');
const config = require('@/config').value;
const logger = require('@/utils/logger');
const { RequestInProgressError } = require('@/errors');
const globalCache = {
get: () => null,
set: () => null,
};
let cacheModule = {
get: () => null,
set: () => null,
status: { available: false },
clients: {},
};
if (config.cache.type === 'redis') {
cacheModule = require('./redis');
const { redisClient } = cacheModule.clients;
globalCache.get = async (key) => {
if (key && cacheModule.status.available) {
const value = await redisClient.get(key);
return value;
}
};
globalCache.set = cacheModule.set;
} else if (config.cache.type === 'memory') {
cacheModule = require('./memory');
const { memoryCache } = cacheModule.clients;
globalCache.get = (key) => {
if (key && cacheModule.status.available) {
return memoryCache.get(key, { updateAgeOnGet: false });
}
};
globalCache.set = (key, value, maxAge) => {
if (!value || value === 'undefined') {
value = '';
}
if (typeof value === 'object') {
value = JSON.stringify(value);
}
if (key) {
return memoryCache.set(key, value, { ttl: maxAge * 1000 });
}
};
} else {
logger.error('Cache not available, concurrent requests are not limited. This could lead to bad behavior.');
}
// only give cache string, as the `!` condition tricky
// md5 is used to shrink key size
// plz, write these tips in comments!
module.exports = function (app) {
const { get, set, status } = cacheModule;
app.context.cache = {
...cacheModule,
tryGet: async (key, getValueFunc, maxAge = config.cache.contentExpire, refresh = true) => {
if (typeof key !== 'string') {
throw new TypeError('Cache key must be a string');
}
let v = await get(key, refresh);
if (v) {
let parsed;
try {
parsed = JSON.parse(v);
} catch {
parsed = null;
}
if (parsed) {
v = parsed;
}
} else {
v = await getValueFunc();
set(key, v, maxAge);
}
return v;
},
globalCache,
};
return async (ctx, next) => {
const { h64ToString } = await xxhash();
const key = 'rsshub:koa-redis-cache:' + h64ToString(ctx.request.path);
const controlKey = 'rsshub:path-requested:' + h64ToString(ctx.request.path);
if (!status.available) {
return next();
}
const isRequesting = await globalCache.get(controlKey);
if (isRequesting === '1') {
throw new RequestInProgressError('This path is currently fetching, please come back later!');
}
try {
const value = await globalCache.get(key);
if (value) {
ctx.response.status = 200;
if (config.cache.type === 'redis') {
ctx.response.set({
'X-Koa-Redis-Cache': 'true',
});
} else if (config.cache.type === 'memory') {
ctx.response.set({
'X-Koa-Memory-Cache': 'true',
});
}
ctx.state.data = JSON.parse(value);
return;
}
} catch {
//
}
// Doesn't hit the cache? We need to let others know!
await globalCache.set(controlKey, '1', config.cache.requestTimeout);
try {
await next();
} catch (error) {
await globalCache.set(controlKey, '0', config.cache.requestTimeout);
throw error;
}
if (ctx.response.get('Cache-Control') !== 'no-cache' && ctx.state && ctx.state.data) {
ctx.state.data.lastBuildDate = new Date().toUTCString();
const body = JSON.stringify(ctx.state.data);
await globalCache.set(key, body, config.cache.routeExpire);
}
// We need to let it go, even no cache set.
// Wait to set cache so the next request could be handled correctly
await globalCache.set(controlKey, '0', config.cache.requestTimeout);
};
};