next/lib/server/storyHelpers/bodyHandler.ts

33 lines
1.1 KiB
TypeScript
Raw Normal View History

import { extname, resolve } from "path";
import { readFileSync } from "fs";
import { marked } from "marked";
import mammoth from "mammoth";
import san from "sanitize-html";
import { sanitizeConf } from "../constants";
import { FormChapter } from "@client/types/form/story";
import { log } from "../logger";
export default async function (bodyObj: FormChapter): Promise<string> {
let str: string = "";
log.debug(JSON.stringify(bodyObj), { label: "bodyhandler" });
if (bodyObj.content) {
str = bodyObj.content;
} else if (bodyObj.file) {
let ext = extname(bodyObj.file).toLowerCase();
2023-12-29 20:53:29 -05:00
if (ext === ".md" || ext === ".markdown") str = marked.parse(readFileSync(resolve(`tmp/${bodyObj.file}`)).toString());
else if (ext === ".doc" || ext === ".docx")
2023-12-29 20:53:29 -05:00
str = (await mammoth.convertToHtml({ path: resolve(`tmp/${bodyObj.file}`) }, { styleMap: ["b => b", "i => i", "u => u"] })).value;
else
throw createError({
statusCode: 400,
message: "bad file type",
});
} else {
throw createError({
statusCode: 400,
message: "no content",
});
}
return san(str, sanitizeConf);
}