Socialify

Folder ..

Viewing cache.ts
46 lines (39 loc) • 1.1 KB

 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
import { join } from "https://deno.land/[email protected]/path/mod.ts";
import {
  ensureDirSync,
  existsSync,
} from "https://deno.land/[email protected]/fs/mod.ts";
import { environment } from "../environment/environment.ts";

export class Cache {
  path = environment.cacheDir;

  public saveJson(name: string, data: {}) {
    ensureDirSync(this.path);

    Deno.writeTextFileSync(
      join(this.path, `${name}.json`),
      JSON.stringify(data)
    );
  }

  public saveTxt(name: string, value: string) {
    ensureDirSync(this.path);
    Deno.writeTextFileSync(join(this.path, `${name}.txt`), value);
  }

  public readJson(name: string): {} | [] | undefined {
    let data;
    try {
      data = Deno.readTextFileSync(join(this.path, `${name}.json`));
    } catch (err) {
      return undefined;
    }
    return JSON.parse(data);
  }

  public readTxt(name: string) {
    try {
      return Deno.readTextFileSync(join(this.path, `${name}.txt`));
    } catch (err) {
      return undefined;
    }
  }

  public exists(name: string, extension?: string) {
    return existsSync(join(this.path, `${name}${extension}`));
  }
}