功能:收口小程序前后台安全与防重复提交

This commit is contained in:
xiaowang
2026-04-20 16:02:57 +08:00
parent eb1c209d79
commit a3df262fae
237 changed files with 14068 additions and 728 deletions
+78
View File
@@ -0,0 +1,78 @@
const inflightScopes = new Map()
function resolveScopeId(scope) {
if (scope && typeof scope === 'string') {
return scope
}
if (scope && typeof scope.route === 'string' && scope.route) {
return scope.route
}
const pages = typeof getCurrentPages === 'function' ? getCurrentPages() : []
const current = pages[pages.length - 1]
if (current && current.route) {
return current.route
}
return 'global'
}
function getScopeMap(scopeId) {
if (!inflightScopes.has(scopeId)) {
inflightScopes.set(scopeId, new Map())
}
return inflightScopes.get(scopeId)
}
function createGuardError(message, scopeId, actionKey) {
const error = new Error(message || '\u64cd\u4f5c\u8fdb\u884c\u4e2d\uff0c\u8bf7\u52ff\u91cd\u590d\u70b9\u51fb')
error.isActionGuardError = true
error.scopeId = scopeId
error.actionKey = actionKey
return error
}
async function run(scope, actionKey, task, options) {
const scopeId = resolveScopeId(scope)
const normalizedKey = String(actionKey || 'default')
const scopeMap = getScopeMap(scopeId)
if (scopeMap.get(normalizedKey)) {
return Promise.reject(createGuardError((options && options.message) || '', scopeId, normalizedKey))
}
scopeMap.set(normalizedKey, true)
try {
return await Promise.resolve().then(() => task())
} finally {
scopeMap.delete(normalizedKey)
if (!scopeMap.size) {
inflightScopes.delete(scopeId)
}
}
}
function isRunning(scope, actionKey) {
const scopeId = resolveScopeId(scope)
const scopeMap = inflightScopes.get(scopeId)
if (!scopeMap) {
return false
}
return Boolean(scopeMap.get(String(actionKey || 'default')))
}
function clearScope(scope) {
inflightScopes.delete(resolveScopeId(scope))
}
function isGuardError(error) {
return Boolean(error && error.isActionGuardError)
}
module.exports = {
run,
isRunning,
clearScope,
isGuardError,
createGuardError
}