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 16// Mock of the native provided IStorage used by PersistentStorage 17 18class MockStorage implements IStorage { 19 private dbFileName_: string; 20 private fs = require('fs'); 21 private data_ = {}; 22 23 /** 24 * Connect to existing db or create new one 25 * Note: Filename could also be managed by underlying 26 * system in C++. 27 * @param fileName 28 */ 29 constructor(fileName: string) { 30 this.dbFileName_ = fileName; 31 const file = this.fs.readFileSync(fileName, 'utf-8') 32 33 try { 34 this.data_ = JSON.parse(file); 35 } catch (e) { 36 console.debug("Error reading from database! Initializing empty object"); 37 this.data_ = {}; 38 } 39 console.debug(`MockStorage: database opened: ${JSON.stringify(this.data_)}`); 40 } 41 42 /** 43 * retrieve property 44 * @param key property name 45 * @returns property value of undefined 46 */ 47 public get<T>(key: string): T | undefined { 48 console.debug(`MockStorage: get(${key}) returns ${this.data_[key]}`); 49 return this.data_[key]; 50 } 51 52 /** 53 * Create new or update existing entry in the DB 54 * @param key property name 55 * @param val value 56 */ 57 public set<T>(key: string, val: T): void { 58 console.debug(`MockStorage: set(${key}, ${val})`); 59 this.data_[key] = val; 60 this.fs.writeFileSync(this.dbFileName_, JSON.stringify(this.data_)); 61 } 62 63 /** 64 * Delete all contents from the DB 65 */ 66 public clear(): void { 67 console.debug("MockStorage: clear()"); 68 this.data_ = {}; 69 } 70 71 /** 72 * Delete a prop from the DB 73 * @param key property name 74 */ 75 76 public delete(key: string): void { 77 console.debug(`MockStorage: delete(${key})`); 78 delete this.data_[key]; 79 this.fs.writeFileSync(this.dbFileName_, JSON.stringify(this.data_)); 80 } 81 82 /** 83 * Enumate the DB contents 84 * @returns array of all property names 85 */ 86 public keys(): string[] { 87 return Object.getOwnPropertyNames(this.data_); 88 } 89}; 90