-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathhttp-dispatcher.test.ts
More file actions
802 lines (675 loc) · 38.9 KB
/
Copy pathhttp-dispatcher.test.ts
File metadata and controls
802 lines (675 loc) · 38.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
import { describe, it, expect, vi, beforeEach } from 'vitest';
import { HttpDispatcher } from './http-dispatcher.js';
import { ObjectKernel } from '@objectstack/core';
describe('HttpDispatcher', () => {
let kernel: ObjectKernel;
let dispatcher: HttpDispatcher;
let mockProtocol: any;
let mockBroker: any;
beforeEach(() => {
// Mock Kernel
mockProtocol = {
saveMetaItem: vi.fn().mockResolvedValue({ success: true, message: 'Saved' }),
getMetaItem: vi.fn().mockResolvedValue({ success: true, item: { foo: 'bar' } })
};
mockBroker = {
call: vi.fn(),
};
kernel = {
broker: mockBroker,
context: {
getService: (name: string) => {
if (name === 'protocol') return mockProtocol;
return null;
}
}
} as any;
dispatcher = new HttpDispatcher(kernel);
});
describe('handleMetadata', () => {
it('should handle PUT /metadata/:type/:name by calling protocol.saveMetaItem', async () => {
const context = { request: {} };
const body = { label: 'New Label' };
const path = '/objects/my_obj';
const result = await dispatcher.handleMetadata(path, context, 'PUT', body);
expect(result.handled).toBe(true);
expect(result.response?.status).toBe(200);
expect(mockProtocol.saveMetaItem).toHaveBeenCalledWith({
type: 'objects',
name: 'my_obj',
item: body
});
expect(result.response?.body).toEqual({
success: true,
data: { success: true, message: 'Saved' },
meta: undefined
});
});
it('should fallback to broker call if protocol is missing saveMetaItem', async () => {
// Mock protocol without saveMetaItem
(kernel as any).context.getService = () => ({});
// Mock broker success
mockBroker.call.mockResolvedValue({ success: true, fromBroker: true });
const context = { request: {} };
const body = { label: 'Fallback' };
const path = '/objects/my_obj';
const result = await dispatcher.handleMetadata(path, context, 'PUT', body);
expect(result.handled).toBe(true);
expect(mockBroker.call).toHaveBeenCalledWith(
'metadata.saveItem',
{ type: 'objects', name: 'my_obj', item: body },
{ request: context.request }
);
expect(result.response?.body?.data).toEqual({ success: true, fromBroker: true });
});
it('should return error if save fails', async () => {
mockProtocol.saveMetaItem.mockRejectedValue(new Error('Save failed'));
const context = { request: {} };
const body = {};
const path = '/objects/bad_obj';
const result = await dispatcher.handleMetadata(path, context, 'PUT', body);
expect(result.handled).toBe(true);
expect(result.response?.status).toBe(400);
expect(result.response?.body?.error?.message).toBe('Save failed');
});
it('should handle READ operations as before', async () => {
mockBroker.call.mockResolvedValue({ name: 'my_obj' });
const context = { request: {} };
const result = await dispatcher.handleMetadata('/objects/my_obj', context, 'GET');
expect(result.handled).toBe(true);
expect(mockBroker.call).toHaveBeenCalledWith(
'metadata.getObject',
{ objectName: 'my_obj' },
{ request: context.request }
);
});
});
describe('handleAutomation', () => {
let mockAutomationService: any;
beforeEach(() => {
mockAutomationService = {
listFlows: vi.fn().mockResolvedValue(['flow_a', 'flow_b']),
getFlow: vi.fn().mockResolvedValue({ name: 'flow_a', label: 'Flow A' }),
registerFlow: vi.fn(),
unregisterFlow: vi.fn(),
execute: vi.fn().mockResolvedValue({ success: true, output: {} }),
toggleFlow: vi.fn().mockResolvedValue(undefined),
listRuns: vi.fn().mockResolvedValue([{ id: 'run_1', status: 'completed' }]),
getRun: vi.fn().mockResolvedValue({ id: 'run_1', status: 'completed' }),
trigger: vi.fn().mockResolvedValue({ success: true }),
};
// Set up kernel services to include automation
(kernel as any).services = new Map([
['automation', mockAutomationService],
]);
});
it('should list flows via GET /', async () => {
const result = await dispatcher.handleAutomation('', 'GET', {}, { request: {} });
expect(result.handled).toBe(true);
expect(result.response?.body?.data?.flows).toEqual(['flow_a', 'flow_b']);
});
it('should get a flow via GET /:name', async () => {
const result = await dispatcher.handleAutomation('flow_a', 'GET', {}, { request: {} });
expect(result.handled).toBe(true);
expect(result.response?.body?.data?.name).toBe('flow_a');
});
it('should return 404 for non-existent flow via GET /:name', async () => {
mockAutomationService.getFlow.mockResolvedValue(null);
const result = await dispatcher.handleAutomation('missing', 'GET', {}, { request: {} });
expect(result.handled).toBe(true);
expect(result.response?.status).toBe(404);
});
it('should create a flow via POST /', async () => {
const body = { name: 'new_flow', label: 'New Flow' };
const result = await dispatcher.handleAutomation('', 'POST', body, { request: {} });
expect(result.handled).toBe(true);
expect(mockAutomationService.registerFlow).toHaveBeenCalledWith('new_flow', body);
});
it('should update a flow via PUT /:name', async () => {
const body = { definition: { label: 'Updated' } };
const result = await dispatcher.handleAutomation('flow_a', 'PUT', body, { request: {} });
expect(result.handled).toBe(true);
expect(mockAutomationService.registerFlow).toHaveBeenCalledWith('flow_a', { label: 'Updated' });
});
it('should delete a flow via DELETE /:name', async () => {
const result = await dispatcher.handleAutomation('flow_a', 'DELETE', {}, { request: {} });
expect(result.handled).toBe(true);
expect(mockAutomationService.unregisterFlow).toHaveBeenCalledWith('flow_a');
expect(result.response?.body?.data?.deleted).toBe(true);
});
it('should trigger a flow via POST /:name/trigger', async () => {
const result = await dispatcher.handleAutomation('flow_a/trigger', 'POST', { key: 'val' }, { request: {} });
expect(result.handled).toBe(true);
expect(mockAutomationService.execute).toHaveBeenCalledWith('flow_a', { key: 'val' });
});
it('should toggle a flow via POST /:name/toggle', async () => {
const result = await dispatcher.handleAutomation('flow_a/toggle', 'POST', { enabled: false }, { request: {} });
expect(result.handled).toBe(true);
expect(mockAutomationService.toggleFlow).toHaveBeenCalledWith('flow_a', false);
});
it('should list runs via GET /:name/runs', async () => {
const result = await dispatcher.handleAutomation('flow_a/runs', 'GET', {}, { request: {} });
expect(result.handled).toBe(true);
expect(result.response?.body?.data?.runs).toHaveLength(1);
});
it('should get a run via GET /:name/runs/:runId', async () => {
const result = await dispatcher.handleAutomation('flow_a/runs/run_1', 'GET', {}, { request: {} });
expect(result.handled).toBe(true);
expect(result.response?.body?.data?.id).toBe('run_1');
});
it('should return 404 for non-existent run', async () => {
mockAutomationService.getRun.mockResolvedValue(null);
const result = await dispatcher.handleAutomation('flow_a/runs/missing', 'GET', {}, { request: {} });
expect(result.handled).toBe(true);
expect(result.response?.status).toBe(404);
});
it('should handle legacy trigger path POST /trigger/:name', async () => {
const result = await dispatcher.handleAutomation('trigger/flow_a', 'POST', { data: 1 }, { request: {} });
expect(result.handled).toBe(true);
expect(mockAutomationService.trigger).toHaveBeenCalledWith('flow_a', { data: 1 }, { request: {} });
});
});
// ═══════════════════════════════════════════════════════════════
// Async Service Resolution Tests
// Covers: getService awaits Promise-based (async factory) services
// ═══════════════════════════════════════════════════════════════
describe('Async service resolution (Promise-based injection)', () => {
describe('handleAnalytics with async service', () => {
it('should resolve analytics service from Promise (async factory)', async () => {
const mockAnalytics = {
query: vi.fn().mockResolvedValue({ rows: [{ id: 1 }], total: 1 }),
getMetadata: vi.fn().mockResolvedValue({ tables: ['t1'] }),
generateSql: vi.fn().mockResolvedValue({ sql: 'SELECT 1' }),
};
// Inject as Promise (simulates async factory registration)
(kernel as any).getService = vi.fn().mockImplementation((name: string) => {
if (name === 'analytics') return Promise.resolve(mockAnalytics);
return null;
});
const result = await dispatcher.handleAnalytics('query', 'POST', { sql: 'SELECT 1' }, { request: {} });
expect(result.handled).toBe(true);
expect(result.response?.status).toBe(200);
expect(mockAnalytics.query).toHaveBeenCalled();
});
it('should handle POST /analytics/sql with async service', async () => {
const mockAnalytics = {
generateSql: vi.fn().mockResolvedValue({ sql: 'SELECT * FROM t' }),
};
(kernel as any).getService = vi.fn().mockResolvedValue(mockAnalytics);
const result = await dispatcher.handleAnalytics('sql', 'POST', { object: 'test' }, { request: {} });
expect(result.handled).toBe(true);
expect(result.response?.status).toBe(200);
expect(mockAnalytics.generateSql).toHaveBeenCalled();
});
it('should handle GET /analytics/meta with async service', async () => {
const mockAnalytics = {
getMetadata: vi.fn().mockResolvedValue({ tables: ['users', 'orders'] }),
};
(kernel as any).getService = vi.fn().mockResolvedValue(mockAnalytics);
const result = await dispatcher.handleAnalytics('meta', 'GET', {}, { request: {} });
expect(result.handled).toBe(true);
expect(result.response?.status).toBe(200);
expect(result.response?.body?.data?.tables).toEqual(['users', 'orders']);
});
it('should return unhandled when analytics service is not registered', async () => {
(kernel as any).getService = vi.fn().mockResolvedValue(null);
(kernel as any).services = new Map();
const result = await dispatcher.handleAnalytics('query', 'POST', {}, { request: {} });
expect(result.handled).toBe(false);
});
it('should return unhandled for unknown analytics sub-path', async () => {
const mockAnalytics = { query: vi.fn() };
(kernel as any).getService = vi.fn().mockResolvedValue(mockAnalytics);
const result = await dispatcher.handleAnalytics('unknown', 'POST', {}, { request: {} });
expect(result.handled).toBe(false);
});
});
describe('handleAuth with async service', () => {
it('should resolve auth service from Promise', async () => {
const mockAuth = {
handler: vi.fn().mockResolvedValue({ user: { id: '1' } }),
};
(kernel as any).getService = vi.fn().mockImplementation((name: string) => {
if (name === 'auth') return Promise.resolve(mockAuth);
return null;
});
const result = await dispatcher.handleAuth('', 'POST', {}, { request: {}, response: {} });
expect(result.handled).toBe(true);
expect(mockAuth.handler).toHaveBeenCalled();
});
it('should fallback to legacy login when async auth service has no handler', async () => {
(kernel as any).getService = vi.fn().mockResolvedValue({});
mockBroker.call.mockResolvedValue({ token: 'abc' });
const result = await dispatcher.handleAuth('/login', 'POST', { user: 'a' }, { request: {} });
expect(result.handled).toBe(true);
expect(mockBroker.call).toHaveBeenCalledWith('auth.login', { user: 'a' }, { request: {} });
});
it('should return unhandled when auth service not registered and no legacy match', async () => {
(kernel as any).getService = vi.fn().mockResolvedValue(null);
(kernel as any).services = new Map();
const result = await dispatcher.handleAuth('/profile', 'GET', {}, { request: {} });
expect(result.handled).toBe(false);
});
});
describe('handleStorage with async service', () => {
it('should resolve storage service from Promise', async () => {
const mockStorage = {
upload: vi.fn().mockResolvedValue({ id: 'file_1', url: '/files/1' }),
};
(kernel as any).getService = vi.fn().mockImplementation((name: string) => {
if (name === 'file-storage') return Promise.resolve(mockStorage);
return null;
});
const result = await dispatcher.handleStorage('/upload', 'POST', { name: 'test.txt' }, { request: {} });
expect(result.handled).toBe(true);
expect(result.response?.status).toBe(200);
expect(mockStorage.upload).toHaveBeenCalled();
});
it('should return 501 when storage service is not registered (async null)', async () => {
(kernel as any).getService = vi.fn().mockResolvedValue(null);
(kernel as any).services = new Map();
const result = await dispatcher.handleStorage('/upload', 'POST', {}, { request: {} });
expect(result.handled).toBe(true);
expect(result.response?.status).toBe(501);
expect(result.response?.body?.error?.message).toBe('File storage not configured');
});
it('should handle GET /storage/file/:id with async service', async () => {
const mockStorage = {
download: vi.fn().mockResolvedValue({ data: 'content', mimeType: 'text/plain' }),
};
(kernel as any).getService = vi.fn().mockImplementation((name: string) => {
if (name === 'file-storage') return Promise.resolve(mockStorage);
return null;
});
const result = await dispatcher.handleStorage('/file/abc123', 'GET', null, { request: {} });
expect(result.handled).toBe(true);
expect(mockStorage.download).toHaveBeenCalledWith('abc123', { request: {} });
});
it('should return 400 when upload has no file', async () => {
const mockStorage = { upload: vi.fn() };
(kernel as any).getService = vi.fn().mockResolvedValue(mockStorage);
const result = await dispatcher.handleStorage('/upload', 'POST', null, { request: {} });
expect(result.handled).toBe(true);
expect(result.response?.status).toBe(400);
expect(result.response?.body?.error?.message).toBe('No file provided');
});
});
describe('handleAutomation with async service', () => {
it('should resolve automation service from Promise (async factory)', async () => {
const mockAuto = {
listFlows: vi.fn().mockResolvedValue(['f1']),
};
(kernel as any).getService = vi.fn().mockImplementation((name: string) => {
if (name === 'automation') return Promise.resolve(mockAuto);
return null;
});
const result = await dispatcher.handleAutomation('', 'GET', {}, { request: {} });
expect(result.handled).toBe(true);
expect(result.response?.body?.data?.flows).toEqual(['f1']);
});
it('should return unhandled when automation service not registered', async () => {
(kernel as any).getService = vi.fn().mockResolvedValue(null);
(kernel as any).services = new Map();
const result = await dispatcher.handleAutomation('', 'GET', {}, { request: {} });
expect(result.handled).toBe(false);
});
});
describe('handleMetadata with async protocol service', () => {
it('should resolve protocol service from async getService', async () => {
const asyncProtocol = {
saveMetaItem: vi.fn().mockResolvedValue({ success: true }),
};
(kernel as any).context.getService = vi.fn().mockImplementation((name: string) => {
if (name === 'protocol') return Promise.resolve(asyncProtocol);
return null;
});
const result = await dispatcher.handleMetadata('/objects/my_obj', { request: {} }, 'PUT', { label: 'Test' });
expect(result.handled).toBe(true);
expect(result.response?.status).toBe(200);
expect(asyncProtocol.saveMetaItem).toHaveBeenCalled();
});
it('should fallback to broker when async protocol returns null', async () => {
(kernel as any).context.getService = vi.fn().mockResolvedValue(null);
mockBroker.call.mockResolvedValue({ name: 'my_obj' });
const result = await dispatcher.handleMetadata('/objects/my_obj', { request: {} }, 'GET');
expect(result.handled).toBe(true);
expect(mockBroker.call).toHaveBeenCalledWith(
'metadata.getObject',
{ objectName: 'my_obj' },
{ request: {} }
);
});
});
});
// ═══════════════════════════════════════════════════════════════
// Synchronous service resolution (backward compatibility)
// ═══════════════════════════════════════════════════════════════
describe('Synchronous service resolution (backward compat)', () => {
it('should work with synchronous service from services Map', async () => {
const syncAnalytics = {
query: vi.fn().mockResolvedValue({ rows: [], total: 0 }),
};
(kernel as any).services = new Map([['analytics', syncAnalytics]]);
const result = await dispatcher.handleAnalytics('query', 'POST', {}, { request: {} });
expect(result.handled).toBe(true);
expect(syncAnalytics.query).toHaveBeenCalled();
});
it('should work with synchronous getService returning service directly', async () => {
const syncAuto = {
listFlows: vi.fn().mockResolvedValue(['flow_x']),
};
(kernel as any).getService = vi.fn().mockReturnValue(syncAuto);
const result = await dispatcher.handleAutomation('', 'GET', {}, { request: {} });
expect(result.handled).toBe(true);
expect(result.response?.body?.data?.flows).toEqual(['flow_x']);
});
});
// ═══════════════════════════════════════════════════════════════
// handleData — expand/populate parameter flow
// ═══════════════════════════════════════════════════════════════
describe('handleData', () => {
it('should pass expand and select to broker for GET /data/:object/:id', async () => {
mockBroker.call.mockResolvedValue({ object: 'order_item', id: 'oi_1', record: { _id: 'oi_1' } });
const result = await dispatcher.handleData(
'/order_item/oi_1', 'GET', {},
{ expand: 'order,product', select: 'name,total' },
{ request: {} }
);
expect(result.handled).toBe(true);
expect(result.response?.status).toBe(200);
expect(mockBroker.call).toHaveBeenCalledWith(
'data.get',
{ object: 'order_item', id: 'oi_1', expand: 'order,product', select: 'name,total' },
{ request: {} }
);
});
it('should NOT pass non-allowlisted params for GET /data/:object/:id', async () => {
mockBroker.call.mockResolvedValue({ object: 'task', id: 't1', record: {} });
await dispatcher.handleData(
'/task/t1', 'GET', {},
{ expand: 'assignee', malicious: 'drop_table', filter: 'hack' },
{ request: {} }
);
// Only expand is passed; malicious and filter are dropped
expect(mockBroker.call).toHaveBeenCalledWith(
'data.get',
{ object: 'task', id: 't1', expand: 'assignee' },
{ request: {} }
);
});
it('should pass full query (with expand/populate) for GET /data/:object list', async () => {
mockBroker.call.mockResolvedValue({ object: 'task', records: [], total: 0 });
const query = { populate: 'assignee,project', top: '10', skip: '0' };
const result = await dispatcher.handleData(
'/task', 'GET', {},
query,
{ request: {} }
);
expect(result.handled).toBe(true);
expect(mockBroker.call).toHaveBeenCalledWith(
'data.query',
{ object: 'task', query },
{ request: {} }
);
});
it('should pass expand in query for GET /data/:object list', async () => {
mockBroker.call.mockResolvedValue({ object: 'order', records: [], total: 0 });
const query = { expand: 'customer,products' };
await dispatcher.handleData('/order', 'GET', {}, query, { request: {} });
expect(mockBroker.call).toHaveBeenCalledWith(
'data.query',
{ object: 'order', query: { expand: 'customer,products' } },
{ request: {} }
);
});
it('should return error if object name is missing', async () => {
const result = await dispatcher.handleData('/', 'GET', {}, {}, { request: {} });
expect(result.handled).toBe(true);
expect(result.response?.status).toBe(400);
});
it('should handle POST /data/:object/query with body containing expand', async () => {
mockBroker.call.mockResolvedValue({ object: 'task', records: [] });
await dispatcher.handleData(
'/task/query', 'POST',
{ filter: { status: 'active' }, populate: ['assignee'] },
{},
{ request: {} }
);
expect(mockBroker.call).toHaveBeenCalledWith(
'data.query',
{ object: 'task', filter: { status: 'active' }, populate: ['assignee'] },
{ request: {} }
);
});
});
// ═══════════════════════════════════════════════════════════════
// Error handling for service method failures
// ═══════════════════════════════════════════════════════════════
describe('Service method error handling', () => {
it('should propagate analytics query error', async () => {
const badAnalytics = {
query: vi.fn().mockRejectedValue(new Error('Query timeout')),
};
(kernel as any).getService = vi.fn().mockResolvedValue(badAnalytics);
await expect(
dispatcher.handleAnalytics('query', 'POST', {}, { request: {} })
).rejects.toThrow('Query timeout');
});
it('should propagate storage upload error', async () => {
const badStorage = {
upload: vi.fn().mockRejectedValue(new Error('Disk full')),
};
(kernel as any).getService = vi.fn().mockImplementation((name: string) => {
if (name === 'file-storage') return Promise.resolve(badStorage);
return null;
});
await expect(
dispatcher.handleStorage('/upload', 'POST', { data: 'file' }, { request: {} })
).rejects.toThrow('Disk full');
});
});
// ═══════════════════════════════════════════════════════════════
// Package Publish / Revert Endpoints
// ═══════════════════════════════════════════════════════════════
describe('Package publish/revert endpoints', () => {
it('should handle POST /packages/:id/publish via metadata service', async () => {
const mockMetadata = {
publishPackage: vi.fn().mockResolvedValue({
success: true,
packageId: 'com.acme.crm',
version: 2,
publishedAt: '2025-06-01T00:00:00Z',
itemsPublished: 3,
}),
};
const mockRegistry = {
getAllPackages: vi.fn().mockReturnValue([]),
enablePackage: vi.fn(),
disablePackage: vi.fn(),
};
(kernel as any).getService = vi.fn().mockImplementation((name: string) => {
if (name === 'metadata') return Promise.resolve(mockMetadata);
if (name === 'objectql') return Promise.resolve({ registry: mockRegistry });
return null;
});
const result = await dispatcher.handlePackages('/com.acme.crm/publish', 'POST', { publishedBy: 'admin' }, {}, { request: {} });
expect(result.handled).toBe(true);
expect(result.response?.status).toBe(200);
expect(mockMetadata.publishPackage).toHaveBeenCalledWith('com.acme.crm', { publishedBy: 'admin' });
});
it('should handle POST /packages/:id/revert via metadata service', async () => {
const mockMetadata = {
revertPackage: vi.fn().mockResolvedValue(undefined),
};
const mockRegistry = {
getAllPackages: vi.fn().mockReturnValue([]),
enablePackage: vi.fn(),
disablePackage: vi.fn(),
};
(kernel as any).getService = vi.fn().mockImplementation((name: string) => {
if (name === 'metadata') return Promise.resolve(mockMetadata);
if (name === 'objectql') return Promise.resolve({ registry: mockRegistry });
return null;
});
const result = await dispatcher.handlePackages('/com.acme.crm/revert', 'POST', {}, {}, { request: {} });
expect(result.handled).toBe(true);
expect(result.response?.status).toBe(200);
expect(mockMetadata.revertPackage).toHaveBeenCalledWith('com.acme.crm');
});
it('should fallback to broker for publish when metadata service unavailable', async () => {
const mockRegistry = {
getAllPackages: vi.fn().mockReturnValue([]),
};
(kernel as any).getService = vi.fn().mockImplementation((name: string) => {
if (name === 'metadata') return Promise.resolve(null);
if (name === 'objectql') return Promise.resolve({ registry: mockRegistry });
return null;
});
mockBroker.call.mockResolvedValue({ success: true, packageId: 'crm', version: 1, publishedAt: '2025-01-01T00:00:00Z', itemsPublished: 2 });
const result = await dispatcher.handlePackages('/crm/publish', 'POST', {}, {}, { request: {} });
expect(result.handled).toBe(true);
expect(mockBroker.call).toHaveBeenCalledWith('metadata.publishPackage', { packageId: 'crm' }, { request: {} });
});
});
// ═══════════════════════════════════════════════════════════════
// Metadata getPublished Endpoint
// ═══════════════════════════════════════════════════════════════
describe('Metadata getPublished endpoint', () => {
it('should handle GET /metadata/:type/:name/published via metadata service', async () => {
const mockMetadata = {
getPublished: vi.fn().mockResolvedValue({ name: 'account', label: 'Account' }),
};
(kernel as any).getService = vi.fn().mockImplementation((name: string) => {
if (name === 'metadata') return Promise.resolve(mockMetadata);
return null;
});
const result = await dispatcher.handleMetadata('/object/account/published', { request: {} }, 'GET');
expect(result.handled).toBe(true);
expect(result.response?.status).toBe(200);
expect(result.response?.body?.data).toEqual({ name: 'account', label: 'Account' });
expect(mockMetadata.getPublished).toHaveBeenCalledWith('object', 'account');
});
it('should return 404 when published item not found', async () => {
const mockMetadata = {
getPublished: vi.fn().mockResolvedValue(undefined),
};
(kernel as any).getService = vi.fn().mockImplementation((name: string) => {
if (name === 'metadata') return Promise.resolve(mockMetadata);
return null;
});
const result = await dispatcher.handleMetadata('/object/nonexistent/published', { request: {} }, 'GET');
expect(result.handled).toBe(true);
expect(result.response?.status).toBe(404);
});
it('should fallback to broker for getPublished when metadata service unavailable', async () => {
(kernel as any).getService = vi.fn().mockResolvedValue(null);
mockBroker.call.mockResolvedValue({ name: 'account', fields: ['name'] });
const result = await dispatcher.handleMetadata('/object/account/published', { request: {} }, 'GET');
expect(result.handled).toBe(true);
expect(result.response?.status).toBe(200);
expect(mockBroker.call).toHaveBeenCalledWith(
'metadata.getPublished',
{ type: 'object', name: 'account' },
{ request: {} }
);
});
});
// ═══════════════════════════════════════════════════════════════
// handleI18n — i18n route dispatching
// ═══════════════════════════════════════════════════════════════
describe('handleI18n', () => {
let mockI18nService: any;
beforeEach(() => {
mockI18nService = {
getLocales: vi.fn().mockReturnValue(['en', 'zh-CN', 'ja']),
getTranslations: vi.fn().mockReturnValue({ 'o.account.label': '客户', 'o.account.fields.name': '名称' }),
getFieldLabels: vi.fn().mockReturnValue({ name: '名称', industry: '行业' }),
};
(kernel as any).getService = vi.fn().mockImplementation((name: string) => {
if (name === 'i18n') return mockI18nService;
return null;
});
});
it('should list locales via GET /locales', async () => {
const result = await dispatcher.handleI18n('/locales', 'GET', {}, { request: {} });
expect(result.handled).toBe(true);
expect(result.response?.status).toBe(200);
expect(result.response?.body?.data?.locales).toEqual(['en', 'zh-CN', 'ja']);
expect(mockI18nService.getLocales).toHaveBeenCalled();
});
it('should get translations via GET /translations/:locale', async () => {
const result = await dispatcher.handleI18n('/translations/zh-CN', 'GET', {}, { request: {} });
expect(result.handled).toBe(true);
expect(result.response?.status).toBe(200);
expect(result.response?.body?.data?.locale).toBe('zh-CN');
expect(result.response?.body?.data?.translations).toEqual({ 'o.account.label': '客户', 'o.account.fields.name': '名称' });
expect(mockI18nService.getTranslations).toHaveBeenCalledWith('zh-CN');
});
it('should get translations via GET /translations?locale=zh-CN (query param)', async () => {
const result = await dispatcher.handleI18n('/translations', 'GET', { locale: 'zh-CN' }, { request: {} });
expect(result.handled).toBe(true);
expect(result.response?.status).toBe(200);
expect(result.response?.body?.data?.locale).toBe('zh-CN');
expect(mockI18nService.getTranslations).toHaveBeenCalledWith('zh-CN');
});
it('should return 400 when translations requested without locale', async () => {
const result = await dispatcher.handleI18n('/translations', 'GET', {}, { request: {} });
expect(result.handled).toBe(true);
expect(result.response?.status).toBe(400);
expect(result.response?.body?.error?.message).toBe('Missing locale parameter');
});
it('should get field labels via GET /labels/:object/:locale', async () => {
const result = await dispatcher.handleI18n('/labels/account/zh-CN', 'GET', {}, { request: {} });
expect(result.handled).toBe(true);
expect(result.response?.status).toBe(200);
expect(result.response?.body?.data?.object).toBe('account');
expect(result.response?.body?.data?.locale).toBe('zh-CN');
expect(result.response?.body?.data?.labels).toEqual({ name: '名称', industry: '行业' });
expect(mockI18nService.getFieldLabels).toHaveBeenCalledWith('account', 'zh-CN');
});
it('should get field labels via GET /labels/:object?locale=zh-CN (query param)', async () => {
const result = await dispatcher.handleI18n('/labels/account', 'GET', { locale: 'zh-CN' }, { request: {} });
expect(result.handled).toBe(true);
expect(result.response?.status).toBe(200);
expect(result.response?.body?.data?.object).toBe('account');
expect(mockI18nService.getFieldLabels).toHaveBeenCalledWith('account', 'zh-CN');
});
it('should return 400 when labels requested without locale', async () => {
const result = await dispatcher.handleI18n('/labels/account', 'GET', {}, { request: {} });
expect(result.handled).toBe(true);
expect(result.response?.status).toBe(400);
expect(result.response?.body?.error?.message).toBe('Missing locale parameter');
});
it('should fallback to deriving labels from translations when getFieldLabels is missing', async () => {
delete mockI18nService.getFieldLabels;
mockI18nService.getTranslations.mockReturnValue({
'o.contact.fields.first_name': 'First Name',
'o.contact.fields.email': 'Email',
'o.contact.label': 'Contact',
});
const result = await dispatcher.handleI18n('/labels/contact/en', 'GET', {}, { request: {} });
expect(result.handled).toBe(true);
expect(result.response?.status).toBe(200);
expect(result.response?.body?.data?.labels).toEqual({
first_name: 'First Name',
email: 'Email',
});
});
it('should return 501 when i18n service is not available', async () => {
(kernel as any).getService = vi.fn().mockResolvedValue(null);
(kernel as any).services = new Map();
const result = await dispatcher.handleI18n('/locales', 'GET', {}, { request: {} });
expect(result.handled).toBe(true);
expect(result.response?.status).toBe(501);
});
it('should return unhandled for non-GET methods', async () => {
const result = await dispatcher.handleI18n('/locales', 'POST', {}, { request: {} });
expect(result.handled).toBe(false);
});
it('should dispatch /i18n routes via dispatch()', async () => {
const result = await dispatcher.dispatch('GET', '/i18n/locales', undefined, {}, { request: {} });
expect(result.handled).toBe(true);
expect(result.response?.body?.data?.locales).toEqual(['en', 'zh-CN', 'ja']);
});
});
});