-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathJsonModel.ts
79 lines (66 loc) · 1.93 KB
/
JsonModel.ts
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
import crypto from "crypto"
import fs from "fs/promises"
import { join } from "path"
import { existsSync } from "fs"
import { isFile, readJSON, writeJSON } from "./lib"
import config from "./config"
export class JsonModel<T=Record<string, any>>
{
private state: T;
public readonly id: string;
private path: string;
public static async create<T=Record<string, any>>(state?: T): Promise<JsonModel<T>>
{
const id = crypto.randomBytes(config.jobsIdLength).toString("hex")
await fs.mkdir(join(config.jobsPath, id))
const instance = new JsonModel<T>(id, state)
await instance.save()
return instance
}
public static async byId<T=Record<string, any>>(id: string): Promise<JsonModel<T> | null>
{
const filePath = join(config.jobsPath, id, "state.json")
if (isFile(filePath)) {
const state: T = await readJSON(filePath)
return new JsonModel<T>(id, state)
}
return null
}
private constructor(id: string, state: T)
{
this.id = id
this.path = join(config.jobsPath, id, "state.json")
this.state = { ...state }
}
public toJSON(): T
{
return this.state
}
public get(key: keyof T): any
{
return this.state[key]
}
public set(key: keyof T, value: any): void
{
this.state[key] = value
}
public unset(key: keyof T): void
{
delete this.state[key]
}
public async save(props?: Partial<T>): Promise<void>
{
if (existsSync(join(config.jobsPath, this.id))) {
if (props) {
for (let key in props) {
this.set(key, props[key])
}
}
await writeJSON(this.path, this.toJSON())
}
}
public delete(): Promise<void>
{
return fs.unlink(this.path)
}
}