Skip to content

Commit 201cf6a

Browse files
committed
feat: safe json parse
1 parent 32a7fdc commit 201cf6a

File tree

3 files changed

+21
-2
lines changed

3 files changed

+21
-2
lines changed

packages/pet-shop/index.js

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,13 @@
11
// @ts-nocheck
2+
3+
function safeParse(string) {
4+
try {
5+
return JSON.parse(string);
6+
} catch {
7+
8+
}
9+
}
10+
211
export function PetShop({ storage, namespace, json = false }) {
312
return Object.defineProperties(
413
{},
@@ -14,7 +23,7 @@ export function PetShop({ storage, namespace, json = false }) {
1423
value: json
1524
? function get(key) {
1625
const raw = storage.getItem(`${namespace}.${key}`);
17-
return raw !== null ? JSON.parse(raw) : undefined;
26+
return raw !== null ? safeParse(raw) : undefined;
1827
}
1928
: function get(key) {
2029
const raw = storage.getItem(`${namespace}.${key}`);

packages/pet-shop/package.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
{
22
"name": "pet-shop",
3-
"version": "0.1.0",
3+
"version": "0.1.1",
44
"description": "A simple wrapper of Web Storage API",
55
"license": "MIT",
66
"author": {

tests/pet-shop.test.mjs

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -149,3 +149,13 @@ test('Falsy value', (t) => {
149149
t.deepEqual(store.values, []);
150150
t.deepEqual(store.valueOf(), {});
151151
});
152+
153+
test('json error handle', (t) => {
154+
const store = PetShop({ namespace: 'kkk', storage, json: true });
155+
156+
storage.setItem('kkk.abc', '[');
157+
storage.setItem('kkk.efg', '[]');
158+
159+
t.is(store.get('abc'), undefined);
160+
t.deepEqual(store.get('efg'), []);
161+
});

0 commit comments

Comments
 (0)