-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathprotocol-data.test.ts
More file actions
491 lines (424 loc) · 20.7 KB
/
Copy pathprotocol-data.test.ts
File metadata and controls
491 lines (424 loc) · 20.7 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
// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.
import { describe, it, expect, vi, beforeEach } from 'vitest';
import { ObjectStackProtocolImplementation } from './protocol.js';
/**
* Tests for the Protocol Implementation's data methods (findData, getData).
* Validates that expand/populate/select parameters are correctly normalized
* and forwarded to the underlying engine.
*/
describe('ObjectStackProtocolImplementation - Data Operations', () => {
let protocol: ObjectStackProtocolImplementation;
let mockEngine: any;
beforeEach(() => {
mockEngine = {
find: vi.fn().mockResolvedValue([]),
findOne: vi.fn().mockResolvedValue(null),
};
protocol = new ObjectStackProtocolImplementation(mockEngine);
});
// ═══════════════════════════════════════════════════════════════
// findData — expand/populate normalization
// ═══════════════════════════════════════════════════════════════
describe('findData', () => {
it('should normalize $expand (OData) string to expand Record', async () => {
await protocol.findData({ object: 'order_item', query: { $expand: 'order,product' } });
expect(mockEngine.find).toHaveBeenCalledWith(
'order_item',
expect.objectContaining({
expand: { order: { object: 'order' }, product: { object: 'product' } },
}),
);
// $expand should be deleted from options
const callArgs = mockEngine.find.mock.calls[0][1];
expect(callArgs.$expand).toBeUndefined();
});
it('should normalize $expand (OData) with different fields to expand Record', async () => {
await protocol.findData({ object: 'task', query: { $expand: 'assignee,project' } });
expect(mockEngine.find).toHaveBeenCalledWith(
'task',
expect.objectContaining({
expand: { assignee: { object: 'assignee' }, project: { object: 'project' } },
}),
);
});
it('should normalize populate array to expand Record', async () => {
await protocol.findData({ object: 'task', query: { populate: ['assignee'] } });
expect(mockEngine.find).toHaveBeenCalledWith(
'task',
expect.objectContaining({
expand: { assignee: { object: 'assignee' } },
}),
);
});
it('should normalize populate string to expand Record', async () => {
await protocol.findData({ object: 'task', query: { populate: 'assignee,project' } });
expect(mockEngine.find).toHaveBeenCalledWith(
'task',
expect.objectContaining({
expand: { assignee: { object: 'assignee' }, project: { object: 'project' } },
}),
);
});
it('should prefer populate names over expand string when both provided', async () => {
await protocol.findData({
object: 'task',
query: { populate: ['assignee'], expand: 'project' },
});
// populate names take precedence; the non-object expand string is
// cleaned up first, then populate-derived names create the Record.
const callArgs = mockEngine.find.mock.calls[0][1];
expect(callArgs.populate).toBeUndefined();
expect(callArgs.$expand).toBeUndefined();
expect(callArgs.expand).toEqual({ assignee: { object: 'assignee' } });
});
it('should pass expand Record object through as-is', async () => {
await protocol.findData({
object: 'task',
query: { expand: { owner: { object: 'owner' }, team: { object: 'team' } } },
});
expect(mockEngine.find).toHaveBeenCalledWith(
'task',
expect.objectContaining({
expand: { owner: { object: 'owner' }, team: { object: 'team' } },
}),
);
});
it('should normalize select string to fields array', async () => {
await protocol.findData({ object: 'task', query: { select: 'name,status,assignee' } });
expect(mockEngine.find).toHaveBeenCalledWith(
'task',
expect.objectContaining({
fields: ['name', 'status', 'assignee'],
}),
);
});
it('should pass numeric pagination params correctly', async () => {
await protocol.findData({ object: 'task', query: { top: '10', skip: '20' } });
expect(mockEngine.find).toHaveBeenCalledWith(
'task',
expect.objectContaining({
limit: 10,
offset: 20,
}),
);
});
it('should work with no query options', async () => {
await protocol.findData({ object: 'task' });
expect(mockEngine.find).toHaveBeenCalledWith('task', {});
});
it('should return records and standard response shape', async () => {
mockEngine.find.mockResolvedValue([{ id: 't1', name: 'Task 1' }]);
const result = await protocol.findData({ object: 'task', query: {} });
expect(result).toEqual(
expect.objectContaining({
object: 'task',
records: [{ id: 't1', name: 'Task 1' }],
total: 1,
}),
);
});
});
// ═══════════════════════════════════════════════════════════════
// getData — expand/select normalization
// ═══════════════════════════════════════════════════════════════
describe('getData', () => {
it('should convert expand string to expand Record', async () => {
mockEngine.findOne.mockResolvedValue({ id: 'oi_1', name: 'Item 1' });
await protocol.getData({ object: 'order_item', id: 'oi_1', expand: 'order,product' });
expect(mockEngine.findOne).toHaveBeenCalledWith(
'order_item',
expect.objectContaining({
where: { id: 'oi_1' },
expand: { order: { object: 'order' }, product: { object: 'product' } },
}),
);
});
it('should convert expand array to expand Record', async () => {
mockEngine.findOne.mockResolvedValue({ id: 't1' });
await protocol.getData({ object: 'task', id: 't1', expand: ['assignee', 'project'] });
expect(mockEngine.findOne).toHaveBeenCalledWith(
'task',
expect.objectContaining({
where: { id: 't1' },
expand: { assignee: { object: 'assignee' }, project: { object: 'project' } },
}),
);
});
it('should convert select string to fields array', async () => {
mockEngine.findOne.mockResolvedValue({ id: 't1', name: 'Test' });
await protocol.getData({ object: 'task', id: 't1', select: 'name,status' });
expect(mockEngine.findOne).toHaveBeenCalledWith(
'task',
expect.objectContaining({
where: { id: 't1' },
fields: ['name', 'status'],
}),
);
});
it('should pass both expand and fields together', async () => {
mockEngine.findOne.mockResolvedValue({ id: 'oi_1' });
await protocol.getData({
object: 'order_item',
id: 'oi_1',
expand: 'order',
select: ['name', 'total'],
});
expect(mockEngine.findOne).toHaveBeenCalledWith(
'order_item',
expect.objectContaining({
where: { id: 'oi_1' },
expand: { order: { object: 'order' } },
fields: ['name', 'total'],
}),
);
});
it('should work without expand or select', async () => {
mockEngine.findOne.mockResolvedValue({ id: 't1' });
await protocol.getData({ object: 'task', id: 't1' });
expect(mockEngine.findOne).toHaveBeenCalledWith(
'task',
{ where: { id: 't1' } },
);
});
it('should return standard GetDataResponse shape', async () => {
mockEngine.findOne.mockResolvedValue({ id: 'oi_1', name: 'Item 1' });
const result = await protocol.getData({ object: 'order_item', id: 'oi_1' });
expect(result).toEqual({
object: 'order_item',
id: 'oi_1',
record: { id: 'oi_1', name: 'Item 1' },
});
});
it('should throw when record not found', async () => {
mockEngine.findOne.mockResolvedValue(null);
await expect(
protocol.getData({ object: 'task', id: 'missing_id' })
).rejects.toThrow('not found');
});
});
// ═══════════════════════════════════════════════════════════════
// Optimistic Concurrency Control — updateData / deleteData
// ═══════════════════════════════════════════════════════════════
describe('Optimistic Concurrency Control', () => {
beforeEach(() => {
// Both update and delete need `update` / `delete` on the
// engine, plus `findOne` for the version probe.
mockEngine.update = vi.fn().mockResolvedValue({ id: 'r1', updated_at: '2026-05-22T07:14:33.000Z' });
mockEngine.delete = vi.fn().mockResolvedValue(true);
});
it('updateData proceeds when no expectedVersion is supplied (legacy callers)', async () => {
await protocol.updateData({ object: 'task', id: 'r1', data: { name: 'New' } });
// No version probe was issued
expect(mockEngine.findOne).not.toHaveBeenCalled();
expect(mockEngine.update).toHaveBeenCalledOnce();
});
it('updateData proceeds when expectedVersion matches current updated_at', async () => {
mockEngine.findOne.mockResolvedValue({ id: 'r1', updated_at: '2026-05-22T07:14:00.000Z' });
await protocol.updateData({
object: 'task',
id: 'r1',
data: { name: 'New' },
expectedVersion: '2026-05-22T07:14:00.000Z',
});
expect(mockEngine.findOne).toHaveBeenCalledOnce();
expect(mockEngine.update).toHaveBeenCalledOnce();
});
it('updateData strips RFC-7232 quotes from the If-Match token', async () => {
mockEngine.findOne.mockResolvedValue({ id: 'r1', updated_at: '2026-05-22T07:14:00.000Z' });
await protocol.updateData({
object: 'task',
id: 'r1',
data: { name: 'New' },
expectedVersion: '"2026-05-22T07:14:00.000Z"',
});
expect(mockEngine.update).toHaveBeenCalledOnce();
});
it('updateData throws ConcurrentUpdateError when versions differ', async () => {
mockEngine.findOne.mockResolvedValue({
id: 'r1',
updated_at: '2026-05-22T07:14:00.000Z',
name: 'Server side',
});
await expect(
protocol.updateData({
object: 'task',
id: 'r1',
data: { name: 'My change' },
expectedVersion: '2026-05-22T07:00:00.000Z',
})
).rejects.toMatchObject({
name: 'ConcurrentUpdateError',
code: 'CONCURRENT_UPDATE',
status: 409,
currentVersion: '2026-05-22T07:14:00.000Z',
currentRecord: expect.objectContaining({ id: 'r1', name: 'Server side' }),
});
// update was NOT invoked
expect(mockEngine.update).not.toHaveBeenCalled();
});
it('updateData skips the check when the record has no updated_at column', async () => {
mockEngine.findOne.mockResolvedValue({ id: 'r1', name: 'No timestamps' });
await protocol.updateData({
object: 'task',
id: 'r1',
data: { name: 'New' },
expectedVersion: '2026-05-22T07:14:00.000Z',
});
expect(mockEngine.update).toHaveBeenCalledOnce();
});
it('updateData skips the check when expectedVersion is empty string', async () => {
await protocol.updateData({
object: 'task',
id: 'r1',
data: { name: 'New' },
expectedVersion: ' ',
});
expect(mockEngine.findOne).not.toHaveBeenCalled();
expect(mockEngine.update).toHaveBeenCalledOnce();
});
it('deleteData throws ConcurrentUpdateError on version mismatch', async () => {
mockEngine.findOne.mockResolvedValue({
id: 'r1',
updated_at: '2026-05-22T07:14:00.000Z',
});
await expect(
protocol.deleteData({
object: 'task',
id: 'r1',
expectedVersion: '2026-05-22T06:00:00.000Z',
})
).rejects.toMatchObject({
name: 'ConcurrentUpdateError',
code: 'CONCURRENT_UPDATE',
});
expect(mockEngine.delete).not.toHaveBeenCalled();
});
it('deleteData proceeds when versions match', async () => {
mockEngine.findOne.mockResolvedValue({
id: 'r1',
updated_at: '2026-05-22T07:14:00.000Z',
});
await protocol.deleteData({
object: 'task',
id: 'r1',
expectedVersion: '2026-05-22T07:14:00.000Z',
});
expect(mockEngine.delete).toHaveBeenCalledOnce();
});
});
// ═══════════════════════════════════════════════════════════════
// cloneData — duplicate a record, gated by enable.clone
// ═══════════════════════════════════════════════════════════════
describe('cloneData', () => {
// A richer engine mock: cloneData reads registry.getObject for the
// schema (enable.clone + field defs), findOne for the source row, and
// insert for the copy.
function makeProtocol(opts: {
schema?: any;
source?: any;
} = {}) {
const insert = vi.fn(async (_obj: string, data: any) => ({ id: 'new-id', ...data }));
const findOne = vi.fn().mockResolvedValue(
opts.source === undefined
? { id: 'src-1', name: 'Acme', amount: 100 }
: opts.source,
);
const engine: any = {
findOne,
insert,
registry: {
getObject: vi.fn().mockReturnValue(
opts.schema === undefined
? { name: 'account', fields: { name: { type: 'text' }, amount: { type: 'number' } } }
: opts.schema,
),
},
};
return { protocol: new ObjectStackProtocolImplementation(engine), engine, insert, findOne };
}
it('copies business fields and strips engine-owned audit/id columns', async () => {
const { protocol, insert } = makeProtocol({
source: {
id: 'src-1', name: 'Acme', amount: 100,
created_at: 'x', created_by: 'u1', updated_at: 'y', updated_by: 'u1',
},
});
const result = await protocol.cloneData({ object: 'account', id: 'src-1' });
const [, inserted] = insert.mock.calls[0];
expect(inserted).toEqual({ name: 'Acme', amount: 100 });
expect(inserted).not.toHaveProperty('id');
expect(inserted).not.toHaveProperty('created_at');
expect(inserted).not.toHaveProperty('updated_by');
expect(result).toMatchObject({ object: 'account', id: 'new-id', sourceId: 'src-1' });
});
it('drops autonumber / formula / summary / system fields so they re-derive', async () => {
const { protocol, insert } = makeProtocol({
schema: {
name: 'ticket',
fields: {
name: { type: 'text' },
ref: { type: 'autonumber' },
total: { type: 'formula' },
rollup: { type: 'summary' },
organization_id: { type: 'text', system: true },
},
},
source: {
id: 'src-1', name: 'Bug', ref: 'TKT-0001',
total: 42, rollup: 7, organization_id: 'org-9',
},
});
await protocol.cloneData({ object: 'ticket', id: 'src-1' });
const [, inserted] = insert.mock.calls[0];
expect(inserted).toEqual({ name: 'Bug' });
});
it('applies caller overrides last (they win over copied values)', async () => {
const { protocol, insert } = makeProtocol({
source: { id: 'src-1', name: 'Acme', amount: 100 },
});
await protocol.cloneData({
object: 'account',
id: 'src-1',
overrides: { name: 'Acme (Copy)', amount: 0 },
});
const [, inserted] = insert.mock.calls[0];
expect(inserted).toEqual({ name: 'Acme (Copy)', amount: 0 });
});
it('forwards context to findOne and insert', async () => {
const { protocol, insert, findOne } = makeProtocol();
const ctx = { userId: 'u1' };
await protocol.cloneData({ object: 'account', id: 'src-1', context: ctx });
expect(findOne).toHaveBeenCalledWith('account', expect.objectContaining({ context: ctx }));
expect(insert).toHaveBeenCalledWith('account', expect.anything(), { context: ctx });
});
it('rejects with 403 CLONE_DISABLED when enable.clone === false', async () => {
const { protocol, insert } = makeProtocol({
schema: { name: 'account', enable: { clone: false }, fields: {} },
});
await expect(
protocol.cloneData({ object: 'account', id: 'src-1' }),
).rejects.toMatchObject({ code: 'CLONE_DISABLED', status: 403 });
expect(insert).not.toHaveBeenCalled();
});
it('allows clone when enable block is absent (default-on)', async () => {
const { protocol, insert } = makeProtocol({
schema: { name: 'account', fields: { name: { type: 'text' } } },
});
await protocol.cloneData({ object: 'account', id: 'src-1' });
expect(insert).toHaveBeenCalledOnce();
});
it('rejects with 404 RECORD_NOT_FOUND when the source is missing', async () => {
const { protocol, insert } = makeProtocol({ source: null });
await expect(
protocol.cloneData({ object: 'account', id: 'nope' }),
).rejects.toMatchObject({ code: 'RECORD_NOT_FOUND', status: 404 });
expect(insert).not.toHaveBeenCalled();
});
it('rejects with 404 OBJECT_NOT_FOUND for an unknown object', async () => {
const { protocol } = makeProtocol({ schema: null });
await expect(
protocol.cloneData({ object: 'ghost', id: 'src-1' }),
).rejects.toMatchObject({ code: 'OBJECT_NOT_FOUND', status: 404 });
});
});
});