Skip to content

Commit

Permalink
add jsonParser
Browse files Browse the repository at this point in the history
  • Loading branch information
maanimis committed Sep 3, 2024
1 parent 78e94f8 commit dd69715
Show file tree
Hide file tree
Showing 4 changed files with 33 additions and 7 deletions.
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -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",
Expand Down
9 changes: 6 additions & 3 deletions src/models/inMemoryStorage.js
Original file line number Diff line number Diff line change
@@ -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() {
Expand Down
8 changes: 5 additions & 3 deletions src/models/localStorage.js
Original file line number Diff line number Diff line change
@@ -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) {
Expand All @@ -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) {
Expand Down
21 changes: 21 additions & 0 deletions src/utils/common.js
Original file line number Diff line number Diff line change
@@ -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;
}

0 comments on commit dd69715

Please sign in to comment.