42 lines
1.1 KiB
TypeScript
Raw Normal View History

2024-11-14 19:47:12 +01:00
import { Document } from "../../../controllers/v1/types";
import { Meta } from "..";
import { CacheEntry, cacheKey, saveEntryToCache } from "../../../lib/cache";
export function saveToCache(meta: Meta, document: Document): Document {
2025-01-03 22:55:38 -03:00
if (meta.internalOptions.useCache !== true) {
return document;
}
2024-12-11 19:46:11 -03:00
if (
document.metadata.statusCode! < 200 ||
document.metadata.statusCode! >= 300
)
return document;
2024-12-11 19:46:11 -03:00
if (document.rawHtml === undefined) {
throw new Error(
2024-12-11 19:51:08 -03:00
"rawHtml is undefined -- this transformer is being called out of order",
2024-12-11 19:46:11 -03:00
);
}
2024-11-14 19:47:12 +01:00
2025-01-03 23:07:15 -03:00
// If the document was retrieved from cache, we don't need to save it
if (meta.internalOptions.fromCache) {
return document;
}
2024-12-11 19:46:11 -03:00
const key = cacheKey(meta.url, meta.options, meta.internalOptions);
2024-11-14 19:47:12 +01:00
2024-12-11 19:46:11 -03:00
if (key !== null) {
const entry: CacheEntry = {
html: document.rawHtml!,
statusCode: document.metadata.statusCode!,
url: document.metadata.url ?? document.metadata.sourceURL!,
2024-12-11 19:51:08 -03:00
error: document.metadata.error ?? undefined,
2024-12-11 19:46:11 -03:00
};
2024-11-14 19:47:12 +01:00
2024-12-11 19:46:11 -03:00
saveEntryToCache(key, entry);
}
2024-11-14 19:47:12 +01:00
2024-12-11 19:46:11 -03:00
return document;
}