From 163d8119c109c42e64ab37b01dec131f2cb5bf61 Mon Sep 17 00:00:00 2001 From: Volpeon Date: Tue, 19 Oct 2021 19:25:03 +0200 Subject: Code improvements, support a manual post queue --- src/services/postDatabase.ts | 86 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 86 insertions(+) create mode 100644 src/services/postDatabase.ts (limited to 'src/services/postDatabase.ts') diff --git a/src/services/postDatabase.ts b/src/services/postDatabase.ts new file mode 100644 index 0000000..e3be7bb --- /dev/null +++ b/src/services/postDatabase.ts @@ -0,0 +1,86 @@ +import fs from "fs/promises"; +import path from "path"; +import * as f from "fp-ts"; +import * as t from "io-ts"; + +export const PostDatabaseEntryC = t.type({ + provider: t.literal("e926"), + id: t.number, +}); + +export type PostDatabaseEntry = t.TypeOf; + +export class PostDatabase { + private entries: PostDatabaseEntry[] = []; + + private readonly filePath: string; + + private isLoaded = false; + + constructor(filename: string, private max?: number) { + this.filePath = path.join(process.cwd(), filename); + } + + private async load() { + if (this.isLoaded) { + return; + } + + try { + await fs.stat(this.filePath); + } catch { + await this.save(); + } + + const fileContent = await fs.readFile(this.filePath, "utf8"); + const entries = t.array(PostDatabaseEntryC).decode(fileContent); + + if (f.either.isRight(entries)) { + this.entries = this.max ? entries.right.slice(0, -1 * this.max) : entries.right; + } + } + + private async save() { + await fs.writeFile(this.filePath, JSON.stringify(this.entries), "utf8"); + } + + async insertIfNotExists(entry: PostDatabaseEntry): Promise { + await this.load(); + + const has = !!this.entries.find((e) => e.provider === entry.provider && e.id === entry.id); + + if (!has) { + this.entries.push(entry); + await this.save(); + } + + return has; + } + + async takeFirst(): Promise { + await this.load(); + const entry = this.entries.shift(); + await this.save(); + return entry; + } + + async remove(entry: PostDatabaseEntry): Promise { + await this.load(); + const i = this.entries.findIndex((e) => e.provider === entry.provider && e.id === entry.id); + + if (i === -1) { + return false; + } + + this.entries.splice(i, 1); + await this.save(); + return true; + } + + async getCount() { + await this.load(); + return this.entries.length; + } +} + +export default PostDatabase; -- cgit v1.2.3-70-g09d2