@netlify/content-engine
Version:
63 lines • 3.04 kB
JavaScript
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.makeLedgerFilePath = makeLedgerFilePath;
exports.getIdFromLedgerFilePath = getIdFromLedgerFilePath;
exports.parseStringHeader = parseStringHeader;
exports.makeLedgerWriteHandler = makeLedgerWriteHandler;
const stream_1 = __importDefault(require("stream"));
const path_1 = __importDefault(require("path"));
const util_1 = __importDefault(require("util"));
const pipeline = util_1.default.promisify(stream_1.default.pipeline);
const filePrefix = `block-id-`;
const fileSuffix = `.jsonl.gzip`;
// NOTE: this path differs from what we use in production because the code in this directory isn't used in prod (yet)
// in prod the prefixes like "ledger-id-" aren't there
function makeLedgerFilePath(details) {
return `/ledger-id-${details.ledgerId}/configuration-id-${details.configurationId}/cache-id-${details.cacheId}/${`blockId` in details && details.blockId ? `${filePrefix}${details.blockId}${fileSuffix}` : ``}`;
}
function getIdFromLedgerFilePath(filePath) {
const fileName = path_1.default.basename(filePath);
if (!fileName.startsWith(filePrefix) || !fileName.endsWith(fileSuffix)) {
throw new Error(`Attempted to get ledger id from ${filePath} but this is not a valid ledger block path.`);
}
return fileName.substring(filePrefix.length, fileName.length - fileSuffix.length);
}
function parseStringHeader(headers, names) {
const headersToAccept = Array.isArray(names) ? names : [names];
for (const name of headersToAccept) {
const value = headers[name];
if (typeof value === `string`) {
return value;
}
}
throw new Error(`Header ${headersToAccept.join(", ")} must be a string but isn't.`);
}
// Takes in a function that receives ledger details (various ID's) and that returns a Writable stream.
// This stream can be anything (think AWS bucket, GCP bucket, FS, etc) see ./adapters/fs or ./adapters/gcp for examples
function makeLedgerWriteHandler({ getWritableStream, }) {
return async (req, res) => {
const ledgerId = parseStringHeader(req.headers, `x-ledger-id`) || req.params.ledgerId;
const configurationId = parseStringHeader(req.headers, `x-configuration-id`) ||
req.params.configurationId;
const cacheId = parseStringHeader(req.headers, `x-cache-id`) || req.params.cacheId;
const blockId = parseStringHeader(req.headers, `x-block-id`) || req.params.blockId;
const writeStream = await getWritableStream({
ledgerId,
configurationId,
cacheId,
blockId,
});
try {
await pipeline(req, writeStream);
return res.sendStatus(200);
}
catch (e) {
console.error(e);
return res.sendStatus(500);
}
};
}
//# sourceMappingURL=base-handler.js.map
;