diff --git a/server/src/lib/cdn/cdn.ts b/server/src/lib/cdn/cdn.ts new file mode 100644 index 000000000..e5b24e67f --- /dev/null +++ b/server/src/lib/cdn/cdn.ts @@ -0,0 +1,40 @@ +import fs from "fs"; +import path from "path"; +import { KTCDN_ROOT } from "../env/env"; +import CreateLogCtx from "../logger/logger"; +import { promisify } from "util"; + +const readFilePromise = promisify(fs.readFile); +const writeFilePromise = promisify(fs.writeFile); + +const logger = CreateLogCtx(__filename); + +/** + * Joins a file location against the location of the CDN static store. + */ +function CDNRoot(fileLoc: string) { + return path.join(KTCDN_ROOT, fileLoc); +} + +/** + * Retrieves the data of the file at the given CDN location. + */ +export function Retrieve(fileLoc: string) { + logger.debug(`Retrieving path ${fileLoc}.`); + + return readFilePromise(CDNRoot(fileLoc)); +} + +/** + * Flag for fs.open to write a file but NOT overwrite it if it already exists. + */ +const WRITE_NO_OVERWRITE = "wx"; + +/** + * Stores the provided buffer or string as a file at the given location. + */ +export function Store(fileLoc: string, data: Buffer | string) { + logger.debug(`Storing path ${fileLoc}.`); + + return writeFilePromise(CDNRoot(fileLoc), data, { flag: WRITE_NO_OVERWRITE }); +} diff --git a/server/src/lib/env/env.ts b/server/src/lib/env/env.ts index a7324ced0..e6e77cb6c 100644 --- a/server/src/lib/env/env.ts +++ b/server/src/lib/env/env.ts @@ -11,6 +11,7 @@ const envVars = [ "KTBSV_EAG_API_URL", "KTBSV_ARC_API_URL", "KTBSV_ARC_AUTH_TOKEN", + "KTCDN_ROOT", ]; for (const eVar of envVars) { @@ -27,3 +28,4 @@ export const FLO_API_URL = process.env.KTBSV_FLO_API_URL!; export const EAG_API_URL = process.env.KTBSV_EAG_API_URL!; export const ARC_API_URL = process.env.KTBSV_ARC_API_URL!; export const ARC_AUTH_TOKEN = process.env.KTBSV_ARC_AUTH_TOKEN!; +export const KTCDN_ROOT = process.env.KTCDN_ROOT!;