summaryrefslogtreecommitdiffstats
path: root/src/services/postDatabase.ts
blob: a782af858ebaec0971e214082ba3cee5c735d61e (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
import fs from "fs/promises";
import path from "path";
import * as f from "fp-ts";
import * as t from "io-ts";
import * as tr from "io-ts/PathReporter";

export const PostDatabaseEntryC = t.type({
    provider: t.literal("e926"),
    id: t.number,
});

export type PostDatabaseEntry = t.TypeOf<typeof PostDatabaseEntryC>;

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;
        }

        this.isLoaded = true;

        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(-1 * this.max) : entries.right;
        } else {
            throw new Error(tr.failure(entries.left).join("\n\n"));
        }
    }

    private async save() {
        await fs.writeFile(this.filePath, JSON.stringify(this.entries), "utf8");
    }

    async insertIfNotExists(entry: PostDatabaseEntry): Promise<boolean> {
        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<PostDatabaseEntry | undefined> {
        await this.load();
        const entry = this.entries.shift();
        await this.save();
        return entry;
    }

    async remove(entry: PostDatabaseEntry): Promise<boolean> {
        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;
    }
}

export default PostDatabase;