1/* 2 * Copyright (c) 2021 Huawei Device Co., Ltd. 3 * Licensed under the Apache License, Version 2.0 (the "License"); 4 * you may not use this file except in compliance with the License. 5 * You may obtain a copy of the License at 6 * 7 * http://www.apache.org/licenses/LICENSE-2.0 8 * 9 * Unless required by applicable law or agreed to in writing, software 10 * distributed under the License is distributed on an "AS IS" BASIS, 11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 * See the License for the specific language governing permissions and 13 * limitations under the License. 14 */ 15 16class MockStorage implements IStorage { 17 private dbFileName_: string; 18 private fs = require('fs'); 19 private data_ = {}; 20 21 /** 22 * Connect to existing db or create new one 23 * Note: Filename could also be managed by underlying 24 * system in C++. 25 * @param fileName 26 */ 27 constructor(fileName: string) { 28 this.dbFileName_ = fileName; 29 const file = this.fs.readFileSync(fileName, 'utf-8') 30 31 try { 32 this.data_ = JSON.parse(file); 33 } catch (e) { 34 console.debug("Error reading from database! Initializing empty object"); 35 this.data_ = {}; 36 } 37 console.debug(`MockStorage: database opened: ${JSON.stringify(this.data_)}`); 38 } 39 40 /** 41 * retrieve property 42 * @param key property name 43 * @returns property value of undefined 44 */ 45 public get<T>(key: string): T | undefined { 46 console.debug(`MockStorage: get(${key}) returns ${this.data_[key]}`); 47 return this.data_[key]; 48 } 49 50 /** 51 * Create new or update existing entry in the DB 52 * @param key property name 53 * @param val value 54 */ 55 public set<T>(key: string, val: T): void { 56 console.debug(`MockStorage: set(${key}, ${val})`); 57 this.data_[key] = val; 58 this.fs.writeFileSync(this.dbFileName_, JSON.stringify(this.data_)); 59 } 60 61 /** 62 * Delete all contents from the DB 63 */ 64 public clear(): void { 65 console.debug("MockStorage: clear()"); 66 this.data_ = {}; 67 } 68 69 /** 70 * Delete a prop from the DB 71 * @param key property name 72 */ 73 74 public delete(key: string): void { 75 console.debug(`MockStorage: delete(${key})`); 76 delete this.data_[key]; 77 this.fs.writeFileSync(this.dbFileName_, JSON.stringify(this.data_)); 78 } 79 80 /** 81 * Enumate the DB contents 82 * @returns array of all property names 83 */ 84 public keys(): string[] { 85 return Object.getOwnPropertyNames(this.data_); 86 } 87}; 88