Skip to content

Commit

Permalink
fix: close #24, save every responce data from api (#25)
Browse files Browse the repository at this point in the history
  • Loading branch information
BuptStEve authored Apr 23, 2019
1 parent 02cfd36 commit c8d79d7
Show file tree
Hide file tree
Showing 3 changed files with 23 additions and 17 deletions.
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "tua-storage",
"version": "1.7.0",
"version": "1.7.1",
"description": "🏗 A common storage for web(localStorage), for RN(AsyncStorage), for mini-program(wx) or just memory cache(Node.js)",
"main": "dist/TuaStorage.cjs.js",
"module": "dist/TuaStorage.esm.js",
Expand Down
28 changes: 12 additions & 16 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -501,31 +501,27 @@ class TuaStorage {

if (!isPromise) return pRej(Error(ERROR_MSGS.promise))

// 格式化数据结构
const formatDataStructure = (data) => (data.code == null && data.data == null)
? { data }
: data

// 格式化数据类型
const formatDataType = ({ code = 0, data }) => ({ code: +code, data })
// 格式化数据结构和类型
const formatData = (data) => (data.code == null && data.data == null)
? { code: 0, data }
: { ...data, code: +data.code || 0 }

const task = originTask
.then(formatDataStructure)
.then(formatDataType)
.then(({ code, data }) => {
.then(formatData)
.then(({ code, ...rest }) => {
// 应该首先删除任务
finallyRemoveTask()

if (code !== 0 || !isAutoSave) return { code, data }
if (code !== 0 || !isAutoSave) return { code, ...rest }

this.save({
// 防止无限添加前缀
key: key.replace(this.storageKeyPrefix, ''),
data: { code, data },
data: { code, ...rest },
expires,
}).catch(logger.error)

return { code, data }
return { code, ...rest }
})
.catch(finallyRemoveTask)

Expand All @@ -550,9 +546,9 @@ class TuaStorage {
// 若数据未过期,则直接用缓存数据,
// 否则调用同步数据函数,若没有同步函数则返回错误
return isDataExpired
? !syncFn
? syncRejectFn()
: syncResolveFn()
? syncFn
? syncResolveFn()
: syncRejectFn()
: pRes(rawData)
}

Expand Down
10 changes: 10 additions & 0 deletions test/cache.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -231,6 +231,16 @@ describe('async methods', () => {
expect(stringify(cache[targetKey])).toBeUndefined()
})
})

test('load data except code/data', async () => {
const msg = 'this is msg'
const syncFn = () => Promise.resolve({ code: 1, data, msg })
const loadedData = await tuaStorage.load({ key, syncFn })

expect(loadedData.code).toBe(1)
expect(loadedData.data).toEqual(data)
expect(loadedData.msg).toEqual(msg)
})
})

describe('remove and clear only', () => {
Expand Down

0 comments on commit c8d79d7

Please sign in to comment.