UNPKG

nuxt-multi-cache

Version:

SSR route, component and data cache for Nuxt.js

98 lines (97 loc) 2.26 kB
export class NuxtMultiCacheRouteCacheHelper { /** * The collected cache tags. */ tags = []; /** * Indicates if the route should be cacheable. */ cacheable = null; /** * The maximum age. */ maxAge = null; /** * The stale if error age. */ staleIfError = null; /** * Whether a stale response can be served during revalidation. */ staleWhileRevalidate = null; /** * Add cache tags for this route. */ addTags(tags = []) { this.tags.push(...tags); return this; } /** * Mark this route as cacheable. * * The initial value is null and this method only changes the value if it is * null. This means that once it's set to uncacheable, there is no way to * change it back. */ setCacheable() { if (this.cacheable === null) { this.cacheable = true; } return this; } /** * Mark the route as uncacheable. * * After that there is no way to make it cacheable again. */ setUncacheable() { this.cacheable = false; return this; } /** * Set a numeric value only if its smaller than the existing value. */ setNumeric(property, value) { const current = this[property]; if (current === null || value < current) { this[property] = value; } return this; } /** * Set the max age in seconds. * * The value is only set if it's smaller than the current max age or if it * hasn't been set yet. The initial value is `null`. * * You can always directly set the maxAge property on this object. */ setMaxAge(v = 0) { return this.setNumeric("maxAge", v); } /** * Set the staleIfError in seconds. * * If set, then a stale route will be served if that refreshed route throws an error. */ setStaleIfError(v = 0) { return this.setNumeric("staleIfError", v); } /** * Sets whether a stale respones can be returned while a new one is being generated. */ allowStaleWhileRevalidate() { this.staleWhileRevalidate = true; return this; } /** * Get the expire timestamp as unix epoch (seconds). */ getExpires(property) { const value = this[property]; if (value === null) { return; } return Math.floor(Date.now() / 1e3) + value; } }