1 | import { startOfToday, getTime } from "date-fns";
|
2 | import * as fse from "fs-extra";
|
3 | import { HOME_DIR } from "./config";
|
4 |
|
5 | export class Cache<Info> {
|
6 | private cacheFile: string;
|
7 | protected cacheInfo: Info;
|
8 |
|
9 | constructor(filename: string) {
|
10 | this.cacheFile = `./${HOME_DIR}/${filename}`;
|
11 | fse.ensureFileSync(this.cacheFile);
|
12 | }
|
13 |
|
14 | protected readFile = () => {
|
15 | return fse.readFileSync(this.cacheFile, "utf8");
|
16 | };
|
17 |
|
18 | protected writeToFile = () => {
|
19 | return fse.writeFile(this.cacheFile, JSON.stringify(this.cacheInfo), "utf8");
|
20 | };
|
21 | }
|
22 |
|
23 | export class LastBuiltEntryCache extends Cache<string[]> {
|
24 | constructor() {
|
25 | super("last-build-entry-cache.json");
|
26 | try {
|
27 | this.cacheInfo = JSON.parse(this.readFile());
|
28 | } catch {
|
29 | this.cacheInfo = [];
|
30 | }
|
31 | }
|
32 |
|
33 | getEntry() {
|
34 | return this.cacheInfo;
|
35 | }
|
36 |
|
37 | refreshEntry(newEntry: string[]) {
|
38 | this.cacheInfo = newEntry;
|
39 | this.writeToFile();
|
40 | }
|
41 | }
|
42 |
|
43 | export interface EntryCacheInfo {
|
44 | entryList: string[];
|
45 | createTime: number;
|
46 | }
|
47 |
|
48 | export class DevEntryCache extends Cache<EntryCacheInfo> {
|
49 | private currentTime: number;
|
50 |
|
51 | constructor() {
|
52 | super("dev-entry-cache.json");
|
53 | this.currentTime = getTime(startOfToday());
|
54 | try {
|
55 | this.cacheInfo = JSON.parse(this.readFile());
|
56 | const { createTime } = this.cacheInfo;
|
57 | if (createTime && createTime < this.currentTime) {
|
58 | this.cacheInfo = {
|
59 | entryList: [],
|
60 | createTime: this.currentTime
|
61 | };
|
62 | }
|
63 | } catch {
|
64 | this.cacheInfo = {
|
65 | entryList: [],
|
66 | createTime: this.currentTime
|
67 | };
|
68 | }
|
69 | }
|
70 |
|
71 | getEntry() {
|
72 | return this.cacheInfo.entryList;
|
73 | }
|
74 |
|
75 | addEntry(entryName: string) {
|
76 | const entryList = this.cacheInfo.entryList;
|
77 | if (!entryList.includes(entryName)) {
|
78 | entryList.push(entryName);
|
79 | this.writeToFile();
|
80 | }
|
81 | }
|
82 | }
|
83 |
|
84 | export const lastBuiltEntryCache = new LastBuiltEntryCache();
|
85 | export const devEntryCache = new DevEntryCache();
|