next/lib/functions.ts

69 lines
1.9 KiB
TypeScript
Raw Normal View History

2023-10-02 15:55:38 -04:00
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";
import { PreMiddlewareFunction, Query } from "mongoose";
import { IFicmas } from "@models/challenges/ficmas";
2023-10-02 15:55:38 -04:00
// const { encode, decode } = iconv;
export function countWords(string: string) {
return stripHtml(string).result.split(/W+/).length;
}
export function populate<T>(
field: string,
model: string,
): PreMiddlewareFunction<Query<T, T>> {
2023-10-02 15:55:38 -04:00
return function (next: () => any) {
this.populate(field, undefined, model);
2023-10-02 15:55:38 -04:00
next();
};
}
export function populateSelected<T>(
field: string,
model: string,
selection: string,
): PreMiddlewareFunction<Query<T, T>> {
2023-10-02 15:55:38 -04:00
return function (next: () => any) {
this.populate(field, selection, model);
2023-10-02 15:55:38 -04:00
next();
};
}
export function isFicmasHidden(story: IStory): boolean {
return (
((story.ficmas as IFicmas)?.year == new Date().getFullYear() &&
(story.ficmas as IFicmas)?.anniversary &&
2023-10-02 15:55:38 -04:00
new Date() < new Date(Date.parse("Aug 1 " + new Date().getFullYear()))) ||
((story.ficmas as IFicmas)?.year == new Date().getFullYear() &&
!(story.ficmas as IFicmas)?.anniversary &&
2023-10-02 15:55:38 -04:00
ficsHidden(Date.now()))
);
}
export function stringifyStream(
stream: GridFSBucketReadStream,
): Promise<string> {
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")));
});
}
export function norm(text: string): string {
return text
.replace(/\n/g, "<br>")
.replace(/<br><p>/gm, "<p>")
.replace(/<p>&nbsp;<\/p>/gm, "")
.replace(/<p><br\s\/><b\s\/><\/p>/gm, "");
}