/ src / storage-folder.js
storage-folder.js
 1  const path = require('path');
 2  const fs = require('fs-plus');
 3  
 4  module.exports = class StorageFolder {
 5    constructor(containingPath) {
 6      if (containingPath) {
 7        this.path = path.join(containingPath, 'storage');
 8      }
 9    }
10  
11    store(name, object) {
12      return new Promise((resolve, reject) => {
13        if (!this.path) return resolve();
14        fs.writeFile(
15          this.pathForKey(name),
16          JSON.stringify(object),
17          'utf8',
18          error => (error ? reject(error) : resolve())
19        );
20      });
21    }
22  
23    load(name) {
24      return new Promise(resolve => {
25        if (!this.path) return resolve(null);
26        const statePath = this.pathForKey(name);
27        fs.readFile(statePath, 'utf8', (error, stateString) => {
28          if (error && error.code !== 'ENOENT') {
29            console.warn(
30              `Error reading state file: ${statePath}`,
31              error.stack,
32              error
33            );
34          }
35  
36          if (!stateString) return resolve(null);
37  
38          try {
39            resolve(JSON.parse(stateString));
40          } catch (error) {
41            console.warn(
42              `Error parsing state file: ${statePath}`,
43              error.stack,
44              error
45            );
46            resolve(null);
47          }
48        });
49      });
50    }
51  
52    pathForKey(name) {
53      return path.join(this.getPath(), name);
54    }
55  
56    getPath() {
57      return this.path;
58    }
59  };