@elysiumjs/mnemosyne 0.1.0 → 0.2.0

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.
@@ -12,16 +12,15 @@
12
12
  // See the License for the specific language governing permissions and
13
13
  // limitations under the License.
14
14
 
15
- import { afterEach, beforeEach, describe, expect, it, jest, mock, spyOn } from 'bun:test';
16
-
17
- import { Application, Service } from '@elysiumjs/core';
15
+ import { Application, Service, ServiceNotFoundError } from '@elysiumjs/core';
16
+ import { afterEach, describe, expect, it, jest, mock, spyOn } from 'bun:test';
18
17
 
19
18
  import { AbstractDatabase } from '../src/database';
20
19
 
21
20
  const mockDriver = {
22
21
  createConnection: mock((config: any) => ({ mockConnection: true, config })),
23
22
  withTransaction: mock((conn: any, cb: any) => cb(conn)),
24
- getRawClient: mock((conn: any) => ({ rawClient: true })),
23
+ getRawClient: mock((_conn: any) => ({ rawClient: true }))
25
24
  };
26
25
 
27
26
  class TestDatabase extends AbstractDatabase<any, any> {
@@ -29,220 +28,85 @@ class TestDatabase extends AbstractDatabase<any, any> {
29
28
  }
30
29
 
31
30
  describe('AbstractDatabase', () => {
32
- // Mock console.error and process.exit to prevent actual console output and process exit
33
- const originalConsoleError = console.error;
34
- const originalProcessExit = process.exit;
35
-
36
- beforeEach(() => {
37
- console.error = mock();
38
- process.exit = mock() as any;
39
- });
40
-
41
31
  afterEach(() => {
42
- console.error = originalConsoleError;
43
- process.exit = originalProcessExit;
32
+ jest.restoreAllMocks();
44
33
  jest.clearAllMocks();
45
34
  });
46
35
 
47
- describe('registerConnection', () => {
48
- it('should register a new connection', () => {
49
- const db = new TestDatabase();
50
-
51
- // Mock Service.exists to return false (connection doesn't exist)
52
- const existsSpy = spyOn(Service, 'exists').mockReturnValueOnce(false);
53
- const instanceSpy = spyOn(Service, 'instance');
54
-
55
- // Call the function
56
- const result = db.registerConnection('test', { connection: 'sqlite:test.db' });
57
-
58
- // Check if Service.exists was called with the correct connection name
59
- expect(existsSpy).toHaveBeenCalledWith('db.connection.test');
60
-
61
- // Check if the driver's createConnection was called with the config
62
- expect(mockDriver.createConnection).toHaveBeenCalledWith({ connection: 'sqlite:test.db' });
63
-
64
- // Check if Service.instance was called with the correct parameters
65
- expect(instanceSpy).toHaveBeenCalledWith('db.connection.test', {
66
- mockConnection: true,
67
- config: { connection: 'sqlite:test.db' }
68
- });
69
- });
70
-
71
- it('should throw an error if the connection already exists', () => {
72
- const db = new TestDatabase();
73
-
74
- // Mock Service.exists to return true (connection exists)
75
- const existsSpy = spyOn(Service, 'exists').mockReturnValueOnce(true);
76
-
77
- // Call the function
78
- db.registerConnection('test', { connection: 'sqlite:test.db' });
79
-
80
- // Check if console.error and process.exit were called
81
- expect(console.error).toHaveBeenCalledWith(
82
- expect.stringContaining('A connection with the name test has already been registered')
83
- );
84
- expect(process.exit).toHaveBeenCalledWith(1);
85
- });
86
- });
87
-
88
36
  describe('getConnection', () => {
89
37
  it('should retrieve an existing connection', () => {
90
- const db = new TestDatabase();
91
-
92
- // Mock Service.exists to return true (connection exists)
93
- const existsSpy = spyOn(Service, 'exists').mockReturnValueOnce(true);
94
-
95
- // Mock Service.get to return a mock connection
96
38
  const mockConnection = { mockConnection: true };
97
39
  const getSpy = spyOn(Service, 'get').mockReturnValue(mockConnection);
98
40
 
99
- // Call the function
100
- const result = db.getConnection('test');
101
-
102
- // Check if Service.exists was called with the correct connection name
103
- expect(existsSpy).toHaveBeenCalledWith('db.connection.test');
41
+ const result = new TestDatabase().getConnection('test');
104
42
 
105
- // Check if Service.get was called with the correct connection name
106
43
  expect(getSpy).toHaveBeenCalledWith('db.connection.test');
107
-
108
- // Check if the result is correct
109
- expect(result as any).toEqual(mockConnection);
44
+ expect(result).toBe(mockConnection);
110
45
  });
111
46
 
112
- it('should throw an error if the connection does not exist', () => {
113
- const db = new TestDatabase();
47
+ it('should throw ServiceNotFoundError if the connection does not exist', () => {
48
+ spyOn(Service, 'get').mockReturnValue(null);
114
49
 
115
- // Mock Service.exists to return false (connection doesn't exist)
116
- const existsSpy = spyOn(Service, 'exists').mockReturnValueOnce(false);
50
+ expect(() => new TestDatabase().getConnection('test')).toThrow(ServiceNotFoundError);
51
+ });
117
52
 
118
- // Call the function
119
- db.getConnection('test');
53
+ it('should return the transaction handle for the default connection', () => {
54
+ const tx = { tx: true };
55
+ const originalDescriptor = Object.getOwnPropertyDescriptor(Application, 'context');
56
+ Object.defineProperty(Application, 'context', {
57
+ get: () => ({ getStore: () => new Map([['db:tx', tx]]) }),
58
+ configurable: true
59
+ });
120
60
 
121
- // Check if console.error and process.exit were called
122
- expect(console.error).toHaveBeenCalledWith(
123
- expect.stringContaining('No connection with name test found')
124
- );
125
- expect(process.exit).toHaveBeenCalledWith(1);
61
+ try {
62
+ expect(new TestDatabase().getConnection()).toBe(tx);
63
+ } finally {
64
+ if (originalDescriptor) Object.defineProperty(Application, 'context', originalDescriptor);
65
+ }
126
66
  });
127
67
  });
128
68
 
129
69
  describe('connectionExists', () => {
130
- it('should return true if the connection exists', () => {
131
- const db = new TestDatabase();
132
-
133
- // Mock Service.exists to return true
134
- const existsSpy = spyOn(Service, 'exists').mockReturnValueOnce(true);
135
-
136
- // Call the function
137
- const result = db.connectionExists('test');
138
-
139
- // Check if Service.exists was called with the correct connection name
140
- expect(existsSpy).toHaveBeenCalledWith('db.connection.test');
141
-
142
- // Check if the result is correct
143
- expect(result).toBe(true);
144
- });
145
-
146
- it('should return false if the connection does not exist', () => {
70
+ it('should delegate to Service.exists', () => {
71
+ const existsSpy = spyOn(Service, 'exists')
72
+ .mockReturnValueOnce(true)
73
+ .mockReturnValueOnce(false);
147
74
  const db = new TestDatabase();
148
75
 
149
- // Mock Service.exists to return false
150
- const existsSpy = spyOn(Service, 'exists').mockReturnValueOnce(false);
151
-
152
- // Call the function
153
- const result = db.connectionExists('test');
154
-
155
- // Check if Service.exists was called with the correct connection name
76
+ expect(db.connectionExists('test')).toBe(true);
77
+ expect(db.connectionExists('test')).toBe(false);
156
78
  expect(existsSpy).toHaveBeenCalledWith('db.connection.test');
157
-
158
- // Check if the result is correct
159
- expect(result).toBe(false);
160
79
  });
161
80
  });
162
81
 
163
82
  describe('getDefaultConnection', () => {
164
83
  it('should retrieve the default connection', () => {
165
- const db = new TestDatabase();
166
-
167
- // Save original descriptor and mock Application.context
168
- const originalDescriptor = Object.getOwnPropertyDescriptor(Application, 'context');
169
- Object.defineProperty(Application, 'context', {
170
- get: () => ({ getStore: () => null }),
171
- configurable: true,
172
- });
173
-
174
- // Mock Service.exists to return true and Service.get to return a mock connection
175
- const mockConnection = { mockConnection: true };
176
- spyOn(Service, 'exists').mockReturnValueOnce(true);
177
- spyOn(Service, 'get').mockReturnValue(mockConnection);
178
-
179
- // Call the function
180
- const result = db.getDefaultConnection();
181
-
182
- // Check if the result is correct
183
- expect(result as any).toEqual(mockConnection);
184
-
185
- // Restore original descriptor
186
- if (originalDescriptor) {
187
- Object.defineProperty(Application, 'context', originalDescriptor);
188
- }
189
- });
190
- });
191
-
192
- describe('setDefaultConnection', () => {
193
- it('should set the default connection', () => {
194
- const db = new TestDatabase();
195
-
196
- // Save original descriptor and mock Application.context
197
84
  const originalDescriptor = Object.getOwnPropertyDescriptor(Application, 'context');
198
85
  Object.defineProperty(Application, 'context', {
199
86
  get: () => ({ getStore: () => null }),
200
- configurable: true,
87
+ configurable: true
201
88
  });
202
89
 
203
- const instanceSpy = spyOn(Service, 'instance');
204
- const removeSpy = spyOn(Service, 'remove');
205
-
206
- // Mock getConnection to return a mock connection
207
- const mockConnection = { mockConnection: true };
208
- spyOn(Service, 'exists').mockReturnValue(true);
209
- spyOn(Service, 'get').mockReturnValue(mockConnection);
210
-
211
- // Call the function
212
- const result = db.setDefaultConnection('test');
213
-
214
- // Check if Service.remove was called with the correct connection name
215
- expect(removeSpy).toHaveBeenCalledWith('db.connection.default');
216
-
217
- // Check if Service.instance was called with the correct parameters
218
- expect(instanceSpy).toHaveBeenCalledWith('db.connection.default', mockConnection);
90
+ try {
91
+ const mockConnection = { mockConnection: true };
92
+ const getSpy = spyOn(Service, 'get').mockReturnValue(mockConnection);
219
93
 
220
- // Check if the result is correct
221
- expect(result as any).toEqual(mockConnection);
222
-
223
- // Restore original descriptor
224
- if (originalDescriptor) {
225
- Object.defineProperty(Application, 'context', originalDescriptor);
94
+ expect(new TestDatabase().getDefaultConnection()).toBe(mockConnection);
95
+ expect(getSpy).toHaveBeenCalledWith('db.connection.default');
96
+ } finally {
97
+ if (originalDescriptor) Object.defineProperty(Application, 'context', originalDescriptor);
226
98
  }
227
99
  });
228
100
  });
229
101
 
230
102
  describe('getRawClient', () => {
231
103
  it('should return the raw client from the driver', () => {
232
- const db = new TestDatabase();
233
-
234
- // Mock getConnection to return a mock connection
235
104
  const mockConnection = { mockConnection: true };
236
- spyOn(Service, 'exists').mockReturnValue(true);
237
105
  spyOn(Service, 'get').mockReturnValue(mockConnection);
238
106
 
239
- // Call the function
240
- const result = db.getRawClient('test');
107
+ const result = new TestDatabase().getRawClient('test');
241
108
 
242
- // Check if the driver's getRawClient was called with the connection
243
109
  expect(mockDriver.getRawClient).toHaveBeenCalledWith(mockConnection);
244
-
245
- // Check if the result is correct
246
110
  expect(result).toEqual({ rawClient: true });
247
111
  });
248
112
  });
@@ -0,0 +1,214 @@
1
+ // Copyright (c) 2026-present Workbud Technologies Inc. All rights reserved.
2
+ //
3
+ // Licensed under the Apache License, Version 2.0 (the "License");
4
+ // you may not use this file except in compliance with the License.
5
+ // You may obtain a copy of the License at
6
+ //
7
+ // http://www.apache.org/licenses/LICENSE-2.0
8
+ //
9
+ // Unless required by applicable law or agreed to in writing, software
10
+ // distributed under the License is distributed on an "AS IS" BASIS,
11
+ // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ // See the License for the specific language governing permissions and
13
+ // limitations under the License.
14
+
15
+ import type { TestingApp } from '@elysiumjs/core';
16
+
17
+ import { Application, RedisModule, Service, ServiceNotFoundError } from '@elysiumjs/core';
18
+ import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, mock } from 'bun:test';
19
+
20
+ import * as pkg from '../src';
21
+ import { Cache, MnemosyneModule } from '../src';
22
+ import { AbstractDatabase } from '../src/database';
23
+ import { KeyvRedis } from '../src/keyv-redis';
24
+ import { getTenancyConfig, getTenancyStrategy } from '../src/tenancy';
25
+
26
+ const store = new Map<string, string>();
27
+ const originalRedisClient = Bun.RedisClient;
28
+ const ClientMock = mock(function (_url: string, _options?: object) {
29
+ return {
30
+ close: mock(),
31
+ get: mock(async (k: string) => store.get(k) ?? null),
32
+ set: mock(async (k: string, v: string) => {
33
+ store.set(k, v);
34
+ return 'OK';
35
+ })
36
+ };
37
+ });
38
+ beforeAll(() => {
39
+ Bun.RedisClient = ClientMock as unknown as typeof Bun.RedisClient;
40
+ });
41
+
42
+ afterAll(() => {
43
+ Bun.RedisClient = originalRedisClient;
44
+ });
45
+
46
+ const redis = RedisModule.with({
47
+ default: 'cache',
48
+ connections: { cache: { url: 'redis://cache:6379' } }
49
+ });
50
+
51
+ class TestDatabase extends AbstractDatabase<any, any> {
52
+ protected driver = {
53
+ createConnection: mock(),
54
+ withTransaction: mock(),
55
+ getRawClient: mock()
56
+ } as any;
57
+ }
58
+
59
+ describe('MnemosyneModule', () => {
60
+ let app: TestingApp | undefined;
61
+
62
+ beforeEach(() => {
63
+ store.clear();
64
+ ClientMock.mockClear();
65
+ });
66
+
67
+ afterEach(async () => {
68
+ await app?.shutdown();
69
+ app = undefined;
70
+ });
71
+
72
+ it('registers nothing on import', () => {
73
+ expect(Service.exists('mnemosyne.cache.redis')).toBe(false);
74
+ expect(Service.exists('mnemosyne.cache.memory')).toBe(false);
75
+ expect(() => Cache.redis).toThrow(ServiceNotFoundError);
76
+ expect(() => Cache.memory).toThrow(ServiceNotFoundError);
77
+ });
78
+
79
+ it('exports the module', () => {
80
+ expect(pkg.MnemosyneModule).toBe(MnemosyneModule);
81
+ });
82
+
83
+ it('serves Cache.redis without opening a client until first use', async () => {
84
+ app = await Application.testing({ modules: [redis, MnemosyneModule] });
85
+ await app.get('mnemosyne.cache.redis');
86
+ const cache = Cache.redis;
87
+ expect(cache).toBeDefined();
88
+ expect(ClientMock).not.toHaveBeenCalled();
89
+
90
+ await cache.set('a', 'b');
91
+ expect(ClientMock).toHaveBeenCalledTimes(1);
92
+ expect(await cache.get('a')).toBe('b');
93
+ });
94
+
95
+ it('resolves the redis client through the async path on a lazy boot', async () => {
96
+ app = await Application.testing({ modules: [redis, MnemosyneModule], boot: 'lazy' });
97
+ await app.get('mnemosyne.cache.redis');
98
+ expect(await Cache.redis.get('missing')).toBeUndefined();
99
+ });
100
+
101
+ it('uses the configured redis connection', async () => {
102
+ app = await Application.testing({
103
+ modules: [
104
+ RedisModule.with({
105
+ default: 'other',
106
+ connections: { other: { url: 'redis://other:6379' } }
107
+ }),
108
+ MnemosyneModule.with({ cache: { redis: { connection: 'other' } } })
109
+ ]
110
+ });
111
+ await app.get('mnemosyne.cache.redis');
112
+ await Cache.redis.set('a', 'b');
113
+ expect(ClientMock).toHaveBeenCalledWith('redis://other:6379', {});
114
+ });
115
+
116
+ it('Cache.memory uses the configured TTL', async () => {
117
+ app = await Application.testing({
118
+ modules: [MnemosyneModule.with({ cache: { memory: { ttl: 40, lruSize: 10 } } })]
119
+ });
120
+ await app.get('mnemosyne.cache.memory');
121
+ await Cache.memory.set('k', 'v');
122
+ expect(await Cache.memory.get('k')).toBe('v');
123
+
124
+ await Bun.sleep(80);
125
+ expect(await Cache.memory.get('k')).toBeUndefined();
126
+ });
127
+
128
+ it('merges the defaults into a partial config', async () => {
129
+ app = await Application.testing({
130
+ modules: [MnemosyneModule.with({ cache: { memory: { ttl: 1000, lruSize: 10 } } })]
131
+ });
132
+ await app.get('mnemosyne.cache.memory');
133
+ expect(Service.exists('mnemosyne.cache.memory')).toBe(true);
134
+ expect(Service.exists('mnemosyne.cache.redis')).toBe(true);
135
+ });
136
+
137
+ it('registers no redis cache when it is set to false', async () => {
138
+ app = await Application.testing({
139
+ modules: [MnemosyneModule.with({ cache: { redis: false } })]
140
+ });
141
+ await app.get('mnemosyne.cache.memory');
142
+
143
+ expect(Service.exists('mnemosyne.cache.redis')).toBe(false);
144
+ expect(() => Cache.redis).toThrow(ServiceNotFoundError);
145
+ await Cache.memory.set('k', 'v');
146
+ expect(await Cache.memory.get('k')).toBe('v');
147
+ });
148
+
149
+ it('registers no memory cache when it is set to false', async () => {
150
+ app = await Application.testing({
151
+ modules: [redis, MnemosyneModule.with({ cache: { memory: false } })]
152
+ });
153
+ await app.get('mnemosyne.cache.redis');
154
+
155
+ expect(Service.exists('mnemosyne.cache.memory')).toBe(false);
156
+ expect(() => Cache.memory).toThrow(ServiceNotFoundError);
157
+ });
158
+
159
+ it('disconnect leaves the shared redis client open', async () => {
160
+ app = await Application.testing({ modules: [redis, MnemosyneModule] });
161
+ const client = (await app.get('redis.connection.cache')) as { close: ReturnType<typeof mock> };
162
+ const adapter = new KeyvRedis({ connection: 'cache' });
163
+
164
+ await adapter.set('a', 'b');
165
+ await adapter.disconnect();
166
+
167
+ expect(client.close).not.toHaveBeenCalled();
168
+ expect(ClientMock).toHaveBeenCalledTimes(1);
169
+ expect(await adapter.get('a')).toBe('b');
170
+ });
171
+
172
+ describe('tenancy', () => {
173
+ it('falls back to schema mode when no config is registered', async () => {
174
+ app = await Application.testing({ modules: [MnemosyneModule] });
175
+ expect(getTenancyConfig()).toEqual({ mode: 'schema' });
176
+ expect(getTenancyStrategy()).toBeNull();
177
+ });
178
+
179
+ it('reads the registered tenancy config', async () => {
180
+ app = await Application.testing({
181
+ modules: [MnemosyneModule],
182
+ overrides: { 'mnemosyne.tenancy.config': { mode: 'rls' } }
183
+ });
184
+ expect(getTenancyConfig()).toEqual({ mode: 'rls' });
185
+ });
186
+
187
+ it('reads the registered tenancy strategy', async () => {
188
+ const strategy = { name: 'test' };
189
+ app = await Application.testing({
190
+ modules: [MnemosyneModule],
191
+ overrides: { 'mnemosyne.tenancy.strategy': strategy }
192
+ });
193
+ expect(getTenancyStrategy()).toBe(strategy as any);
194
+ });
195
+ });
196
+
197
+ describe('AbstractDatabase', () => {
198
+ it('throws ServiceNotFoundError for a missing connection', async () => {
199
+ app = await Application.testing({ modules: [MnemosyneModule] });
200
+ expect(() => new TestDatabase().getConnection('missing')).toThrow(ServiceNotFoundError);
201
+ });
202
+
203
+ it('returns a registered connection', async () => {
204
+ const connection = { id: 1 };
205
+ app = await Application.testing({
206
+ modules: [MnemosyneModule],
207
+ overrides: { 'db.connection.main': connection }
208
+ });
209
+ const db = new TestDatabase();
210
+ expect(db.connectionExists('main')).toBe(true);
211
+ expect(db.getConnection('main')).toBe(connection);
212
+ });
213
+ });
214
+ });
package/tests/setup.ts CHANGED
@@ -11,16 +11,3 @@
11
11
  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
12
  // See the License for the specific language governing permissions and
13
13
  // limitations under the License.
14
-
15
- import 'reflect-metadata';
16
-
17
- import { mock } from 'bun:test';
18
-
19
- // Mock dependencies
20
-
21
- mock.module('node:async_hooks', () => ({
22
- AsyncLocalStorage: class {
23
- public run = mock((_map, callback) => callback());
24
- public disable = mock();
25
- }
26
- }));
@@ -1 +0,0 @@
1
- $ tsc --noEmit