功能:收口小程序前后台安全与防重复提交
This commit is contained in:
@@ -0,0 +1,73 @@
|
||||
const DRAFT_PREFIX = 'miniDraft:'
|
||||
|
||||
function buildDraftKey(key) {
|
||||
return `${DRAFT_PREFIX}${key}`
|
||||
}
|
||||
|
||||
function loadDraft(key, defaultValue) {
|
||||
if (!key) {
|
||||
return defaultValue
|
||||
}
|
||||
try {
|
||||
const value = wx.getStorageSync(buildDraftKey(key))
|
||||
return value === undefined || value === '' ? defaultValue : value
|
||||
} catch (error) {
|
||||
return defaultValue
|
||||
}
|
||||
}
|
||||
|
||||
function saveDraft(key, value) {
|
||||
if (!key) {
|
||||
return
|
||||
}
|
||||
try {
|
||||
wx.setStorageSync(buildDraftKey(key), {
|
||||
savedAt: Date.now(),
|
||||
value
|
||||
})
|
||||
} catch (error) {}
|
||||
}
|
||||
|
||||
function clearDraft(key) {
|
||||
if (!key) {
|
||||
return
|
||||
}
|
||||
try {
|
||||
wx.removeStorageSync(buildDraftKey(key))
|
||||
} catch (error) {}
|
||||
}
|
||||
|
||||
function getDraftValue(key, defaultValue) {
|
||||
const record = loadDraft(key, null)
|
||||
if (!record || typeof record !== 'object' || !Object.prototype.hasOwnProperty.call(record, 'value')) {
|
||||
return defaultValue
|
||||
}
|
||||
return record.value
|
||||
}
|
||||
|
||||
function scheduleDraftSave(context, key, buildValue, delay) {
|
||||
if (!context) {
|
||||
return
|
||||
}
|
||||
if (context.__draftSaveTimer) {
|
||||
clearTimeout(context.__draftSaveTimer)
|
||||
}
|
||||
context.__draftSaveTimer = setTimeout(() => {
|
||||
saveDraft(key, buildValue())
|
||||
}, delay || 300)
|
||||
}
|
||||
|
||||
function clearDraftTimer(context) {
|
||||
if (context && context.__draftSaveTimer) {
|
||||
clearTimeout(context.__draftSaveTimer)
|
||||
context.__draftSaveTimer = null
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
getDraftValue,
|
||||
saveDraft,
|
||||
clearDraft,
|
||||
scheduleDraftSave,
|
||||
clearDraftTimer
|
||||
}
|
||||
Reference in New Issue
Block a user