|
|
@ -1,7 +1,24 @@ |
|
|
|
'use strict'; |
|
|
|
import { Promises } from '../promise'; |
|
|
|
|
|
|
|
export function gate() { |
|
|
|
const emptyStr = ''; |
|
|
|
|
|
|
|
function defaultResolver(...args: any[]): string { |
|
|
|
if (args.length === 1) { |
|
|
|
const arg0 = args[0]; |
|
|
|
if (arg0 == null) return emptyStr; |
|
|
|
if (typeof arg0 === 'string') return arg0; |
|
|
|
if (typeof arg0 === 'number' || typeof arg0 === 'boolean') { |
|
|
|
return String(arg0); |
|
|
|
} |
|
|
|
|
|
|
|
return JSON.stringify(arg0); |
|
|
|
} |
|
|
|
|
|
|
|
return JSON.stringify(args); |
|
|
|
} |
|
|
|
|
|
|
|
export function gate<T extends (...arg: any) => any>(resolver?: (...args: Parameters<T>) => string) { |
|
|
|
return (target: any, key: string, descriptor: PropertyDescriptor) => { |
|
|
|
let fn: Function | undefined; |
|
|
|
if (typeof descriptor.value === 'function') { |
|
|
@ -15,8 +32,11 @@ export function gate() { |
|
|
|
const gateKey = `$gate$${key}`; |
|
|
|
|
|
|
|
descriptor.value = function(this: any, ...args: any[]) { |
|
|
|
if (!Object.prototype.hasOwnProperty.call(this, gateKey)) { |
|
|
|
Object.defineProperty(this, gateKey, { |
|
|
|
const prop = |
|
|
|
args.length === 0 ? gateKey : `${gateKey}$${(resolver || defaultResolver)(...(args as Parameters<T>))}`; |
|
|
|
|
|
|
|
if (!Object.prototype.hasOwnProperty.call(this, prop)) { |
|
|
|
Object.defineProperty(this, prop, { |
|
|
|
configurable: false, |
|
|
|
enumerable: false, |
|
|
|
writable: true, |
|
|
@ -24,15 +44,15 @@ export function gate() { |
|
|
|
}); |
|
|
|
} |
|
|
|
|
|
|
|
let promise = this[gateKey]; |
|
|
|
let promise = this[prop]; |
|
|
|
if (promise === undefined) { |
|
|
|
const result = fn!.apply(this, args); |
|
|
|
if (result == null || !Promises.isPromise(result)) { |
|
|
|
return result; |
|
|
|
} |
|
|
|
|
|
|
|
this[gateKey] = promise = result.then((r: any) => { |
|
|
|
this[gateKey] = undefined; |
|
|
|
this[prop] = promise = result.then((r: any) => { |
|
|
|
this[prop] = undefined; |
|
|
|
return r; |
|
|
|
}); |
|
|
|
} |
|
|
|