Skip to content

Commit

Permalink
feat: 🎸 Replace deepFreeze with readonly to provide better error mess…
Browse files Browse the repository at this point in the history
…ages
  • Loading branch information
haozi committed Dec 10, 2023
1 parent 2edc539 commit 1489487
Show file tree
Hide file tree
Showing 4 changed files with 53 additions and 13 deletions.
9 changes: 9 additions & 0 deletions demo/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,15 @@ import React, { useState } from 'react'
import Item from './Item'
import ItemIdmp from './ItemIdmp'
// import idmp from '../src'
// import { getUserDataIdmp } from './api'

// getUserDataIdmp('123').then((d) => {
// console.log(123, d)
// d.extra.a = {
// a: 1,
// b: 2,
// }
// })

// const getInfo = async () => {
// // const API = `https://haozi.meaa/?api/your-info`
Expand Down
8 changes: 6 additions & 2 deletions demo/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,13 +11,17 @@ export const getUserData = async (userId: string) => {
const API = `https://haozi.me/?id=${userId}&t=${Math.random()}`
await fetch(API).then((d) => d.text())

const res = { id: userId, val: Math.random() }
const res = {
id: userId,
val: Math.random(),
extra: { a: { b: { c: 111 } } },
}
return res
}

export const getUserDataIdmp = (userId: string) => {
const key = `getUserData:${userId}`
return idmp(key, () => getUserData(userId))
return idmp(key, () => getUserData(userId), { maxAge: 60 * 1000 })
}

export const getUserDataIdmp2 = (userId: string) => {
Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "idmp",
"version": "1.8.4",
"version": "1.9.0",
"keywords": [
"cache response",
"swr without hooks",
Expand Down
47 changes: 37 additions & 10 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -61,16 +61,43 @@ const DEFAULT_MAX_AGE = 3000
const _7days = 604800000
const noop = () => {}
const udf = undefined
const deepFreeze = /* @__PURE__ */ <T>(obj: any): T => {
if (!obj) return obj
if (typeof obj !== 'object') return obj

Object.keys(obj).forEach((property) => {
if (typeof obj[property] === 'object' && !Object.isFrozen(obj[property])) {
deepFreeze(obj[property])
}
// const deepFreeze = /* @__PURE__ */ <T>(obj: any): T => {
// if (!obj) return obj
// if (typeof obj !== 'object') return obj

// Object.keys(obj).forEach((property) => {
// if (typeof obj[property] === 'object' && !Object.isFrozen(obj[property])) {
// deepFreeze(obj[property])
// }
// })
// return Object.freeze(obj)
// }

const defineReactive = (obj: any, key: string | symbol, value: any) => {
readonly(value)
Object.defineProperty(obj, key, {
get: () => value,
set: (newValue) => {
const msg = `[idmp error] The data is read-only, set ${key.toString()}=${JSON.stringify(
newValue,
)} is not allow`
console.error(`%c ${msg}`, 'font-weight: lighter; color: red')
throw new Error(msg)
},
})
}

const readonly = <T>(obj: T): T => {
if (obj === null || typeof obj !== 'object') {
return obj
}

Object.keys(obj).forEach((key) => {
defineReactive(obj, key, (obj as any)[key])
})
return Object.freeze(obj)

return obj
}

const getRange = (maxAge: number) => {
Expand Down Expand Up @@ -120,7 +147,7 @@ const idmp = <T>(
options?: IdmpOptions,
): Promise<T> => {
if (process.env.NODE_ENV !== 'production') {
options = deepFreeze(options)
options = readonly(options)
}

const {
Expand Down Expand Up @@ -275,7 +302,7 @@ const idmp = <T>(
cache[K.oneCallPromiseFunc]()
.then((data: T) => {
if (process.env.NODE_ENV !== 'production') {
cache[K.resData] = deepFreeze<T>(data)
cache[K.resData] = readonly<T>(data)
} else {
cache[K.resData] = data
}
Expand Down

0 comments on commit 1489487

Please sign in to comment.