@cogover/sdk 0.5.0 → 0.6.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.
- package/README.md +101 -4
- package/dist/data.d.ts +6 -1
- package/dist/data.js +28 -1
- package/dist/errors.d.ts +7 -0
- package/dist/errors.js +10 -0
- package/dist/index.d.ts +5 -3
- package/dist/index.js +2 -1
- package/dist/internal/json.js +81 -0
- package/dist/internal/trigger-config.js +212 -0
- package/dist/internal/trigger-runtime.js +211 -0
- package/dist/records.d.ts +5 -0
- package/dist/trigger.d.ts +121 -0
- package/dist/trigger.js +15 -0
- package/docs/en/api-reference.md +469 -2
- package/docs/en/usage-guide.md +214 -3
- package/package.json +1 -1
package/docs/en/api-reference.md
CHANGED
|
@@ -250,6 +250,431 @@ the transport envelope directly. A redirect location must be non-empty, at most
|
|
|
250
250
|
4,096 characters, and contain no newline. `response.json()` rejects `undefined`;
|
|
251
251
|
`response.text()` requires a string and `response.bytes()` requires `Uint8Array`.
|
|
252
252
|
|
|
253
|
+
## Record triggers
|
|
254
|
+
|
|
255
|
+
A record trigger runs project code when records of one Object are created, updated,
|
|
256
|
+
or deleted. Declare each trigger with `defineTrigger` and list the results in the
|
|
257
|
+
project's named `triggers` export. The default export is still the HTTP handler and
|
|
258
|
+
is optional in a project that only declares triggers.
|
|
259
|
+
|
|
260
|
+
This example assumes that `workspace.d.ts` declares the `order` Object and the
|
|
261
|
+
fields used below.
|
|
262
|
+
|
|
263
|
+
```typescript
|
|
264
|
+
import { defineTrigger } from "@cogover/sdk";
|
|
265
|
+
|
|
266
|
+
export const triggers = [
|
|
267
|
+
defineTrigger({
|
|
268
|
+
key: "order_credit_check",
|
|
269
|
+
object: "order",
|
|
270
|
+
timing: "beforeChange",
|
|
271
|
+
operations: ["create", "update"],
|
|
272
|
+
fields: ["status", "amount", "customer"],
|
|
273
|
+
changedFields: ["status", "amount"],
|
|
274
|
+
when: { op: "=", field: "status", params: "confirmed" },
|
|
275
|
+
writableFields: ["approval_level"],
|
|
276
|
+
}, async ({ records }) => {
|
|
277
|
+
for (const record of records) {
|
|
278
|
+
if ((record.new.amount ?? 0) > 1_000_000_000) {
|
|
279
|
+
record.addError("amount", "AMOUNT_TOO_LARGE", "Amount exceeds the approval limit.");
|
|
280
|
+
continue;
|
|
281
|
+
}
|
|
282
|
+
record.new.approval_level = "high";
|
|
283
|
+
}
|
|
284
|
+
}),
|
|
285
|
+
];
|
|
286
|
+
```
|
|
287
|
+
|
|
288
|
+
A trigger has one of two timings. A **before-change** trigger runs before the change
|
|
289
|
+
is saved: it can reject records and adjust the values that will be saved. An
|
|
290
|
+
**after-change** trigger runs asynchronously after the change has been saved: it
|
|
291
|
+
cannot reject or modify that change, but it may write records and call `fetch`. See
|
|
292
|
+
[Before-change execution rules](#before-change-execution-rules) and
|
|
293
|
+
[After-change execution rules](#after-change-execution-rules).
|
|
294
|
+
|
|
295
|
+
Cogover reads the trigger configuration when a project version is published and
|
|
296
|
+
applies it while that version is active. Deactivating the project removes its
|
|
297
|
+
triggers. A project can declare at most 50 triggers, and an Object can have at most
|
|
298
|
+
20 active before-change triggers.
|
|
299
|
+
|
|
300
|
+
### `defineTrigger(config, handler): TriggerDefinition`
|
|
301
|
+
|
|
302
|
+
```typescript
|
|
303
|
+
function defineTrigger<
|
|
304
|
+
ObjectSlug extends keyof Schema & string,
|
|
305
|
+
Operation extends TriggerOperation,
|
|
306
|
+
Schema extends object = EffectiveWorkspaceObjects,
|
|
307
|
+
>(
|
|
308
|
+
config: TriggerConfig<ObjectSlug, Operation, Schema>,
|
|
309
|
+
handler: TriggerHandler<ObjectSlug, Operation, Schema>,
|
|
310
|
+
): TriggerDefinition;
|
|
311
|
+
```
|
|
312
|
+
|
|
313
|
+
The type arguments are inferred from `config.object` and `config.operations`.
|
|
314
|
+
With a generated `workspace.d.ts`, the object slug, every field slug in the
|
|
315
|
+
configuration, and the values of `record.new` and `record.old` are checked against
|
|
316
|
+
the declared Object. Without Workspace declarations, slugs are strings and field
|
|
317
|
+
values are `unknown`.
|
|
318
|
+
|
|
319
|
+
`defineTrigger` validates the configuration immediately and throws `ValidationError`
|
|
320
|
+
for any violation, for an unknown configuration key, or for a handler that is not a
|
|
321
|
+
function. It returns a frozen `TriggerDefinition`.
|
|
322
|
+
|
|
323
|
+
```typescript
|
|
324
|
+
type TriggerTiming = "beforeChange" | "afterChange";
|
|
325
|
+
type TriggerOperation = "create" | "update" | "delete";
|
|
326
|
+
type TriggerRunWhen = "always" | "onEnter";
|
|
327
|
+
|
|
328
|
+
interface TriggerConfig<
|
|
329
|
+
ObjectSlug extends string = string,
|
|
330
|
+
Operation extends TriggerOperation = TriggerOperation,
|
|
331
|
+
Schema extends object = EffectiveWorkspaceObjects,
|
|
332
|
+
> {
|
|
333
|
+
readonly key: string;
|
|
334
|
+
readonly name?: string;
|
|
335
|
+
readonly object: ObjectSlug;
|
|
336
|
+
readonly timing: TriggerTiming;
|
|
337
|
+
readonly operations: readonly Operation[];
|
|
338
|
+
readonly fields: readonly FieldSlug[]; // field slugs of the Object
|
|
339
|
+
readonly changedFields?: readonly FieldSlug[];
|
|
340
|
+
readonly when?: TriggerFilter;
|
|
341
|
+
readonly runWhen?: TriggerRunWhen;
|
|
342
|
+
readonly writableFields?: readonly FieldSlug[];
|
|
343
|
+
readonly order?: number;
|
|
344
|
+
readonly timeoutMs?: number;
|
|
345
|
+
}
|
|
346
|
+
```
|
|
347
|
+
|
|
348
|
+
| Option | Required | Rules and meaning |
|
|
349
|
+
|---|---|---|
|
|
350
|
+
| `key` | Yes | Identifies the trigger inside the project. Starts with an ASCII letter and contains letters, digits, or `_`; at most 100 characters. Keep it stable between versions: a new key is a different trigger. |
|
|
351
|
+
| `name` | No | Display name of at most 250 characters. Defaults to `key`. |
|
|
352
|
+
| `object` | Yes | Slug of the Object whose records run the trigger. |
|
|
353
|
+
| `timing` | Yes | `"beforeChange"` runs before the change is saved and can reject or adjust it. `"afterChange"` runs asynchronously after the change has been saved. |
|
|
354
|
+
| `operations` | Yes | Non-empty list of `"create"`, `"update"`, and `"delete"` without duplicates. |
|
|
355
|
+
| `fields` | Yes | 1–200 unique field slugs. `record.new` and `record.old` contain only these fields and `id`. |
|
|
356
|
+
| `changedFields` | No | 1–200 unique field slugs; requires the `"update"` operation. An update runs the trigger only when at least one of these fields changed. Creates and deletes are not affected. |
|
|
357
|
+
| `when` | No | A `TriggerFilter`. Only matching records run the trigger. |
|
|
358
|
+
| `runWhen` | No | `"always"` (default) or `"onEnter"`. `"onEnter"` requires `when`. |
|
|
359
|
+
| `writableFields` | No | At most 100 unique field slugs that the handler may change. Only for `"beforeChange"`; must be empty when `"delete"` is the only operation. Defaults to `[]`. |
|
|
360
|
+
| `order` | No | Integer from 1000 through 8999; defaults to `5000`. Triggers of an Object run in ascending order. Other values are reserved for Cogover. Do not rely on the relative order of triggers that share a value. |
|
|
361
|
+
| `timeoutMs` | No | Integer from 100 through 3000; defaults to `2000`. Time budget of one handler call. |
|
|
362
|
+
|
|
363
|
+
Object and field slugs start with an ASCII letter or `_`, contain letters, digits,
|
|
364
|
+
or `_`, and are at most 355 characters. `changedFields` and `writableFields` do not
|
|
365
|
+
have to be listed in `fields`.
|
|
366
|
+
|
|
367
|
+
### Trigger filters
|
|
368
|
+
|
|
369
|
+
```typescript
|
|
370
|
+
interface TriggerFilterCondition {
|
|
371
|
+
readonly op: FilterOperator;
|
|
372
|
+
readonly field: string;
|
|
373
|
+
readonly params?: unknown;
|
|
374
|
+
}
|
|
375
|
+
|
|
376
|
+
interface TriggerFilterGroup {
|
|
377
|
+
readonly op: "and" | "or";
|
|
378
|
+
readonly conditions: readonly TriggerFilter[];
|
|
379
|
+
}
|
|
380
|
+
|
|
381
|
+
type TriggerFilter = TriggerFilterCondition | TriggerFilterGroup;
|
|
382
|
+
```
|
|
383
|
+
|
|
384
|
+
```typescript
|
|
385
|
+
when: {
|
|
386
|
+
op: "and",
|
|
387
|
+
conditions: [
|
|
388
|
+
{ op: "=", field: "status", params: "confirmed" },
|
|
389
|
+
{ op: "or", conditions: [
|
|
390
|
+
{ op: ">=", field: "amount", params: 1_000_000 },
|
|
391
|
+
{ op: "in", field: "priority", params: ["high", "urgent"] },
|
|
392
|
+
] },
|
|
393
|
+
],
|
|
394
|
+
}
|
|
395
|
+
```
|
|
396
|
+
|
|
397
|
+
A condition compares one field using a `FilterOperator`. `params` is the JSON
|
|
398
|
+
comparison value: it is required for every operator except `"is null"` and
|
|
399
|
+
`"not null"`, which take none. `"in"` and `"not in"` take a non-empty array and
|
|
400
|
+
`"between"` takes exactly two values. A group combines a non-empty list of
|
|
401
|
+
filters. A filter is nested at most 8 levels deep and contains at most 50
|
|
402
|
+
conditions. Trigger filters are plain objects: expressions built with `and()`,
|
|
403
|
+
`or()`, or field references are for `records.list` and are rejected here.
|
|
404
|
+
|
|
405
|
+
`when` is evaluated on the new values, or on the old values when a record is
|
|
406
|
+
deleted. With `runWhen: "onEnter"` the trigger runs only when the record did not
|
|
407
|
+
match `when` before the change and matches after it; a record that is being created
|
|
408
|
+
counts as not matching before, and `runWhen` is ignored for deletes.
|
|
409
|
+
|
|
410
|
+
Cogover decides which triggers run once, before the first trigger of a change, from
|
|
411
|
+
the values submitted by the writer together with field defaults. A value changed by
|
|
412
|
+
an earlier trigger does not change which triggers run, but later triggers see it in
|
|
413
|
+
`record.new`.
|
|
414
|
+
|
|
415
|
+
### `TriggerDefinition` and `TriggerManifest`
|
|
416
|
+
|
|
417
|
+
```typescript
|
|
418
|
+
interface TriggerManifest {
|
|
419
|
+
readonly key: string;
|
|
420
|
+
readonly name?: string;
|
|
421
|
+
readonly object: string;
|
|
422
|
+
readonly timing: TriggerTiming;
|
|
423
|
+
readonly operations: readonly TriggerOperation[];
|
|
424
|
+
readonly fields: readonly string[];
|
|
425
|
+
readonly changedFields?: readonly string[];
|
|
426
|
+
readonly when?: TriggerFilter;
|
|
427
|
+
readonly runWhen: TriggerRunWhen;
|
|
428
|
+
readonly writableFields: readonly string[];
|
|
429
|
+
readonly order: number;
|
|
430
|
+
readonly timeoutMs: number;
|
|
431
|
+
}
|
|
432
|
+
|
|
433
|
+
type TriggerSandboxHandler = (inputJson: string) => Promise<string>;
|
|
434
|
+
|
|
435
|
+
interface TriggerDefinition {
|
|
436
|
+
readonly key: string;
|
|
437
|
+
readonly config: TriggerManifest;
|
|
438
|
+
readonly __cogoverTriggerHandler: TriggerSandboxHandler;
|
|
439
|
+
}
|
|
440
|
+
```
|
|
441
|
+
|
|
442
|
+
`config` is the normalized configuration as deeply frozen plain JSON, with every
|
|
443
|
+
default applied: `runWhen: "always"`, `writableFields: []`, `order: 5000`, and
|
|
444
|
+
`timeoutMs: 2000`. Optional settings that were not provided are absent. It is
|
|
445
|
+
detached from the object passed to `defineTrigger`, so later edits of that object
|
|
446
|
+
have no effect. `__cogoverTriggerHandler` is reserved for Cogover; project code
|
|
447
|
+
does not call it.
|
|
448
|
+
|
|
449
|
+
### Trigger handler context
|
|
450
|
+
|
|
451
|
+
```typescript
|
|
452
|
+
type TriggerHandler<
|
|
453
|
+
ObjectSlug extends string = string,
|
|
454
|
+
Operation extends TriggerOperation = TriggerOperation,
|
|
455
|
+
Schema extends object = EffectiveWorkspaceObjects,
|
|
456
|
+
> = (context: TriggerContext<ObjectSlug, Operation, Schema>) => void | Promise<void>;
|
|
457
|
+
|
|
458
|
+
interface TriggerContext<
|
|
459
|
+
ObjectSlug extends string = string,
|
|
460
|
+
Operation extends TriggerOperation = TriggerOperation,
|
|
461
|
+
Schema extends object = EffectiveWorkspaceObjects,
|
|
462
|
+
> {
|
|
463
|
+
readonly records: readonly TriggerRecord<Fields, Operation>[]; // Fields of ObjectSlug
|
|
464
|
+
readonly trigger: TriggerInfo<Operation>;
|
|
465
|
+
readonly invocation: InvocationContext;
|
|
466
|
+
readonly data: DataApi<Schema>;
|
|
467
|
+
readonly schema: SchemaApi<Schema>;
|
|
468
|
+
readonly log: ScriptLogger;
|
|
469
|
+
}
|
|
470
|
+
|
|
471
|
+
interface TriggerInfo<Operation extends TriggerOperation = TriggerOperation> {
|
|
472
|
+
readonly id: string;
|
|
473
|
+
readonly key: string;
|
|
474
|
+
readonly timing: TriggerTiming;
|
|
475
|
+
readonly operation: Operation;
|
|
476
|
+
readonly objectSlug: string;
|
|
477
|
+
readonly changeId: string;
|
|
478
|
+
}
|
|
479
|
+
|
|
480
|
+
interface TriggerRecord<Fields = Record<string, unknown>, Operation extends TriggerOperation = TriggerOperation> {
|
|
481
|
+
readonly key: string;
|
|
482
|
+
readonly id: CogoverRecordId | null;
|
|
483
|
+
readonly new: TriggerNewValues<Fields> | null;
|
|
484
|
+
readonly old: TriggerOldValues<Fields> | null;
|
|
485
|
+
readonly changedFields: readonly (keyof Fields & string)[];
|
|
486
|
+
addError(field: (keyof Fields & string) | null, code: string, message?: string): void;
|
|
487
|
+
}
|
|
488
|
+
|
|
489
|
+
type TriggerNewValues<Fields> = {
|
|
490
|
+
-readonly [K in keyof Fields]?: Fields[K] | UpdateFields<Fields>[K];
|
|
491
|
+
};
|
|
492
|
+
|
|
493
|
+
type TriggerOldValues<Fields> = {
|
|
494
|
+
readonly [K in keyof Fields]?: Fields[K];
|
|
495
|
+
};
|
|
496
|
+
```
|
|
497
|
+
|
|
498
|
+
A handler may be synchronous or asynchronous; its return value is ignored. One call
|
|
499
|
+
receives all records of the same change that run the trigger, up to 200 records and
|
|
500
|
+
200 KiB, so a batch write or an import calls the handler once per chunk instead of
|
|
501
|
+
once per record. Keep `fields` short, and read related data for the whole list with
|
|
502
|
+
one `records.getMany` call rather than one read per record.
|
|
503
|
+
|
|
504
|
+
`data`, `schema`, `log`, and `invocation` are the same APIs that scripts receive. A
|
|
505
|
+
trigger context has no `input`, `request`, `response`, `state`, or `locks`.
|
|
506
|
+
`trigger.operation` is the operation of the current call, `trigger.id` identifies the
|
|
507
|
+
trigger registration, and `trigger.changeId` identifies the record change that caused
|
|
508
|
+
the call.
|
|
509
|
+
|
|
510
|
+
Each `TriggerRecord` describes one record:
|
|
511
|
+
|
|
512
|
+
- `key` correlates the record with its result. It is not a record ID.
|
|
513
|
+
- `id` is the record ID, or `null` while a record that is being created has no ID yet.
|
|
514
|
+
In an after-change trigger it is always set.
|
|
515
|
+
- `new` holds the values after the change as a plain, mutable object. It is `null`
|
|
516
|
+
when the record is deleted.
|
|
517
|
+
- `old` holds the values before the change and is deeply frozen. It is `null` when the
|
|
518
|
+
record is created.
|
|
519
|
+
- `changedFields` is a frozen list of the field slugs that changed. For a created
|
|
520
|
+
record it lists every field that has a value.
|
|
521
|
+
|
|
522
|
+
The declared `operations` narrow these types: `new` is never `null` unless
|
|
523
|
+
`"delete"` is declared, `old` is never `null` unless `"create"` is declared, and a
|
|
524
|
+
trigger that only declares `"delete"` has `new: null`. `TriggerNewValues` and
|
|
525
|
+
`TriggerOldValues` make every field optional because a field that is not listed in
|
|
526
|
+
`fields`, or that has no value, is `undefined`.
|
|
527
|
+
|
|
528
|
+
### Validating and changing records
|
|
529
|
+
|
|
530
|
+
This section applies to before-change triggers. In an after-change trigger the
|
|
531
|
+
change is already saved: `addError` only reports to the project log and
|
|
532
|
+
`record.new` must not be changed (see
|
|
533
|
+
[After-change execution rules](#after-change-execution-rules)).
|
|
534
|
+
|
|
535
|
+
`record.addError(field, code, message?)` rejects the record. `field` is a field slug,
|
|
536
|
+
or `null` for an error about the whole record. `code` starts with an upper-case ASCII
|
|
537
|
+
letter and contains upper-case letters, digits, or `_`; at most 64 characters, for
|
|
538
|
+
example `AMOUNT_TOO_LARGE`. `message` is an optional English text of at most 500
|
|
539
|
+
characters that Cogover shows to the end user when it has no translation for the
|
|
540
|
+
code; an empty message is ignored. Invalid arguments throw `ValidationError`. A
|
|
541
|
+
record may collect several errors.
|
|
542
|
+
|
|
543
|
+
A rejected record is not saved, and any change the handler made to it is discarded.
|
|
544
|
+
The writer receives HTTP 400 with `msg: "BEFORE_CHANGE_TRIGGER_REJECTED"`, the error
|
|
545
|
+
codes in `meta` keyed by field slug (`$record` for an error about the whole record),
|
|
546
|
+
and the optional texts in `messages` keyed by code. A rejected single-record write
|
|
547
|
+
stops at the first trigger that reports an error. In a batch write only the rejected
|
|
548
|
+
rows fail, and a rejected row is not passed to later triggers.
|
|
549
|
+
|
|
550
|
+
To change the values that will be saved, assign fields of `record.new`:
|
|
551
|
+
|
|
552
|
+
```typescript
|
|
553
|
+
record.new.approval_level = "high";
|
|
554
|
+
record.new.customer = "ACC-1"; // same format as records.update() input
|
|
555
|
+
record.new.note = null; // clears the field
|
|
556
|
+
```
|
|
557
|
+
|
|
558
|
+
- Only fields listed in `writableFields` may change. When the handler returns, the
|
|
559
|
+
SDK compares every top-level field of `record.new` with a snapshot taken before the
|
|
560
|
+
handler ran, using a deep JSON comparison. Changing any other field, including
|
|
561
|
+
`id`, throws `ValidationError` naming the field, and the write fails.
|
|
562
|
+
- Assigned values use the same format as `records.update` input and must be JSON
|
|
563
|
+
data. `NaN`, functions, `Map`, `Set`, and class instances are rejected; a `Date` is
|
|
564
|
+
stored as its ISO string. Assigning `null` clears a field; assigning `undefined` or
|
|
565
|
+
deleting the field has the same effect.
|
|
566
|
+
- A change inside an array or object value is detected and sends the whole field value.
|
|
567
|
+
- `record.new` itself cannot be replaced, and a record that is being deleted has
|
|
568
|
+
nothing to change.
|
|
569
|
+
- Cogover validates the final values again before saving, including field types and
|
|
570
|
+
required, unique, and duplicate rules. For the fields a trigger changed, the
|
|
571
|
+
field's manual create/modify setting and the writer's field edit permission are
|
|
572
|
+
not applied. Read-only fields such as formulas, auto numbers, and rollups, and
|
|
573
|
+
system fields, are always refused.
|
|
574
|
+
|
|
575
|
+
### Before-change execution rules
|
|
576
|
+
|
|
577
|
+
A before-change trigger runs for every source of a write: the Cogover web
|
|
578
|
+
application, API keys, imports, automation processes, other Custom Backend Modules,
|
|
579
|
+
and writes made through `data.asUser()` or `data.asSystem()`. Maintenance writes
|
|
580
|
+
made by Cogover itself — recalculating formula and rollup fields, background record
|
|
581
|
+
merges, and cascading deletes — do not run before-change triggers, and neither does
|
|
582
|
+
a request that only validates input without saving.
|
|
583
|
+
|
|
584
|
+
- **Read-only.** A before-change trigger may read records and schema, but every
|
|
585
|
+
record write, `fetch`, lock, and state write is refused with
|
|
586
|
+
`PermissionDeniedError` whose `details.reason` is `"TRIGGER_READ_ONLY"`. This
|
|
587
|
+
applies to every identity, including `data.asSystem()`.
|
|
588
|
+
- **Identity.** `data.object()` acts as the user who made the change, with that
|
|
589
|
+
user's permissions, and `invocation` describes the same user. When a change has
|
|
590
|
+
no user, `invocation.identity` is `"system"` and `data.object()` works only if the
|
|
591
|
+
project's approved identity policy sets `allowInternalSystem: true`; otherwise its
|
|
592
|
+
calls throw `PermissionDeniedError` with `details.reason` `"IDENTITY_NOT_GRANTED"`
|
|
593
|
+
while the handler still receives `records`. `data.asUser()` and `data.asSystem()`
|
|
594
|
+
follow the project's identity policy as usual.
|
|
595
|
+
- **Fail closed.** When a handler throws, exceeds `timeoutMs`, exceeds a runtime
|
|
596
|
+
limit, or cannot be run, the write is rejected and nothing is saved. The writer
|
|
597
|
+
receives `msg: "BEFORE_CHANGE_TRIGGER_FAILED"` without internal details.
|
|
598
|
+
- **Time.** Each call must finish within `timeoutMs`. All before-change triggers of
|
|
599
|
+
one write share a total budget of 8 seconds.
|
|
600
|
+
|
|
601
|
+
### After-change execution rules
|
|
602
|
+
|
|
603
|
+
An after-change trigger (`timing: "afterChange"`) runs asynchronously, shortly after
|
|
604
|
+
the change has been saved. Use it for follow-up work such as creating or updating
|
|
605
|
+
related records or notifying another system. It runs for the same sources of a
|
|
606
|
+
write as a before-change trigger, with the same exceptions.
|
|
607
|
+
|
|
608
|
+
```typescript
|
|
609
|
+
import { defineTrigger, fetch, RetryableError } from "@cogover/sdk";
|
|
610
|
+
|
|
611
|
+
export const triggers = [
|
|
612
|
+
defineTrigger({
|
|
613
|
+
key: "order_confirmed_notify",
|
|
614
|
+
object: "order",
|
|
615
|
+
timing: "afterChange",
|
|
616
|
+
operations: ["create", "update"],
|
|
617
|
+
fields: ["status", "amount"],
|
|
618
|
+
changedFields: ["status"],
|
|
619
|
+
when: { op: "=", field: "status", params: "confirmed" },
|
|
620
|
+
runWhen: "onEnter",
|
|
621
|
+
}, async ({ records, trigger }) => {
|
|
622
|
+
for (const record of records) {
|
|
623
|
+
const response = await fetch("https://erp.example.com/orders", {
|
|
624
|
+
method: "POST",
|
|
625
|
+
headers: {
|
|
626
|
+
"content-type": "application/json",
|
|
627
|
+
// The same change of the same record always produces the same key.
|
|
628
|
+
"idempotency-key": `${trigger.changeId}:${record.id}`,
|
|
629
|
+
},
|
|
630
|
+
body: JSON.stringify({ id: record.id, amount: record.new.amount }),
|
|
631
|
+
});
|
|
632
|
+
if (response.status >= 500) {
|
|
633
|
+
throw new RetryableError("The ERP is temporarily unavailable");
|
|
634
|
+
}
|
|
635
|
+
}
|
|
636
|
+
}),
|
|
637
|
+
];
|
|
638
|
+
```
|
|
639
|
+
|
|
640
|
+
- **Cannot block or change the saved record.** The writer has already received its
|
|
641
|
+
response. `writableFields` is not allowed, and changing `record.new` makes the call
|
|
642
|
+
fail with `ValidationError`. `record.addError()` rejects nothing: the reported
|
|
643
|
+
errors are only written to the project log. To change the record, call
|
|
644
|
+
`records.update`; that is a new write and runs triggers again.
|
|
645
|
+
- **Saved values.** `record.id` is always set. `record.new` holds the values as they
|
|
646
|
+
were saved, including the record ID and values assigned while saving, such as an
|
|
647
|
+
auto number. For a deleted record `record.new` is `null` and `record.old` holds the
|
|
648
|
+
last values.
|
|
649
|
+
- **May write and call out.** Record writes and `fetch` work as they do in a script,
|
|
650
|
+
within the same runtime limits. `data.object()` acts as the user who made the
|
|
651
|
+
change, and the other identity rules of before-change triggers apply. The trigger
|
|
652
|
+
context has no `state` or `locks`.
|
|
653
|
+
- **Best-effort delivery.** Cogover does not guarantee that an after-change handler
|
|
654
|
+
runs exactly once. It may occasionally run more than once for the same change, or
|
|
655
|
+
not at all. Make every handler idempotent: `trigger.changeId` together with
|
|
656
|
+
`record.id` identifies one change of one record. Never make an after-change
|
|
657
|
+
trigger the only guarantee of a critical rule; enforce such rules in a
|
|
658
|
+
before-change trigger.
|
|
659
|
+
- **Retries.** Throw `RetryableError` when a handler fails for a temporary reason,
|
|
660
|
+
such as an external service that is unavailable. Cogover runs the handler again
|
|
661
|
+
later: by default up to 5 more times, waiting longer before each attempt, from
|
|
662
|
+
about one second to about ten minutes. A call that exceeds `timeoutMs`, or that
|
|
663
|
+
Cogover could not run for a temporary reason, is retried the same way. Any other
|
|
664
|
+
error is not retried: the failure is logged and the handler does not run again for
|
|
665
|
+
that change. When the retries are used up, the handler does not run again for that
|
|
666
|
+
change either.
|
|
667
|
+
- **Loops end.** A write made by a trigger runs triggers again, possibly including
|
|
668
|
+
the same trigger. Cogover limits such chains: every automated write uses one step
|
|
669
|
+
of a fixed budget (10 steps for a change made directly by a user or an API
|
|
670
|
+
client), and after-change triggers no longer run once the budget is used up. Use
|
|
671
|
+
`changedFields`, `when`, and `runWhen: "onEnter"` so that a handler's own writes
|
|
672
|
+
do not start it again.
|
|
673
|
+
- **Order and time.** Each call must finish within `timeoutMs`. After-change triggers
|
|
674
|
+
of one change run independently of each other: do not rely on their relative
|
|
675
|
+
order. A retried call may run after a later change of the same record has already
|
|
676
|
+
been processed, so read the current record when the latest values matter.
|
|
677
|
+
|
|
253
678
|
## Outbound HTTP `fetch`
|
|
254
679
|
|
|
255
680
|
```typescript
|
|
@@ -325,6 +750,7 @@ request. Use the remote API's idempotency mechanism and never retry blindly.
|
|
|
325
750
|
```typescript
|
|
326
751
|
const orders = data.object("order");
|
|
327
752
|
await orders.records.get(id, { fields });
|
|
753
|
+
await orders.records.getMany(ids, { fields });
|
|
328
754
|
await orders.records.list({ where, orderBy, fields, limit, cursor });
|
|
329
755
|
await orders.records.create(fields);
|
|
330
756
|
await orders.records.update(id, fields);
|
|
@@ -376,6 +802,11 @@ interface RecordPage<Fields> {
|
|
|
376
802
|
readonly nextCursor?: string;
|
|
377
803
|
}
|
|
378
804
|
|
|
805
|
+
interface GetManyResult<Fields> {
|
|
806
|
+
readonly records: CogoverRecord<Fields>[];
|
|
807
|
+
readonly missingIds: CogoverRecordId[];
|
|
808
|
+
}
|
|
809
|
+
|
|
379
810
|
interface DeleteResult {
|
|
380
811
|
readonly deleted: CogoverRecordId[];
|
|
381
812
|
readonly notDeleted: CogoverRecordId[];
|
|
@@ -420,6 +851,10 @@ interface GetRecordOptions<Fields> {
|
|
|
420
851
|
readonly fields?: readonly (keyof Fields & string)[];
|
|
421
852
|
}
|
|
422
853
|
|
|
854
|
+
interface GetManyOptions<Fields> {
|
|
855
|
+
readonly fields: readonly (keyof Fields & string)[];
|
|
856
|
+
}
|
|
857
|
+
|
|
423
858
|
interface ListOptions<Fields> {
|
|
424
859
|
readonly where?: FilterExpression;
|
|
425
860
|
readonly orderBy?: readonly SortExpression[];
|
|
@@ -442,6 +877,7 @@ interface RecordWritesApi<Fields> {
|
|
|
442
877
|
|
|
443
878
|
interface RecordsApi<Fields> extends RecordWritesApi<Fields> {
|
|
444
879
|
get(id: string, options?: GetRecordOptions<Fields>): Promise<CogoverRecord<Fields> | null>;
|
|
880
|
+
getMany(ids: readonly string[], options: GetManyOptions<Fields>): Promise<GetManyResult<Fields>>;
|
|
445
881
|
list(options?: ListOptions<Fields>): Promise<RecordPage<Fields>>;
|
|
446
882
|
}
|
|
447
883
|
|
|
@@ -470,6 +906,25 @@ interface DataApi<Schema extends object = EffectiveWorkspaceObjects> {
|
|
|
470
906
|
`nextCursor`. A `CogoverRecord<T>` has `id`, business `fields`, and a separate
|
|
471
907
|
`system` object containing creation/update metadata.
|
|
472
908
|
|
|
909
|
+
`getMany(ids, { fields })` reads up to 200 records by ID with a single capability
|
|
910
|
+
call. `fields` is required and must be a non-empty list of field slugs. IDs are
|
|
911
|
+
trimmed and deduplicated in their original order; more than 200 unique IDs, a blank
|
|
912
|
+
ID, or an invalid `fields` list throws `ValidationError` before any request is sent.
|
|
913
|
+
An empty `ids` array resolves to `{ records: [], missingIds: [] }` without a request.
|
|
914
|
+
The result contains the readable `records` and `missingIds`: every requested ID that
|
|
915
|
+
could not be read, because the record does not exist or the identity in use cannot
|
|
916
|
+
see it. IDs are never dropped silently. The order of `records` is not guaranteed to
|
|
917
|
+
follow `ids`, so index them by `id`:
|
|
918
|
+
|
|
919
|
+
```typescript
|
|
920
|
+
const accounts = data.object("account");
|
|
921
|
+
const { records, missingIds } = await accounts.records.getMany(accountIds, { fields: ["credit_limit"] });
|
|
922
|
+
const accountById = new Map(records.map(record => [record.id, record]));
|
|
923
|
+
```
|
|
924
|
+
|
|
925
|
+
Use `getMany` instead of calling `get` in a loop. Every capability call counts
|
|
926
|
+
towards the project's limits, and a record trigger can receive 200 records at once.
|
|
927
|
+
|
|
473
928
|
Service `0`/`1` booleans are normalized to JavaScript booleans. Lookup/reference
|
|
474
929
|
responses expose only `id`, `name`, and `objectSlug`; writes accept an ID or a
|
|
475
930
|
`RecordReference` and send only the ID to Cogover.
|
|
@@ -571,7 +1026,7 @@ invocation this is the caller; a system invocation keeps system access.
|
|
|
571
1026
|
Returns a new immutable client for reads and writes as the specified personnel ID (not an
|
|
572
1027
|
account ID), in the same workspace. `personnelId` is trimmed; a non-string or blank
|
|
573
1028
|
value throws `ValidationError`. Its `object(slug)` returns `ObjectClient<TFields>`,
|
|
574
|
-
whose `records: RecordsApi<TFields>` exposes `get`, `list`, `create`, `update`, and
|
|
1029
|
+
whose `records: RecordsApi<TFields>` exposes `get`, `getMany`, `list`, `create`, `update`, and
|
|
575
1030
|
`deleteMany` as well as batch insert, batch update, and business upsert, with the
|
|
576
1031
|
same argument and return types as the default record API.
|
|
577
1032
|
|
|
@@ -594,7 +1049,7 @@ const page = await delegatedOrders.records.list({
|
|
|
594
1049
|
### `data.asSystem(): DataApi<TSchema>`
|
|
595
1050
|
|
|
596
1051
|
Returns a new immutable client for system record access, including during an
|
|
597
|
-
authenticated public invocation. It supports `get`, `list`, `create`, `update`, and
|
|
1052
|
+
authenticated public invocation. It supports `get`, `getMany`, `list`, `create`, `update`, and
|
|
598
1053
|
`deleteMany`, including batch writes and business upsert. System access does not
|
|
599
1054
|
apply the caller's record permissions; approved project restrictions, field
|
|
600
1055
|
validation, workspace boundaries, and runtime limits still apply. It neither
|
|
@@ -839,6 +1294,10 @@ class RateLimitError extends CogoverApiError {
|
|
|
839
1294
|
constructor(message: string, details?: unknown);
|
|
840
1295
|
}
|
|
841
1296
|
|
|
1297
|
+
class RetryableError extends CogoverApiError {
|
|
1298
|
+
constructor(message: string, details?: unknown);
|
|
1299
|
+
}
|
|
1300
|
+
|
|
842
1301
|
class StateConflictError extends CogoverApiError {
|
|
843
1302
|
constructor(message: string, details?: unknown);
|
|
844
1303
|
}
|
|
@@ -857,6 +1316,13 @@ result in `error.r` (also retained in `error.details.r`). `r` is `undefined` whe
|
|
|
857
1316
|
there was no server response, such as local SDK validation. The original message
|
|
858
1317
|
remains in `error.message`.
|
|
859
1318
|
|
|
1319
|
+
`RetryableError` (`code: "RETRYABLE"`) is thrown by project code, never by the SDK.
|
|
1320
|
+
An after-change trigger handler throws it to report a temporary failure, and Cogover
|
|
1321
|
+
runs the handler again later (see
|
|
1322
|
+
[After-change execution rules](#after-change-execution-rules)). Anywhere else it
|
|
1323
|
+
has no special meaning: a script that lets it escape returns HTTP 422, and a
|
|
1324
|
+
before-change trigger that throws it rejects the write like any other failure.
|
|
1325
|
+
|
|
860
1326
|
Scripts can catch `CogoverApiError`, inspect `error.r`, and return their own client
|
|
861
1327
|
error, such as `{ r: 1001, msg: "You cannot update this order." }`, without exposing
|
|
862
1328
|
the original code or message. A script's returned JSON remains its own response
|
|
@@ -898,6 +1364,7 @@ For SDK errors escaping `defineScript`, the HTTP endpoint returns an error with
|
|
|
898
1364
|
| `FETCH_TIMEOUT` | 504 |
|
|
899
1365
|
| `FETCH_FAILED` | 502 |
|
|
900
1366
|
| `COGOVER_API_ERROR` | 422 |
|
|
1367
|
+
| `RETRYABLE` | 422 |
|
|
901
1368
|
|
|
902
1369
|
Missing approval for an explicit identity adds `reason: "IDENTITY_NOT_GRANTED"`;
|
|
903
1370
|
it does not mean the selected user was denied access to a particular record.
|