Skip to content

Commit

Permalink
Added ttl
Browse files Browse the repository at this point in the history
  • Loading branch information
mupperton committed Oct 11, 2022
1 parent 6f259e7 commit ad7bfde
Showing 1 changed file with 27 additions and 4 deletions.
31 changes: 27 additions & 4 deletions src/phunk.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
interface Config {
init?: boolean
cacheRejections?: boolean
ttl?: number
}

const noop = () => {}
Expand All @@ -16,21 +17,40 @@ class Phunk<T> {

#cacheRejections

constructor(fn: () => T, config?: Config) {
this.#fn = fn
#ttl
#lastResolve = 0

constructor(fn: () => T, config?: Config) {
const options = config ?? {}

if (typeof options.ttl !== 'undefined' && (!Number.isSafeInteger(options.ttl) || options.ttl < 0)) {
throw new TypeError('<config.ttl> must be a positive integer')
}

this.#fn = fn

this.#cacheRejections = options.cacheRejections === true

this.#ttl = options.ttl ?? null

if (options.init === true) {
this.next().catch(noop) // catch error to avoid unhandled promise exceptions
}
}

async current() {
if (this.#promise === null) return this.next()
if (!this.#cacheRejections && this.#isRejected) return this.next()
if (this.#promise === null) {
// first invocation
return this.next()
}
if (!this.#cacheRejections && this.#isRejected) {
// Configured not to cache rejections and previously rejected
return this.next()
}
if (this.#ttl !== null && Date.now() >= (this.#lastResolve + this.#ttl)) {
// ttl expired
return this.next()
}

return this.#promise
}
Expand All @@ -55,6 +75,9 @@ class Phunk<T> {
this.#isRejected = true
throw error
} finally {
if (this.#ttl !== null) {
this.#lastResolve = Date.now()
}
this.#isResolving = false
}
}
Expand Down

0 comments on commit ad7bfde

Please sign in to comment.