Skip to content

Commit

Permalink
fixup
Browse files Browse the repository at this point in the history
  • Loading branch information
ronag committed Nov 15, 2024
1 parent ab59084 commit b114ce4
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 2 deletions.
27 changes: 25 additions & 2 deletions lib/cache/memory-cache-store.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,11 @@ const { Writable } = require('node:stream')
*/
class MemoryCacheStore {
#maxCount = Infinity
#maxSize = Infinity
#maxEntrySize = Infinity

#size = 0

/**
* @type {Map<string, Map<string, GetResult[]>>}
*/
Expand All @@ -42,6 +45,17 @@ class MemoryCacheStore {
this.#maxCount = opts.maxCount
}

if (opts.maxSize !== undefined) {
if (
typeof opts.maxSize !== 'number' ||
!Number.isInteger(opts.maxSize) ||
opts.maxSize < 0
) {
throw new TypeError('MemoryCacheStore options.maxSize must be a non-negative integer')
}
this.#maxSize = opts.maxSize
}

if (opts.maxEntrySize !== undefined) {
if (
typeof opts.maxEntrySize !== 'number' ||
Expand All @@ -56,7 +70,7 @@ class MemoryCacheStore {
}

get isFull () {
return this.#arr.length >= this.#maxCount
return this.#arr.length >= this.#maxCount || this.#size >= this.#maxSize
}

/**
Expand All @@ -65,7 +79,8 @@ class MemoryCacheStore {
*/
get (key) {
const values = this.#getValuesForRequest(key)
return findValue(key, values)
const value = findValue(key, values)
return value != null ? { ...value } : undefined
}

/**
Expand Down Expand Up @@ -120,7 +135,12 @@ class MemoryCacheStore {
let value = findValue(key, values)
if (!value) {
value = { ...opts, body }

store.#arr.push(value)
for (const buf of body) {
store.#size += buf.byteLength
}

values.push(value)
} else {
Object.assign(value, opts, { body })
Expand Down Expand Up @@ -172,6 +192,9 @@ class MemoryCacheStore {

const count = Math.max(0, this.#arr.length - this.#maxCount / 2)
for (const value of this.#arr.splice(0, count)) {
for (const buf of value.body) {
this.#size -= buf.byteLength
}
value.body = null
}

Expand Down
5 changes: 5 additions & 0 deletions types/cache-interceptor.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,11 @@ declare namespace CacheHandler {
*/
maxCount?: number

/**
* @default Infinity
*/
maxSize?: number

/**
* @default Infinity
*/
Expand Down

0 comments on commit b114ce4

Please sign in to comment.