@cogover/sdk 0.12.2 → 0.13.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 +61 -12
- package/dist/data.d.ts +160 -13
- package/dist/data.js +30 -14
- package/dist/index.d.ts +1 -1
- package/dist/internal/record-reads.js +183 -0
- package/dist/records.d.ts +18 -0
- package/docs/en/api-reference/background-jobs.md +4 -1
- package/docs/en/api-reference/overview.md +9 -2
- package/docs/en/api-reference/record-triggers.md +12 -0
- package/docs/en/api-reference/records.md +378 -33
- package/docs/en/api-reference/state-and-locks.md +3 -0
- package/docs/en/usage-guide.md +66 -1
- package/package.json +1 -1
- package/scripts/generate-workspace-types.mjs +19 -7
package/docs/en/usage-guide.md
CHANGED
|
@@ -32,7 +32,7 @@ npx tsc --noEmit
|
|
|
32
32
|
```
|
|
33
33
|
|
|
34
34
|
Place the generated `workspace.d.ts` declaration alongside the module's source
|
|
35
|
-
and include it in the TypeScript project.
|
|
35
|
+
and include it in the TypeScript project. Type checking needs TypeScript 5.0 or later.
|
|
36
36
|
|
|
37
37
|
## Quick start
|
|
38
38
|
|
|
@@ -172,6 +172,23 @@ const approvers = chain?.tiers.flatMap(tier =>
|
|
|
172
172
|
- For other personnel fields, such as custom fields, use
|
|
173
173
|
`data.object("personnel")`, which applies record permissions.
|
|
174
174
|
|
|
175
|
+
## Choose the fields to read
|
|
176
|
+
|
|
177
|
+
Every read names its fields: the slugs the script uses, or `"*"` for every field that
|
|
178
|
+
the identity in use and the project's identity policy may read. A read without
|
|
179
|
+
`fields` throws `ValidationError` (`fields is required: pass field slugs or "*"
|
|
180
|
+
(@cogover/sdk 0.13.0+)`) before anything is sent.
|
|
181
|
+
|
|
182
|
+
```typescript
|
|
183
|
+
const order = await orders.records.get(orderId, { fields: ["code", "amount"] });
|
|
184
|
+
const amount = order?.fields.amount; // number | null | undefined
|
|
185
|
+
// order?.fields.status does not compile: it was not requested.
|
|
186
|
+
const everything = await orders.records.get(orderId, { fields: "*" });
|
|
187
|
+
```
|
|
188
|
+
|
|
189
|
+
Prefer a list of fields to `"*"`: the read returns less data, and a large `"*"`
|
|
190
|
+
result, especially from `getMany` or `list`, can exceed the 1 MiB limit of one call.
|
|
191
|
+
|
|
175
192
|
## Filter and sort records
|
|
176
193
|
|
|
177
194
|
```typescript
|
|
@@ -180,6 +197,7 @@ import { and, defineScript } from "@cogover/sdk";
|
|
|
180
197
|
export default defineScript(async ({ data }) => {
|
|
181
198
|
const orders = data.object("order");
|
|
182
199
|
return orders.records.list({
|
|
200
|
+
fields: ["code", "status", "total"],
|
|
183
201
|
where: and(
|
|
184
202
|
orders.fields.status.in(["new", "nurturing"]),
|
|
185
203
|
orders.fields.is_active.eq(true),
|
|
@@ -209,6 +227,49 @@ Duplicate IDs are sent once. The order of `records` is not guaranteed to follow
|
|
|
209
227
|
`ids`, so look records up by `id`. Prefer `getMany` to calling `get` in a loop:
|
|
210
228
|
every capability call counts towards the project's limits.
|
|
211
229
|
|
|
230
|
+
## Read linked records
|
|
231
|
+
|
|
232
|
+
A lookup value is `{ id, name: "", objectSlug }` unless the read asks for the linked
|
|
233
|
+
record, and `system.createdBy.name` is `""` as well. Set `expandLookups` when the script
|
|
234
|
+
needs the names or fields of linked records:
|
|
235
|
+
|
|
236
|
+
```typescript
|
|
237
|
+
const order = await orders.records.get(orderId, {
|
|
238
|
+
fields: ["code", "customer"],
|
|
239
|
+
expandLookups: { customer: ["credit_limit", "tier"] },
|
|
240
|
+
});
|
|
241
|
+
const customer = order?.fields.customer;
|
|
242
|
+
log.info("Customer", { name: customer?.name, creditLimit: customer?.fields?.credit_limit });
|
|
243
|
+
```
|
|
244
|
+
|
|
245
|
+
`expandLookups: true` expands every lookup among the returned fields. Linked records
|
|
246
|
+
are read one level deep, up to 1,000 per call, with the same identity and permissions
|
|
247
|
+
as the read itself; a linked record that cannot be read keeps `name: ""` and has no
|
|
248
|
+
`fields`. Expanding reads more data, so expand only the lookups the script uses. The
|
|
249
|
+
`new` and `old` values of a record trigger already carry lookup names.
|
|
250
|
+
|
|
251
|
+
## Count and sum records
|
|
252
|
+
|
|
253
|
+
`records.aggregate` returns counts, sums, averages, and smallest or largest values
|
|
254
|
+
without reading the records, optionally grouped by up to three fields:
|
|
255
|
+
|
|
256
|
+
```typescript
|
|
257
|
+
const byStatus = await orders.records.aggregate({
|
|
258
|
+
where: orders.fields.total.gt(0),
|
|
259
|
+
groupBy: ["status"],
|
|
260
|
+
metrics: { orders: { count: "id" }, revenue: { sum: "total" } },
|
|
261
|
+
});
|
|
262
|
+
for (const group of byStatus.groups) {
|
|
263
|
+
log.info("Orders by status", { status: group.key.status, ...group.values });
|
|
264
|
+
}
|
|
265
|
+
```
|
|
266
|
+
|
|
267
|
+
Without `groupBy` the result is `{ values }`. A client from `data.asUser()`, like
|
|
268
|
+
`data.object()` in a trigger or a job that runs as a user, cannot group and supports
|
|
269
|
+
only counts and number metrics; use `data.asSystem()` there. Aggregates follow record writes after about one second,
|
|
270
|
+
so a record saved just before may not be counted yet. See
|
|
271
|
+
[Aggregates](api-reference/records.md#aggregates) for every metric and limit.
|
|
272
|
+
|
|
212
273
|
## Call an external API with `fetch`
|
|
213
274
|
|
|
214
275
|
```typescript
|
|
@@ -859,6 +920,10 @@ permissions, so a read can legitimately return nothing for a record the user can
|
|
|
859
920
|
see. `data.asUser()` and `data.asSystem()` need the same administrator approval as
|
|
860
921
|
in scripts.
|
|
861
922
|
|
|
923
|
+
**Lookup names.** Lookups in `record.new` and `record.old` carry the linked record's
|
|
924
|
+
name. Records read through `data` have `name: ""` in their lookups unless the read
|
|
925
|
+
uses `expandLookups`.
|
|
926
|
+
|
|
862
927
|
**Time budget and failures.** A call must finish within `timeoutMs`, and all
|
|
863
928
|
before-change triggers of one write share 8 seconds. Before-change triggers fail
|
|
864
929
|
closed: when a handler throws, runs out of time, or cannot be run, the write is
|
package/package.json
CHANGED
|
@@ -27,14 +27,23 @@ function extractObjects(documentValue) {
|
|
|
27
27
|
}
|
|
28
28
|
|
|
29
29
|
function renderDeclaration(objectsValue) {
|
|
30
|
+
// SDK types used by the generated field types. The augmentation cannot see the module's own exports, so the
|
|
31
|
+
// declaration imports them; an unresolved name would silently become `any` under skipLibCheck.
|
|
32
|
+
const sdkTypes = new Set();
|
|
30
33
|
const objectLines = objectsValue
|
|
31
34
|
.filter((object) => typeof object?.slug === "string" && object.slug.length > 0)
|
|
32
35
|
.sort((left, right) => left.slug.localeCompare(right.slug))
|
|
33
|
-
.map(renderObject)
|
|
36
|
+
.map((object) => renderObject(object, sdkTypes))
|
|
34
37
|
.join("\n");
|
|
35
38
|
|
|
39
|
+
// Only the names in use are imported, so the file also compiles with noUnusedLocals.
|
|
40
|
+
const usedTypes = [...sdkTypes].sort();
|
|
41
|
+
const importLine = usedTypes.length === 0
|
|
42
|
+
? `import "@cogover/sdk";\n\n`
|
|
43
|
+
: `import type { ${usedTypes.join(", ")} } from "@cogover/sdk";\n\n`;
|
|
44
|
+
|
|
36
45
|
return `// Generated by @cogover/sdk. Do not edit manually.\n`
|
|
37
|
-
+
|
|
46
|
+
+ importLine
|
|
38
47
|
+ `declare module "@cogover/sdk" {\n`
|
|
39
48
|
+ ` interface WorkspaceObjects {\n`
|
|
40
49
|
+ objectLines
|
|
@@ -42,25 +51,25 @@ function renderDeclaration(objectsValue) {
|
|
|
42
51
|
+ `}\n`;
|
|
43
52
|
}
|
|
44
53
|
|
|
45
|
-
function renderObject(object) {
|
|
54
|
+
function renderObject(object, sdkTypes) {
|
|
46
55
|
const fields = Array.isArray(object.fields) ? object.fields : [];
|
|
47
56
|
const fieldLines = fields
|
|
48
57
|
.filter((field) => typeof field?.slug === "string" && field.slug.length > 0)
|
|
49
58
|
.sort((left, right) => left.slug.localeCompare(right.slug))
|
|
50
|
-
.map((field) => ` ${property(field.slug)}: ${fieldType(field)};\n`)
|
|
59
|
+
.map((field) => ` ${property(field.slug)}: ${fieldType(field, sdkTypes)};\n`)
|
|
51
60
|
.join("");
|
|
52
61
|
return ` ${property(object.slug)}: {\n${fieldLines} };\n`;
|
|
53
62
|
}
|
|
54
63
|
|
|
55
|
-
function fieldType(field) {
|
|
56
|
-
const baseType = baseFieldType(field);
|
|
64
|
+
function fieldType(field, sdkTypes) {
|
|
65
|
+
const baseType = baseFieldType(field, sdkTypes);
|
|
57
66
|
const nullableType = field.required === true ? baseType : `${baseType} | null`;
|
|
58
67
|
return field.multiple === true && !baseType.endsWith("[]")
|
|
59
68
|
? `readonly ${parenthesize(baseType)}[]${field.required === true ? "" : " | null"}`
|
|
60
69
|
: nullableType;
|
|
61
70
|
}
|
|
62
71
|
|
|
63
|
-
function baseFieldType(field) {
|
|
72
|
+
function baseFieldType(field, sdkTypes) {
|
|
64
73
|
switch (field.fieldType) {
|
|
65
74
|
case "short_text":
|
|
66
75
|
case "long_text":
|
|
@@ -88,11 +97,14 @@ function baseFieldType(field) {
|
|
|
88
97
|
case "cascading":
|
|
89
98
|
return `readonly ${parenthesize(optionUnion(field.options))}[]`;
|
|
90
99
|
case "url":
|
|
100
|
+
sdkTypes.add("UrlValue");
|
|
91
101
|
return "UrlValue";
|
|
92
102
|
case "file":
|
|
103
|
+
sdkTypes.add("FileValue");
|
|
93
104
|
return "FileValue";
|
|
94
105
|
case "lookup_normal":
|
|
95
106
|
case "reference": {
|
|
107
|
+
sdkTypes.add("RecordReference");
|
|
96
108
|
const objectSlug = referenceObjectSlug(field);
|
|
97
109
|
return objectSlug === null
|
|
98
110
|
? "RecordReference"
|