This repository has been archived by the owner on Mar 4, 2020. It is now read-only.
/
index.ts
83 lines (79 loc) · 1.78 KB
/
index.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
80
81
82
83
"use strict";
import * as yaml from "js-yaml";
import * as fs from "fs-extra";
namespace Errors {
export class KeyNotExistsError extends Error {
constructor(key: string) {
super(`config key "${key}" does not exist`);
this.name = "KeyNotExistsError";
}
}
}
class Config {
private filePath: string;
public data: any = {};
constructor(filePath: string) {
this.filePath = filePath;
}
pull = async () => {
try {
await this.pullWhenExists();
} catch (err) {
if (err.code === "ENOENT") {
await this.touch();
} else {
throw err;
}
}
}
pullWhenExists = async () => {
this.data = yaml.safeLoad((await fs.readFile(this.filePath)).toString());
}
pullSync = () => {
try {
this.pullSyncWhenExists();
} catch (err) {
if (err.code === "ENOENT") {
this.touchSync();
} else {
throw err;
}
}
}
pullSyncWhenExists = () => {
this.data = yaml.safeLoad(fs.readFileSync(this.filePath).toString());
}
push = async () => {
await fs.writeFile(this.filePath, yaml.safeDump(this.data));
}
pushSync = () => {
fs.writeFileSync(this.filePath, yaml.safeDump(this.data));
}
touch = async () => {
await this.push();
}
touchSync = () => {
this.pushSync();
}
get = (name: string) => {
if (this.data[name]) {
return this.data[name];
} else {
throw new Errors.KeyNotExistsError(name);
}
}
set = (name: string, data: any) => {
this.data[name] = data;
}
setWhenExists = (name: string, data: any) => {
if (name in this.data) {
this.set(name, data);
} else {
throw new Errors.KeyNotExistsError(name);
}
}
};
namespace Config {
export let KeyNotExistsError = Errors.KeyNotExistsError;
}
export = Config;