UNPKG

balena-settings-storage

Version:
114 lines (111 loc) 3.75 kB
"use strict"; /* Copyright 2020 Balena Ltd. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ Object.defineProperty(exports, "__esModule", { value: true }); exports.createStorage = exports.NodeStorage = void 0; const tslib_1 = require("tslib"); const fs_1 = require("fs"); const path = require("path"); class NodeStorage { constructor(dataDirectory) { this.dataDirectory = dataDirectory; this.initialized = false; } init() { return tslib_1.__awaiter(this, void 0, void 0, function* () { if (this.initialized === true) { return; } if (this.initialized === false) { this.initialized = fs_1.promises.mkdir(this.dataDirectory); } try { yield this.initialized; } catch (_a) { // ignore if it already exists } finally { this.initialized = true; } }); } getPath(key) { return path.join(this.dataDirectory, encodeURIComponent(key)); } clear() { return tslib_1.__awaiter(this, void 0, void 0, function* () { try { yield Promise.all((yield fs_1.promises.readdir(this.dataDirectory)).map((f) => tslib_1.__awaiter(this, void 0, void 0, function* () { f = path.join(this.dataDirectory, f); try { if ((yield fs_1.promises.stat(f)).isDirectory()) { yield fs_1.promises.rmdir(f); } else { yield fs_1.promises.unlink(f); } } catch (_b) { // ignore } }))); } catch (_a) { // ignore } }); } getItem(key) { return tslib_1.__awaiter(this, void 0, void 0, function* () { try { return yield fs_1.promises.readFile(this.getPath(key), 'utf8'); } catch (err) { if (err.code === 'EACCES') { throw err; } return null; } }); } setItem(key, data) { return tslib_1.__awaiter(this, void 0, void 0, function* () { yield this.init(); yield fs_1.promises.writeFile(this.getPath(key), data, 'utf8'); }); } removeItem(key) { return tslib_1.__awaiter(this, void 0, void 0, function* () { try { yield fs_1.promises.unlink(this.getPath(key)); } catch (e) { // ignore } }); } } exports.NodeStorage = NodeStorage; const storageCache = Object.create(null); const createStorage = (dataDirectory) => { if (dataDirectory == null) { throw new Error('dataDirectory must be specified in nodejs'); } if (!storageCache[dataDirectory]) { storageCache[dataDirectory] = new NodeStorage(dataDirectory); } return storageCache[dataDirectory]; }; exports.createStorage = createStorage; //# sourceMappingURL=node-storage.js.map