From 983a7e3bdd5c67c9542e6c7da05122a42de7fcf2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E2=98=99=E2=97=A6=20The=20Tablet=20=E2=9D=80=20GamerGirla?= =?UTF-8?q?ndCo=20=E2=97=A6=E2=9D=A7?= Date: Mon, 2 Oct 2023 15:55:38 -0400 Subject: [PATCH] refactor: add utility functions --- lib/functions.ts | 51 ++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 51 insertions(+) create mode 100644 lib/functions.ts diff --git a/lib/functions.ts b/lib/functions.ts new file mode 100644 index 0000000..42f436a --- /dev/null +++ b/lib/functions.ts @@ -0,0 +1,51 @@ +import { readFileSync } from "fs"; +import { resolve } from "path"; +// import chardet from "chardet"; +// import iconv from "iconv-lite"; +import { GridFSBucketReadStream } from "mongodb"; +import { stripHtml } from "string-strip-html"; +import { IStory } from "~/models/stories"; +import { ficsHidden } from "./server/ficmas"; + +// const { encode, decode } = iconv; + +export function countWords(string: string) { + return stripHtml(string).result.split(/W+/).length; +} + +export function populate(field: string) { + return function (next: () => any) { + this.populate(field); + next(); + }; +} +export function populateSelected(field: string, selection: string) { + return function (next: () => any) { + this.populate(field, selection); + next(); + }; +} + +export function isFicmasHidden(story: IStory): boolean { + return ( + (story.ficmas.year == new Date().getFullYear() && + story.ficmas.anniversary && + new Date() < new Date(Date.parse("Aug 1 " + new Date().getFullYear()))) || + (story.ficmas.year == new Date().getFullYear() && + !story.ficmas.anniversary && + ficsHidden(Date.now())) + ); +} + +export function stringifyStream( + stream: GridFSBucketReadStream, +): Promise { + let chunks: Buffer[] = []; + return new Promise((res, rej) => { + stream.on("data", (c) => chunks.push(Buffer.from(c))); + stream.on("error", (err) => { + rej(err); + }); + stream.on("end", () => res(Buffer.concat(chunks).toString("utf-8"))); + }); +}