@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/usage-guide.md
CHANGED
|
@@ -4,8 +4,8 @@
|
|
|
4
4
|
|
|
5
5
|
A **Custom Backend Module** adds server-side business logic to a Cogover
|
|
6
6
|
workspace. Use one to process requests, validate or transform data, automate
|
|
7
|
-
record operations,
|
|
8
|
-
service. It is different from a Custom Frontend Module, which implements a user
|
|
7
|
+
record operations, check or adjust records before they are saved, expose HTTP
|
|
8
|
+
routes, or integrate Cogover with an external service. It is different from a Custom Frontend Module, which implements a user
|
|
9
9
|
interface.
|
|
10
10
|
|
|
11
11
|
Custom Backend Modules are written in TypeScript. `@cogover/sdk` supplies the
|
|
@@ -17,7 +17,8 @@ A typical development flow is:
|
|
|
17
17
|
|
|
18
18
|
1. Create a TypeScript project and install `@cogover/sdk`.
|
|
19
19
|
2. Generate `workspace.d.ts` so workspace Objects and fields are type-safe.
|
|
20
|
-
3. Implement and locally type-check the module's default handler
|
|
20
|
+
3. Implement and locally type-check the module's default handler and its record
|
|
21
|
+
triggers.
|
|
21
22
|
4. Publish the module to Cogover, configure its permissions, and invoke it
|
|
22
23
|
through the intended trigger or HTTP route.
|
|
23
24
|
|
|
@@ -108,6 +109,24 @@ export default defineScript(async ({ data }) => {
|
|
|
108
109
|
});
|
|
109
110
|
```
|
|
110
111
|
|
|
112
|
+
## Read many records by ID
|
|
113
|
+
|
|
114
|
+
`records.getMany` reads up to 200 records with one capability call. `fields` is
|
|
115
|
+
required, and IDs that cannot be read are reported instead of being dropped:
|
|
116
|
+
|
|
117
|
+
```typescript
|
|
118
|
+
const accounts = data.object("account");
|
|
119
|
+
const { records, missingIds } = await accounts.records.getMany(accountIds, {
|
|
120
|
+
fields: ["name", "credit_limit"],
|
|
121
|
+
});
|
|
122
|
+
const accountById = new Map(records.map(record => [String(record.id), record]));
|
|
123
|
+
if (missingIds.length > 0) log.warn("Accounts could not be read", { missingIds });
|
|
124
|
+
```
|
|
125
|
+
|
|
126
|
+
Duplicate IDs are sent once. The order of `records` is not guaranteed to follow
|
|
127
|
+
`ids`, so look records up by `id`. Prefer `getMany` to calling `get` in a loop:
|
|
128
|
+
every capability call counts towards the project's limits.
|
|
129
|
+
|
|
111
130
|
## Call an external API with `fetch`
|
|
112
131
|
|
|
113
132
|
```typescript
|
|
@@ -237,6 +256,198 @@ authentication object in module code, and never log or return credentials for an
|
|
|
237
256
|
external service. See
|
|
238
257
|
[API reference](api-reference.md#record-execution-identities).
|
|
239
258
|
|
|
259
|
+
## Record triggers
|
|
260
|
+
|
|
261
|
+
A record trigger runs your code when records of one Object are created, updated, or
|
|
262
|
+
deleted. A **before-change** trigger runs before the change is saved: it can reject
|
|
263
|
+
the change with validation errors and it can adjust the values that will be saved.
|
|
264
|
+
An **after-change** trigger runs after the change has been saved, for follow-up work
|
|
265
|
+
such as updating related records or notifying another system; see
|
|
266
|
+
[After-change triggers](#after-change-triggers). A trigger runs for every source of a write — the Cogover web application, API keys,
|
|
267
|
+
imports, automation processes, and other Custom Backend Modules — so a rule placed
|
|
268
|
+
in a trigger cannot be bypassed by choosing a different way to write the record.
|
|
269
|
+
Maintenance writes made by Cogover itself, such as recalculating formula and rollup
|
|
270
|
+
fields, background record merges, and cascading deletes, do not run triggers.
|
|
271
|
+
|
|
272
|
+
Declare triggers with `defineTrigger` and list them in the named `triggers` export.
|
|
273
|
+
The default export remains the HTTP handler and is optional in a project that only
|
|
274
|
+
has triggers. This example assumes that `workspace.d.ts` declares the Objects and
|
|
275
|
+
fields it uses.
|
|
276
|
+
|
|
277
|
+
```typescript
|
|
278
|
+
import { defineTrigger, type RecordReference } from "@cogover/sdk";
|
|
279
|
+
|
|
280
|
+
const referenceId = (value: string | RecordReference | null | undefined): string | undefined =>
|
|
281
|
+
typeof value === "string" ? value : value?.id;
|
|
282
|
+
|
|
283
|
+
export const triggers = [
|
|
284
|
+
defineTrigger({
|
|
285
|
+
key: "order_credit_check",
|
|
286
|
+
name: "Order credit check",
|
|
287
|
+
object: "order",
|
|
288
|
+
timing: "beforeChange",
|
|
289
|
+
operations: ["create", "update"],
|
|
290
|
+
fields: ["status", "amount", "customer"],
|
|
291
|
+
changedFields: ["status", "amount", "customer"],
|
|
292
|
+
when: { op: "=", field: "status", params: "confirmed" },
|
|
293
|
+
writableFields: ["approval_level"],
|
|
294
|
+
}, async ({ records, data }) => {
|
|
295
|
+
// One read for the whole list, never one read per record.
|
|
296
|
+
const customerIds = records.flatMap(record => referenceId(record.new.customer) ?? []);
|
|
297
|
+
const customers = await data.object("account").records.getMany(customerIds, {
|
|
298
|
+
fields: ["credit_limit"],
|
|
299
|
+
});
|
|
300
|
+
const limitById = new Map<string, number>(
|
|
301
|
+
customers.records.map(customer => [customer.id, customer.fields.credit_limit ?? 0]),
|
|
302
|
+
);
|
|
303
|
+
|
|
304
|
+
for (const record of records) {
|
|
305
|
+
const amount = record.new.amount ?? 0;
|
|
306
|
+
const limit = limitById.get(referenceId(record.new.customer) ?? "");
|
|
307
|
+
if (limit === undefined) {
|
|
308
|
+
record.addError("customer", "CUSTOMER_NOT_AVAILABLE", "Select a customer that you can access.");
|
|
309
|
+
continue;
|
|
310
|
+
}
|
|
311
|
+
if (amount > limit) {
|
|
312
|
+
record.addError("amount", "CREDIT_LIMIT_EXCEEDED", "Amount exceeds the customer's credit limit.");
|
|
313
|
+
continue;
|
|
314
|
+
}
|
|
315
|
+
record.new.approval_level = amount > 100_000_000 ? "high" : "standard";
|
|
316
|
+
}
|
|
317
|
+
}),
|
|
318
|
+
];
|
|
319
|
+
```
|
|
320
|
+
|
|
321
|
+
Cogover applies the triggers of the active project version. What each setting does:
|
|
322
|
+
|
|
323
|
+
- `fields` selects the values delivered in `record.new` and `record.old`. Only
|
|
324
|
+
these fields and `id` are present, so a field that is not listed is `undefined`.
|
|
325
|
+
List only what the handler reads: one call is limited to 200 KiB.
|
|
326
|
+
- `operations` chooses `"create"`, `"update"`, and `"delete"`. `record.old` is
|
|
327
|
+
`null` for a created record and `record.new` is `null` for a deleted one; the
|
|
328
|
+
TypeScript types follow the operations you declare.
|
|
329
|
+
- `changedFields` makes an update run the trigger only when at least one listed
|
|
330
|
+
field changed. `record.changedFields` tells the handler which fields changed.
|
|
331
|
+
- `when` only runs the trigger for matching records. It is a plain object such as
|
|
332
|
+
`{ op: "=", field: "status", params: "confirmed" }`, combined with
|
|
333
|
+
`{ op: "and", conditions: [...] }` or `{ op: "or", conditions: [...] }`.
|
|
334
|
+
`runWhen: "onEnter"` runs the trigger only when a record starts matching `when`,
|
|
335
|
+
instead of on every matching write.
|
|
336
|
+
- `writableFields` lists the fields the handler may change (before-change only).
|
|
337
|
+
- `order` (1000–8999, default 5000) positions the trigger among the triggers of the
|
|
338
|
+
same Object. Later triggers see the values changed by earlier ones.
|
|
339
|
+
- `timeoutMs` (100–3000, default 2000) is the time budget of one call.
|
|
340
|
+
|
|
341
|
+
**Validate.** Call `record.addError(field, code, message?)` to reject a record; pass
|
|
342
|
+
`null` as the field for an error about the whole record. The code is an upper-case
|
|
343
|
+
identifier such as `CREDIT_LIMIT_EXCEEDED`. The optional message is an English text
|
|
344
|
+
of at most 500 characters that Cogover shows to the end user when it has no
|
|
345
|
+
translation for the code. A rejected record is not saved. In a batch write the other
|
|
346
|
+
rows continue.
|
|
347
|
+
|
|
348
|
+
**Modify.** Assign fields of `record.new`, for example
|
|
349
|
+
`record.new.approval_level = "high"`. Only `writableFields` may change; changing any
|
|
350
|
+
other field makes the write fail with a `ValidationError` naming the field. Assigned
|
|
351
|
+
values use the same format as `records.update` input, so a reference field accepts a
|
|
352
|
+
record ID and a date field accepts `"yyyy-MM-dd"`. Assigning `null` clears a field. Cogover validates the final values again before saving. A trigger
|
|
353
|
+
may fill a field whose manual entry is disabled, but never a read-only field such as
|
|
354
|
+
a formula, auto number, or rollup.
|
|
355
|
+
|
|
356
|
+
**Process the whole list.** A handler receives up to 200 records in one call: a
|
|
357
|
+
batch write or an import calls it once per chunk, not once per record. Never read
|
|
358
|
+
inside the loop. Collect the IDs, call `records.getMany` once, and look the results
|
|
359
|
+
up from a `Map`, as in the example above.
|
|
360
|
+
|
|
361
|
+
**Read-only.** A before-change trigger may read records and schema. Record writes,
|
|
362
|
+
`fetch`, locks, and state writes are refused with `PermissionDeniedError`
|
|
363
|
+
(`details.reason === "TRIGGER_READ_ONLY"`), for every identity. The trigger context
|
|
364
|
+
has `records`, `trigger`, `invocation`, `data`, `schema`, and `log`; it has no
|
|
365
|
+
`request`, `response`, `state`, or `locks`.
|
|
366
|
+
|
|
367
|
+
**Identity.** `data.object()` acts as the user who made the change, with that user's
|
|
368
|
+
permissions, so a read can legitimately return nothing for a record the user cannot
|
|
369
|
+
see. `data.asUser()` and `data.asSystem()` need the same administrator approval as
|
|
370
|
+
in scripts.
|
|
371
|
+
|
|
372
|
+
**Time budget and failures.** A call must finish within `timeoutMs`, and all
|
|
373
|
+
before-change triggers of one write share 8 seconds. Before-change triggers fail
|
|
374
|
+
closed: when a handler throws, runs out of time, or cannot be run, the write is
|
|
375
|
+
rejected and nothing is saved. Keep handlers short and deterministic. See the
|
|
376
|
+
[record trigger reference](api-reference.md#record-triggers).
|
|
377
|
+
|
|
378
|
+
### After-change triggers
|
|
379
|
+
|
|
380
|
+
Set `timing: "afterChange"` to run code after a change has been saved. The handler
|
|
381
|
+
runs asynchronously, shortly after the write: the writer does not wait for it, and
|
|
382
|
+
the handler can neither reject nor modify the saved change. Unlike a before-change
|
|
383
|
+
trigger it may write records and call `fetch`, like a script.
|
|
384
|
+
|
|
385
|
+
```typescript
|
|
386
|
+
import { defineTrigger, fetch, RetryableError } from "@cogover/sdk";
|
|
387
|
+
|
|
388
|
+
export const triggers = [
|
|
389
|
+
defineTrigger({
|
|
390
|
+
key: "order_confirmed_followup",
|
|
391
|
+
object: "order",
|
|
392
|
+
timing: "afterChange",
|
|
393
|
+
operations: ["create", "update"],
|
|
394
|
+
fields: ["status", "amount", "customer"],
|
|
395
|
+
changedFields: ["status"],
|
|
396
|
+
when: { op: "=", field: "status", params: "confirmed" },
|
|
397
|
+
runWhen: "onEnter",
|
|
398
|
+
}, async ({ records, trigger, data }) => {
|
|
399
|
+
for (const record of records) {
|
|
400
|
+
// record.new holds the saved values; record.id is always set after the save.
|
|
401
|
+
const response = await fetch("https://erp.example.com/orders", {
|
|
402
|
+
method: "POST",
|
|
403
|
+
headers: {
|
|
404
|
+
"content-type": "application/json",
|
|
405
|
+
"idempotency-key": `${trigger.changeId}:${record.id}`,
|
|
406
|
+
},
|
|
407
|
+
body: JSON.stringify({ id: record.id, amount: record.new.amount }),
|
|
408
|
+
});
|
|
409
|
+
if (response.status >= 500) {
|
|
410
|
+
// Temporary problem: ask Cogover to run this handler again later.
|
|
411
|
+
throw new RetryableError("The ERP is temporarily unavailable");
|
|
412
|
+
}
|
|
413
|
+
if (!response.ok) continue; // Permanent problem: retrying would not help.
|
|
414
|
+
|
|
415
|
+
await data.object("order_activity").records.create({
|
|
416
|
+
order: record.id,
|
|
417
|
+
activity: "Sent to ERP",
|
|
418
|
+
});
|
|
419
|
+
}
|
|
420
|
+
}),
|
|
421
|
+
];
|
|
422
|
+
```
|
|
423
|
+
|
|
424
|
+
- **Saved values.** `record.new` contains the values as saved, including the record
|
|
425
|
+
ID and values assigned while saving, such as an auto number. `record.old` contains
|
|
426
|
+
the values before the change. A deleted record has `record.new === null`.
|
|
427
|
+
- **No blocking, no changes.** `writableFields` is not allowed and `record.new` must
|
|
428
|
+
not be changed. `record.addError()` rejects nothing here; the errors are only
|
|
429
|
+
written to the project log. To change the record, call `records.update`.
|
|
430
|
+
- **Best-effort delivery.** Cogover does not guarantee that the handler runs exactly
|
|
431
|
+
once: it may occasionally run more than once for the same change, or not at all.
|
|
432
|
+
Make handlers idempotent — `trigger.changeId` together with `record.id` identifies
|
|
433
|
+
one change of one record — and never rely on an after-change trigger as the only
|
|
434
|
+
guarantee of a critical rule. Put such rules in a before-change trigger.
|
|
435
|
+
- **Retries.** Throw `RetryableError` for a temporary failure. Cogover runs the
|
|
436
|
+
handler again later, by default up to 5 more times with growing delays from about
|
|
437
|
+
one second to about ten minutes. A call that runs out of time is retried the same
|
|
438
|
+
way. Any other error is logged and not retried, so catch the errors you can handle
|
|
439
|
+
and decide which of them deserve a retry.
|
|
440
|
+
- **Loops end.** A write made by the handler runs triggers again, possibly including
|
|
441
|
+
the same one. Cogover limits such chains: every automated write uses one step of a
|
|
442
|
+
fixed budget (10 steps for a change made directly by a user or an API client), and
|
|
443
|
+
after-change triggers stop running once it is used up. Narrow the trigger with
|
|
444
|
+
`changedFields`, `when`, and `runWhen: "onEnter"` so its own writes do not start
|
|
445
|
+
it again.
|
|
446
|
+
- **Order.** After-change triggers of one change run independently; do not rely on
|
|
447
|
+
their relative order, and read the current record when the latest values matter.
|
|
448
|
+
|
|
449
|
+
See [After-change execution rules](api-reference.md#after-change-execution-rules).
|
|
450
|
+
|
|
240
451
|
## Recommended TypeScript configuration
|
|
241
452
|
|
|
242
453
|
```json
|