Merge branch 'add-caching-support' into lru-eviction
This commit is contained in:
commit
9fd54d8f4a
|
@ -14,6 +14,7 @@ import {
|
||||||
rmdir,
|
rmdir,
|
||||||
} from 'promise-fs';
|
} from 'promise-fs';
|
||||||
import getFolderSize from 'get-folder-size';
|
import getFolderSize from 'get-folder-size';
|
||||||
|
import crypto from 'crypto';
|
||||||
|
|
||||||
interface LeastRecentlyUsedResult {
|
interface LeastRecentlyUsedResult {
|
||||||
atime: Date;
|
atime: Date;
|
||||||
|
@ -41,7 +42,7 @@ class DiskCache {
|
||||||
constructor(private cacheBucketDir: string) {}
|
constructor(private cacheBucketDir: string) {}
|
||||||
|
|
||||||
async put(cacheKey: string, response: Response): Promise<void> {
|
async put(cacheKey: string, response: Response): Promise<void> {
|
||||||
const cachePath = path.join(this.cacheBucketDir, cacheKey);
|
const cachePath = makeAssetCachePath(this.cacheBucketDir, cacheKey);
|
||||||
evictLeastRecentlyUsed(this.cacheBucketDir, MAX_CACHE_SIZE);
|
evictLeastRecentlyUsed(this.cacheBucketDir, MAX_CACHE_SIZE);
|
||||||
await writeFile(
|
await writeFile(
|
||||||
cachePath,
|
cachePath,
|
||||||
|
@ -50,7 +51,7 @@ class DiskCache {
|
||||||
}
|
}
|
||||||
|
|
||||||
async match(cacheKey: string): Promise<Response> {
|
async match(cacheKey: string): Promise<Response> {
|
||||||
const cachePath = path.join(this.cacheBucketDir, cacheKey);
|
const cachePath = makeAssetCachePath(this.cacheBucketDir, cacheKey);
|
||||||
if (existsSync(cachePath)) {
|
if (existsSync(cachePath)) {
|
||||||
touch(cachePath);
|
touch(cachePath);
|
||||||
return new Response(await readFile(cachePath));
|
return new Response(await readFile(cachePath));
|
||||||
|
@ -60,6 +61,15 @@ class DiskCache {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function makeAssetCachePath(cacheDir: string, cacheKey: string) {
|
||||||
|
// hashing the key to prevent illegal filenames
|
||||||
|
const cacheKeyHash = crypto
|
||||||
|
.createHash('sha256')
|
||||||
|
.update(cacheKey)
|
||||||
|
.digest('hex');
|
||||||
|
return path.join(cacheDir, cacheKeyHash);
|
||||||
|
}
|
||||||
|
|
||||||
async function touch(path: string) {
|
async function touch(path: string) {
|
||||||
const time = new Date();
|
const time = new Date();
|
||||||
try {
|
try {
|
||||||
|
|
Loading…
Reference in a new issue