next/lib/server/storyHelpers/bodyHandler.ts

41 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 "~/lib/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();
if (ext === ".md" || ext === ".markdown")
str = marked.parse(
readFileSync(resolve(`tmp/${bodyObj.file}`)).toString(),
);
else if (ext === ".doc" || ext === ".docx")
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);
}