aboutsummaryrefslogtreecommitdiffstats
path: root/lib/persist.js
blob: 8061d8a31858f2c3019c06170c1eafe638c1636c (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
import fs from "fs";

export default (path, initial = {}) => {
  if (!initial || !Object.keys(initial).length) {
    try {
      initial = require("../" + path);
    } catch (e) {}
  }

  return new Proxy(initial, {
    set(obj, prop, value) {
      fs.writeFileSync(
        path,
        JSON.stringify({ ...obj, [prop]: value }, null, 2),
        "utf-8"
      );
      return Reflect.set(...arguments);
    }
  });
};