From dd6971540352a03da7315d414eb20c73ef6f587a Mon Sep 17 00:00:00 2001 From: maanimis Date: Tue, 3 Sep 2024 12:18:44 +0330 Subject: [PATCH] add jsonParser --- package.json | 2 +- src/models/inMemoryStorage.js | 9 ++++++--- src/models/localStorage.js | 8 +++++--- src/utils/common.js | 21 +++++++++++++++++++++ 4 files changed, 33 insertions(+), 7 deletions(-) create mode 100644 src/utils/common.js diff --git a/package.json b/package.json index 9b912ae..6808103 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "localcache-meisam", - "version": "2.4.0", + "version": "2.5.0", "description": "[personal] An Express.js API for managing in-memory and local storage.", "main": "src/models/index.js", "type": "module", diff --git a/src/models/inMemoryStorage.js b/src/models/inMemoryStorage.js index b7185e1..25625c4 100644 --- a/src/models/inMemoryStorage.js +++ b/src/models/inMemoryStorage.js @@ -1,18 +1,21 @@ +import { jsonParser } from "../utils/common.js"; + class InMemoryStorage { constructor() { this.storage = {}; } setItem(key, value) { - this.storage[key] = value; + this.storage[key] = JSON.stringify(value); } getItem(...keys) { const result = {}; for (const key of keys) { - result[key] = this.storage[key] || null; + const value = this.storage[key] || null; + result[key] = jsonParser(value); } - return JSON.stringify(result); + return result; } getAll() { diff --git a/src/models/localStorage.js b/src/models/localStorage.js index e984ea8..0348d15 100644 --- a/src/models/localStorage.js +++ b/src/models/localStorage.js @@ -1,6 +1,7 @@ import fs from "fs"; import path from "path"; import { LocalStorage as NodeLocalStorage } from "node-localstorage"; +import { jsonParser } from "../utils/common.js"; class LocalStorage { constructor(dir) { @@ -12,15 +13,16 @@ class LocalStorage { } setItem(key, value) { - this.storage.setItem(key, value); + this.storage.setItem(key, JSON.stringify(value)); } getItem(...keys) { const result = {}; for (const key of keys) { - result[key] = this.storage.getItem(key) || null; + const value = this.storage.getItem(key) || null; + result[key] = jsonParser(value); } - return JSON.stringify(result); + return result; } removeItem(...keys) { diff --git a/src/utils/common.js b/src/utils/common.js new file mode 100644 index 0000000..4657650 --- /dev/null +++ b/src/utils/common.js @@ -0,0 +1,21 @@ +import Msg from "./msg.js"; + +function isJson(str) { + const result = new Msg(); + try { + result.obj = JSON.parse(str); + result.success = true; + } catch (e) { + result.msg = e; + result.success = false; + } + return result; +} + +export function jsonParser(str) { + const _isJson = isJson(str); + if (_isJson.success) { + return _isJson.obj; + } + return str; +}