@vida-global/core 2.0.9 → 2.0.11
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/index.js +2 -0
- package/lib/activeRecord/baseRecord.js +22 -0
- package/lib/cache/index.js +4 -0
- package/lib/cache/memoryCache.js +155 -0
- package/package.json +1 -1
- package/test/activeRecord/baseRecord.test.js +52 -0
- package/test/cache/memoryCache.test.js +233 -0
package/index.js
CHANGED
|
@@ -4,6 +4,7 @@ const APM = require('./lib/apm');
|
|
|
4
4
|
const JobQueue = require('./lib/jobQueue');
|
|
5
5
|
const { logger } = require('./lib/logger');
|
|
6
6
|
const redisLibs = require('./lib/redis');
|
|
7
|
+
const cacheLibs = require('./lib/cache');
|
|
7
8
|
const serverLibs = require('./lib/server');
|
|
8
9
|
|
|
9
10
|
|
|
@@ -22,6 +23,7 @@ module.exports = {
|
|
|
22
23
|
...httpLibs,
|
|
23
24
|
JobQueue,
|
|
24
25
|
logger,
|
|
26
|
+
...cacheLibs,
|
|
25
27
|
...redisLibs,
|
|
26
28
|
...serverErrorsToExport,
|
|
27
29
|
ApiDocsGenerator,
|
|
@@ -18,6 +18,11 @@ class BaseRecord extends Model {
|
|
|
18
18
|
static get col() { return this.connection._sequelize.col }
|
|
19
19
|
|
|
20
20
|
|
|
21
|
+
static sqlLiteral(sql) {
|
|
22
|
+
return this.sequelize.literal(sql);
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
|
|
21
26
|
constructor() {
|
|
22
27
|
if (new.target == BaseRecord) throw new Error("Cannot create an instance of BaseRecord");
|
|
23
28
|
super(...arguments);
|
|
@@ -142,6 +147,23 @@ class BaseRecord extends Model {
|
|
|
142
147
|
/***********************************************************************************************
|
|
143
148
|
* DB CONNECTION
|
|
144
149
|
***********************************************************************************************/
|
|
150
|
+
static async withStatementTimeout(milliseconds, callback) {
|
|
151
|
+
return await this.sequelize.transaction(
|
|
152
|
+
{readOnly: true},
|
|
153
|
+
async(transaction) => {
|
|
154
|
+
await this.sequelize.query(
|
|
155
|
+
'SELECT set_config(\'statement_timeout\', :timeout, true)',
|
|
156
|
+
{
|
|
157
|
+
replacements: {timeout: String(milliseconds)},
|
|
158
|
+
transaction,
|
|
159
|
+
}
|
|
160
|
+
);
|
|
161
|
+
return await callback(transaction);
|
|
162
|
+
}
|
|
163
|
+
);
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
|
|
145
167
|
static get connectionClass() {
|
|
146
168
|
return Connection;
|
|
147
169
|
}
|
|
@@ -0,0 +1,155 @@
|
|
|
1
|
+
class MemoryCache {
|
|
2
|
+
#entries = new Map();
|
|
3
|
+
#pendingFetches = new Map();
|
|
4
|
+
#maxEntries;
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
constructor({ maxEntries = 1000 } = {}) {
|
|
8
|
+
const limit = maxEntries;
|
|
9
|
+
if (limit <= 0 || limit > 1000) {
|
|
10
|
+
throw new TypeError('MemoryCache maxEntries must be between 1 and 1000.');
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
this.#maxEntries = limit;
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
async fetch(options = {}, fetcher) {
|
|
18
|
+
this.#validateNamespace(options.namespace);
|
|
19
|
+
this.#validateTtl(options.ttlSeconds);
|
|
20
|
+
this.#validateFetcher(fetcher);
|
|
21
|
+
|
|
22
|
+
const cacheKey = this.#createCacheKey(options);
|
|
23
|
+
const cached = this.#get(cacheKey);
|
|
24
|
+
if (cached) return this.#buildFetchResult(cached.value, true);
|
|
25
|
+
|
|
26
|
+
const pending = this.#pendingFetches.get(cacheKey);
|
|
27
|
+
if (pending) return this.#buildFetchResult(await pending, false);
|
|
28
|
+
|
|
29
|
+
const fetch = this.#fetch(options, fetcher, cacheKey);
|
|
30
|
+
this.#pendingFetches.set(cacheKey, fetch);
|
|
31
|
+
|
|
32
|
+
try {
|
|
33
|
+
return this.#buildFetchResult(await fetch, false);
|
|
34
|
+
} finally {
|
|
35
|
+
this.#pendingFetches.delete(cacheKey);
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
#set(cacheKey, ttlSeconds, value) {
|
|
41
|
+
this.#ensureSpaceForEntry(cacheKey);
|
|
42
|
+
this.#moveToRecentlyUsed(cacheKey, {
|
|
43
|
+
value,
|
|
44
|
+
expiresAt: Date.now() + (ttlSeconds * 1000),
|
|
45
|
+
});
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
async #fetch(options, fetcher, cacheKey) {
|
|
50
|
+
const value = await fetcher();
|
|
51
|
+
this.#set(cacheKey, options.ttlSeconds, value);
|
|
52
|
+
return value;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
#createCacheKey({ namespace, key }) {
|
|
57
|
+
return `${namespace}:${serializeCacheKey(key)}`;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
#get(cacheKey) {
|
|
62
|
+
const cached = this.#entries.get(cacheKey);
|
|
63
|
+
if (!cached) return null;
|
|
64
|
+
|
|
65
|
+
if (this.#isExpired(cached)) {
|
|
66
|
+
this.#entries.delete(cacheKey);
|
|
67
|
+
return null;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
this.#moveToRecentlyUsed(cacheKey, cached);
|
|
71
|
+
return cached;
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
#buildFetchResult(value, cacheHit) {
|
|
76
|
+
return {
|
|
77
|
+
value,
|
|
78
|
+
cacheHit,
|
|
79
|
+
};
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
#validateNamespace(namespace) {
|
|
84
|
+
if (!namespace || typeof namespace !== 'string') {
|
|
85
|
+
throw new TypeError('MemoryCache namespace is required.');
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
#validateTtl(ttlSeconds) {
|
|
91
|
+
if (!Number.isInteger(ttlSeconds) || ttlSeconds <= 0) {
|
|
92
|
+
throw new RangeError('ttlSeconds must be a positive integer');
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
#validateFetcher(fetcher) {
|
|
98
|
+
if (typeof fetcher !== 'function') {
|
|
99
|
+
throw new TypeError('MemoryCache fetcher must be a function.');
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
#isExpired(entry) {
|
|
105
|
+
return entry.expiresAt <= Date.now();
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
#removeExpiredEntries() {
|
|
110
|
+
for (const [key, entry] of this.#entries) {
|
|
111
|
+
if (this.#isExpired(entry)) this.#entries.delete(key);
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
#evictLeastRecentlyUsedEntries() {
|
|
117
|
+
while (this.#entries.size >= this.#maxEntries) {
|
|
118
|
+
const [cacheKey] = this.#entries.keys();
|
|
119
|
+
this.#entries.delete(cacheKey);
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
#ensureSpaceForEntry(cacheKey) {
|
|
125
|
+
if (this.#entries.has(cacheKey) || this.#entries.size < this.#maxEntries) return;
|
|
126
|
+
this.#removeExpiredEntries();
|
|
127
|
+
|
|
128
|
+
if (this.#entries.size >= this.#maxEntries) {
|
|
129
|
+
this.#evictLeastRecentlyUsedEntries()
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
#moveToRecentlyUsed(cacheKey, entry) {
|
|
135
|
+
this.#entries.delete(cacheKey);
|
|
136
|
+
this.#entries.set(cacheKey, entry);
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
function serializeCacheKey(value) {
|
|
143
|
+
if (Array.isArray(value)) return `[${value.map((item) => serializeCacheKey(item)).join(',')}]`;
|
|
144
|
+
if (value && typeof value === 'object') {
|
|
145
|
+
const entries = Object.keys(value)
|
|
146
|
+
.sort()
|
|
147
|
+
.map((key) => `${JSON.stringify(key)}:${serializeCacheKey(value[key])}`);
|
|
148
|
+
return `{${entries.join(',')}}`;
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
return JSON.stringify(value);
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
|
|
155
|
+
module.exports = { MemoryCache };
|
package/package.json
CHANGED
|
@@ -80,6 +80,58 @@ describe('BaseRecord', () => {
|
|
|
80
80
|
});
|
|
81
81
|
|
|
82
82
|
|
|
83
|
+
describe('BaseRecord.withStatementTimeout', () => {
|
|
84
|
+
it ('runs the callback in a read-only transaction with a local statement timeout', async () => {
|
|
85
|
+
const callback = jest.fn().mockResolvedValue('result');
|
|
86
|
+
const transaction = {};
|
|
87
|
+
const query = jest.fn().mockResolvedValue(undefined);
|
|
88
|
+
const transact = jest.fn(
|
|
89
|
+
async (_options, transactionCallback) => {
|
|
90
|
+
return await transactionCallback(transaction);
|
|
91
|
+
}
|
|
92
|
+
);
|
|
93
|
+
class User extends BaseRecord {}
|
|
94
|
+
User.sequelize = {query, transaction: transact};
|
|
95
|
+
|
|
96
|
+
await expect(
|
|
97
|
+
User.withStatementTimeout(15000, callback)
|
|
98
|
+
).resolves.toEqual('result');
|
|
99
|
+
|
|
100
|
+
expect(transact).toHaveBeenCalledTimes(1);
|
|
101
|
+
expect(transact).toHaveBeenCalledWith(
|
|
102
|
+
{readOnly: true},
|
|
103
|
+
expect.any(Function)
|
|
104
|
+
);
|
|
105
|
+
expect(query).toHaveBeenCalledTimes(1);
|
|
106
|
+
expect(query).toHaveBeenCalledWith(
|
|
107
|
+
'SELECT set_config(\'statement_timeout\', :timeout, true)',
|
|
108
|
+
{
|
|
109
|
+
replacements: {timeout: '15000'},
|
|
110
|
+
transaction,
|
|
111
|
+
}
|
|
112
|
+
);
|
|
113
|
+
expect(callback).toHaveBeenCalledTimes(1);
|
|
114
|
+
expect(callback).toHaveBeenCalledWith(transaction);
|
|
115
|
+
});
|
|
116
|
+
});
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
describe('BaseRecord.sqlLiteral', () => {
|
|
120
|
+
it ('returns the SQL literal built by the model sequelize connection', () => {
|
|
121
|
+
const sql = TestHelpers.Faker.Text.randomString();
|
|
122
|
+
const literal = {};
|
|
123
|
+
const literalBuilder = jest.fn().mockReturnValue(literal);
|
|
124
|
+
class User extends BaseRecord {}
|
|
125
|
+
User.sequelize = {literal: literalBuilder};
|
|
126
|
+
|
|
127
|
+
expect(User.sqlLiteral(sql)).toBe(literal);
|
|
128
|
+
|
|
129
|
+
expect(literalBuilder).toHaveBeenCalledTimes(1);
|
|
130
|
+
expect(literalBuilder).toHaveBeenCalledWith(sql);
|
|
131
|
+
});
|
|
132
|
+
});
|
|
133
|
+
|
|
134
|
+
|
|
83
135
|
describe('BaseRecord.initialize', () => {
|
|
84
136
|
it ('calls `getBaseRecordSchema` and passes the response to init', () => {
|
|
85
137
|
class User extends BaseRecord {}
|
|
@@ -0,0 +1,233 @@
|
|
|
1
|
+
const { MemoryCache } = require('../../lib/cache');
|
|
2
|
+
const { MemoryCache: PublicMemoryCache } = require('../../index');
|
|
3
|
+
|
|
4
|
+
|
|
5
|
+
describe('MemoryCache', () => {
|
|
6
|
+
let cache;
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
beforeEach(() => {
|
|
10
|
+
cache = new MemoryCache();
|
|
11
|
+
});
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
afterEach(() => {
|
|
15
|
+
jest.restoreAllMocks();
|
|
16
|
+
});
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
describe('#fetch', () => {
|
|
20
|
+
const options = {
|
|
21
|
+
namespace: 'squire:shop-data',
|
|
22
|
+
key: { shopId: 'shop-1' },
|
|
23
|
+
ttlSeconds: 300,
|
|
24
|
+
};
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
it('fetches and caches a value', async () => {
|
|
28
|
+
const value = { services: ['Cut'] };
|
|
29
|
+
const fetcher = jest.fn().mockResolvedValue(value);
|
|
30
|
+
|
|
31
|
+
const first = await cache.fetch(options, fetcher);
|
|
32
|
+
const second = await cache.fetch(options, fetcher);
|
|
33
|
+
|
|
34
|
+
expect(first).toEqual({ value, cacheHit: false });
|
|
35
|
+
expect(second).toEqual({ value, cacheHit: true });
|
|
36
|
+
expect(first.value).toBe(value);
|
|
37
|
+
expect(second.value).toBe(value);
|
|
38
|
+
expect(fetcher).toHaveBeenCalledTimes(1);
|
|
39
|
+
});
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
it('uses equivalent object keys regardless of property order', async () => {
|
|
43
|
+
const fetcher = jest.fn().mockResolvedValue({ services: ['Cut'] });
|
|
44
|
+
const firstOptions = {
|
|
45
|
+
...options,
|
|
46
|
+
key: { agentId: 'agent-1', shopId: 'shop-1' },
|
|
47
|
+
};
|
|
48
|
+
const secondOptions = {
|
|
49
|
+
...options,
|
|
50
|
+
key: { shopId: 'shop-1', agentId: 'agent-1' },
|
|
51
|
+
};
|
|
52
|
+
|
|
53
|
+
await cache.fetch(firstOptions, fetcher);
|
|
54
|
+
const result = await cache.fetch(secondOptions, fetcher);
|
|
55
|
+
|
|
56
|
+
expect(result).toEqual({ value: { services: ['Cut'] }, cacheHit: true });
|
|
57
|
+
expect(fetcher).toHaveBeenCalledTimes(1);
|
|
58
|
+
});
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
it('fetches an expired value again', async () => {
|
|
62
|
+
jest.spyOn(Date, 'now').mockReturnValue(1000);
|
|
63
|
+
const fetcher = jest.fn()
|
|
64
|
+
.mockResolvedValueOnce({ version: 1 })
|
|
65
|
+
.mockResolvedValueOnce({ version: 2 });
|
|
66
|
+
await cache.fetch({ ...options, ttlSeconds: 1 }, fetcher);
|
|
67
|
+
|
|
68
|
+
Date.now.mockReturnValue(2000);
|
|
69
|
+
const result = await cache.fetch({ ...options, ttlSeconds: 1 }, fetcher);
|
|
70
|
+
|
|
71
|
+
expect(result).toEqual({ value: { version: 2 }, cacheHit: false });
|
|
72
|
+
expect(fetcher).toHaveBeenCalledTimes(2);
|
|
73
|
+
});
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
it('allows cached values to be mutated', async () => {
|
|
77
|
+
const value = { shop: { name: 'Original' } };
|
|
78
|
+
const fetcher = jest.fn().mockResolvedValue(value);
|
|
79
|
+
const first = await cache.fetch(options, fetcher);
|
|
80
|
+
first.value.shop.name = 'Changed by receiver';
|
|
81
|
+
|
|
82
|
+
const second = await cache.fetch(options, fetcher);
|
|
83
|
+
|
|
84
|
+
expect(second.value).toEqual({ shop: { name: 'Changed by receiver' } });
|
|
85
|
+
expect(second.value).toBe(first.value);
|
|
86
|
+
});
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
it('caches null values', async () => {
|
|
90
|
+
const fetcher = jest.fn().mockResolvedValue(null);
|
|
91
|
+
|
|
92
|
+
const first = await cache.fetch(options, fetcher);
|
|
93
|
+
const second = await cache.fetch(options, fetcher);
|
|
94
|
+
|
|
95
|
+
expect(first).toEqual({ value: null, cacheHit: false });
|
|
96
|
+
expect(second).toEqual({ value: null, cacheHit: true });
|
|
97
|
+
expect(fetcher).toHaveBeenCalledTimes(1);
|
|
98
|
+
});
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
it('shares one fetch between concurrent calls for the same key', async () => {
|
|
102
|
+
let resolveFetch;
|
|
103
|
+
const data = { shop: { name: 'Shop' } };
|
|
104
|
+
const fetcher = jest.fn(() => new Promise((resolve) => {
|
|
105
|
+
resolveFetch = resolve;
|
|
106
|
+
}));
|
|
107
|
+
|
|
108
|
+
const first = cache.fetch(options, fetcher);
|
|
109
|
+
const second = cache.fetch(options, fetcher);
|
|
110
|
+
resolveFetch(data);
|
|
111
|
+
const [firstResult, secondResult] = await Promise.all([first, second]);
|
|
112
|
+
|
|
113
|
+
expect(fetcher).toHaveBeenCalledTimes(1);
|
|
114
|
+
expect(firstResult).toEqual({ value: data, cacheHit: false });
|
|
115
|
+
expect(secondResult).toEqual({ value: data, cacheHit: false });
|
|
116
|
+
expect(firstResult.value).toBe(data);
|
|
117
|
+
expect(secondResult.value).toBe(data);
|
|
118
|
+
});
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
it('shares a fetch between equivalent key object order', async () => {
|
|
122
|
+
const fetcher = jest.fn().mockResolvedValue({ services: ['Cut'] });
|
|
123
|
+
const first = cache.fetch({
|
|
124
|
+
...options,
|
|
125
|
+
key: { agentId: 'agent-1', shopId: 'shop-1' },
|
|
126
|
+
}, fetcher);
|
|
127
|
+
const second = cache.fetch({
|
|
128
|
+
...options,
|
|
129
|
+
key: { shopId: 'shop-1', agentId: 'agent-1' },
|
|
130
|
+
}, fetcher);
|
|
131
|
+
|
|
132
|
+
await expect(Promise.all([first, second])).resolves.toEqual([
|
|
133
|
+
{ value: { services: ['Cut'] }, cacheHit: false },
|
|
134
|
+
{ value: { services: ['Cut'] }, cacheHit: false },
|
|
135
|
+
]);
|
|
136
|
+
expect(fetcher).toHaveBeenCalledTimes(1);
|
|
137
|
+
});
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
it('fetches different keys independently', async () => {
|
|
141
|
+
const firstFetcher = jest.fn().mockResolvedValue({ id: 1 });
|
|
142
|
+
const secondFetcher = jest.fn().mockResolvedValue({ id: 2 });
|
|
143
|
+
|
|
144
|
+
const results = await Promise.all([
|
|
145
|
+
cache.fetch({ ...options, key: 'first' }, firstFetcher),
|
|
146
|
+
cache.fetch({ ...options, key: 'second' }, secondFetcher),
|
|
147
|
+
]);
|
|
148
|
+
|
|
149
|
+
expect(results).toEqual([
|
|
150
|
+
{ value: { id: 1 }, cacheHit: false },
|
|
151
|
+
{ value: { id: 2 }, cacheHit: false },
|
|
152
|
+
]);
|
|
153
|
+
expect(firstFetcher).toHaveBeenCalledTimes(1);
|
|
154
|
+
expect(secondFetcher).toHaveBeenCalledTimes(1);
|
|
155
|
+
});
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
it('rejects concurrent calls and allows the fetch to be retried', async () => {
|
|
159
|
+
const fetcher = jest.fn()
|
|
160
|
+
.mockRejectedValueOnce(new Error('fetch failed'))
|
|
161
|
+
.mockResolvedValueOnce({ services: ['Cut'] });
|
|
162
|
+
const first = cache.fetch(options, fetcher);
|
|
163
|
+
const second = cache.fetch(options, fetcher);
|
|
164
|
+
|
|
165
|
+
await expect(Promise.all([first, second])).rejects.toThrow('fetch failed');
|
|
166
|
+
await expect(cache.fetch(options, fetcher)).resolves.toEqual({
|
|
167
|
+
value: { services: ['Cut'] },
|
|
168
|
+
cacheHit: false,
|
|
169
|
+
});
|
|
170
|
+
expect(fetcher).toHaveBeenCalledTimes(2);
|
|
171
|
+
});
|
|
172
|
+
|
|
173
|
+
|
|
174
|
+
it('evicts the least recently used value when full', async () => {
|
|
175
|
+
cache = new MemoryCache({ maxEntries: 2 });
|
|
176
|
+
const optionsFor = (key) => ({ ...options, key });
|
|
177
|
+
await cache.fetch(optionsFor('first'), async () => ({ value: 'first' }));
|
|
178
|
+
await cache.fetch(optionsFor('second'), async () => ({ value: 'second' }));
|
|
179
|
+
await cache.fetch(optionsFor('first'), async () => ({ value: 'unused' }));
|
|
180
|
+
await cache.fetch(optionsFor('third'), async () => ({ value: 'third' }));
|
|
181
|
+
const fetcher = jest.fn().mockResolvedValue({ value: 'new-second' });
|
|
182
|
+
|
|
183
|
+
const result = await cache.fetch(optionsFor('second'), fetcher);
|
|
184
|
+
|
|
185
|
+
expect(result).toEqual({ value: { value: 'new-second' }, cacheHit: false });
|
|
186
|
+
expect(fetcher).toHaveBeenCalledTimes(1);
|
|
187
|
+
});
|
|
188
|
+
|
|
189
|
+
|
|
190
|
+
it('removes expired values before evicting an active value', async () => {
|
|
191
|
+
cache = new MemoryCache({ maxEntries: 2 });
|
|
192
|
+
jest.spyOn(Date, 'now').mockReturnValue(1000);
|
|
193
|
+
await cache.fetch({ ...options, key: 'active' }, async () => ({ value: 'active' }));
|
|
194
|
+
await cache.fetch({ ...options, key: 'expired', ttlSeconds: 1 }, async () => ({ value: 'expired' }));
|
|
195
|
+
|
|
196
|
+
Date.now.mockReturnValue(2000);
|
|
197
|
+
await cache.fetch({ ...options, key: 'new' }, async () => ({ value: 'new' }));
|
|
198
|
+
const active = await cache.fetch({ ...options, key: 'active' }, async () => ({ value: 'unused' }));
|
|
199
|
+
|
|
200
|
+
expect(active).toEqual({ value: { value: 'active' }, cacheHit: true });
|
|
201
|
+
});
|
|
202
|
+
|
|
203
|
+
|
|
204
|
+
it('caches values that cannot be structured cloned', async () => {
|
|
205
|
+
const value = { fetch: () => 'value' };
|
|
206
|
+
|
|
207
|
+
const first = await cache.fetch(options, async () => value);
|
|
208
|
+
const second = await cache.fetch(options, jest.fn());
|
|
209
|
+
|
|
210
|
+
expect(first.value).toBe(value);
|
|
211
|
+
expect(second.value).toBe(value);
|
|
212
|
+
expect(second.value.fetch()).toBe('value');
|
|
213
|
+
});
|
|
214
|
+
|
|
215
|
+
|
|
216
|
+
it('requires a fetcher and valid options', async () => {
|
|
217
|
+
await expect(cache.fetch(options)).rejects.toThrow('MemoryCache fetcher must be a function.');
|
|
218
|
+
await expect(cache.fetch({ ...options, ttlSeconds: null }, jest.fn()))
|
|
219
|
+
.rejects.toThrow('ttlSeconds must be a positive integer');
|
|
220
|
+
await expect(cache.fetch()).rejects.toThrow('MemoryCache namespace is required.');
|
|
221
|
+
});
|
|
222
|
+
});
|
|
223
|
+
|
|
224
|
+
|
|
225
|
+
describe('constructor', () => {
|
|
226
|
+
it('requires a cache entry limit between 1 and 1000', () => {
|
|
227
|
+
expect(() => new MemoryCache({ maxEntries: 0 }))
|
|
228
|
+
.toThrow('MemoryCache maxEntries must be between 1 and 1000.');
|
|
229
|
+
expect(() => new MemoryCache({ maxEntries: 1001 }))
|
|
230
|
+
.toThrow('MemoryCache maxEntries must be between 1 and 1000.');
|
|
231
|
+
});
|
|
232
|
+
});
|
|
233
|
+
});
|