@softr/sdk 0.0.27 → 0.0.29

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.
@@ -1,176 +0,0 @@
1
- ---
2
- name: reading-records
3
- description: >-
4
- Fetch records from a Softr datasource inside a server function: ds.list and
5
- ds.get from @softr/sdk/server, the q query builder (q.text, q.number,
6
- q.boolean, q.date, q.array, q.and, q.or, q.asc, q.desc), q.select field
7
- aliasing, filtering, sorting, the 20-record default and 100-record cap, and
8
- nextOffset pagination. Reads only. Mutations, workflows, integrations, metrics
9
- and chart data are not covered.
10
- metadata:
11
- type: sub-skill
12
- library: softr-sdk
13
- library_version: 0.0.27
14
- ---
15
-
16
- **Boundary.** `ds` lives on `@softr/sdk/server` and runs only inside a `createServerFn` handler or a server-side route hook — importing it into a component fails the build. `q` and every type come from `@softr/sdk` and can be imported anywhere. The app is already wired (`src/start.ts`, `src/router.tsx`, `src/routes/__root.tsx`); never add a second registration. Load the core `softr-sdk` skill only if you are unsure this is the right sub-skill.
17
-
18
- # Reading records
19
-
20
- `ds` reads records out of a Softr datasource, from the server only.
21
-
22
- ## Setup
23
-
24
- ```ts
25
- import { createServerFn } from '@tanstack/react-start'
26
- import { ds } from '@softr/sdk/server'
27
- import { q } from '@softr/sdk'
28
- ```
29
-
30
- Every `ds` call names its datasource by an opaque UUID from the table's registration on the application (Softr Studio's Data tab, or the `register_application_data_source` tool when an agent does it). It is not the table id, and it is never derived from the table's name — `'ds_posts'` or a name glued to a uuid fails at request time as not found or forbidden.
31
-
32
- **The datasource id must be a string literal at the call site.** Do not assign it to a variable and pass the variable. Write the UUID directly as the first argument:
33
-
34
- ```ts
35
- // correct
36
- ds.list('8ffb4814-b028-4496-b679-7face2167ebc', { ... })
37
-
38
- // wrong
39
- const POSTS = '8ffb4814-b028-4496-b679-7face2167ebc'
40
- ds.list(POSTS, { ... })
41
- ```
42
-
43
- A record comes back as `{ id: string; fields: Record<string, unknown> }`. When you write a TypeScript type for the fields, the shape of each value depends on the Softr field type — see [references/field-types.md](./references/field-types.md) for the full mapping.
44
-
45
- ## Typing record fields
46
-
47
- Declare a local type for the records you fetch using `SoftrRecord<Fields>`. Use the shapes from the field-types reference, not guesses from the field name. The most common mistake is treating SELECT and LINKED_RECORD fields as strings — they are objects:
48
-
49
- ```ts
50
- import type { SoftrRecord } from '@softr/sdk'
51
-
52
- type Product = SoftrRecord<{
53
- name: string // SINGLE_LINE_TEXT
54
- price: number | null // CURRENCY
55
- category: { id: string; label: string } // SELECT — not a string
56
- supplier: { id: string; label: string } // LINKED_RECORD — not a string
57
- }>
58
- ```
59
-
60
- `SoftrRecord<Fields>` is shorthand for `{ id: string; fields: Fields }` — the `Fields` type parameter constrains every value to `JsonValue`, so TypeScript rejects non-serializable types like `Date` objects.
61
-
62
- Cast at the `ds.list` call using the `ListResult` generic so the type flows through the loader automatically:
63
-
64
- ```ts
65
- import type { ListResult, SoftrRecord } from '@softr/sdk'
66
-
67
- const fetchProducts = createServerFn().handler(() =>
68
- ds.list('3c1e8a52-6f0d-4b7e-9a21-5d84c0f7b2e6', { select, limit: 100 }) as Promise<ListResult<Product>>
69
- )
70
- ```
71
-
72
- `loaderData` is then already typed as `ListResult<Product>` — no second cast needed in the component. All the shapes in [references/field-types.md](./references/field-types.md) satisfy the `JsonValue` constraint.
73
-
74
- ## Core Patterns
75
-
76
- ### List records
77
-
78
- ```ts
79
- const listPublishedPosts = createServerFn().handler(async () => {
80
- return await ds.list('8ffb4814-b028-4496-b679-7face2167ebc', {
81
- select: q.select({
82
- title: 'fZk3Qm9pLw2Xa1',
83
- author: 'mB4kQ8yTn1sWc7',
84
- published: 'Ru7bVx2cNq0Ed9',
85
- publishedAt: 'Xp2dLh6vKz9Fa3',
86
- }),
87
- where: q.boolean('published').is(true),
88
- orderBy: q.desc('publishedAt'),
89
- limit: 50,
90
- })
91
- })
92
- ```
93
-
94
- Returns `{ records, total, nextOffset }`. `ds.list(POSTS)` on its own returns the first 20 records with their raw field ids. `limit` defaults to 20 and is clamped to 100. A larger number is silently reduced, so more than a hundred records means paginating.
95
-
96
- **Filtering or sorting requires a `select`, and it has to cover every field you name.** `where` and `orderBy` speak aliases, so without a map to translate through they throw at request time. That is why `published` is in the map above even though the table never displays it.
97
-
98
- ### Name the fields with `select`
99
-
100
- Softr field ids are opaque strings (`fZk3Qm9pLw2Xa1`), copied from the table's schema. `q.select` maps your own names onto them, and those names are what the rest of the call speaks:
101
-
102
- ```ts
103
- const select = q.select({ title: 'fZk3Qm9pLw2Xa1', views: 'Ru7bVx2cNq0Ed9' })
104
-
105
- await ds.list('8ffb4814-b028-4496-b679-7face2167ebc', {
106
- select,
107
- where: q.number('views').gt(100), // alias, not Ru7bVx2cNq0Ed9
108
- orderBy: q.asc('title'), // alias here too
109
- })
110
- // records[0].fields is { title: ..., views: ... }
111
- ```
112
-
113
- Once `select` is present it is the whole vocabulary. The returned record carries exactly those keys, and any field you filter or sort on must appear in the map.
114
-
115
- ### Get one record
116
-
117
- ```ts
118
- const post = await ds.get('8ffb4814-b028-4496-b679-7face2167ebc', { id: postId })
119
- if (post === null) throw notFound()
120
- ```
121
-
122
- A record that does not exist comes back as `null`, not an error.
123
-
124
- The type also accepts `{ where }` instead of `{ id }`, but there is no way to pass a `select` alongside it, so the filter cannot be translated and the call throws. Fetch one record by id, or use `ds.list` with a `limit` of 1 when you need to find it by a field.
125
-
126
- ### Filter with `q`
127
-
128
- ```ts
129
- where: q.and(
130
- q.text('status').is('active'),
131
- q.number('amount').gte(100),
132
- q.or(
133
- q.text('owner').is(user.id),
134
- q.array('collaborators').hasAllOf([user.id]),
135
- ),
136
- )
137
- ```
138
-
139
- Five field types, `q.text`, `q.number`, `q.boolean`, `q.date` and `q.array`, combined with `q.and` and `q.or`. The full operator matrix is in [references/query-builder.md](./references/query-builder.md).
140
-
141
- ### Paginate
142
-
143
- ```ts
144
- const first = await ds.list('8ffb4814-b028-4496-b679-7face2167ebc', { limit: 50 })
145
- if (first.nextOffset !== null) {
146
- const second = await ds.list('8ffb4814-b028-4496-b679-7face2167ebc', { limit: 50, offset: first.nextOffset })
147
- }
148
- ```
149
-
150
- `nextOffset` is `null` when there are no more pages. `total` is the count of all matching records, not the count returned.
151
-
152
- ### Scope the read to the visitor
153
-
154
- ```ts
155
- const listMyInvoices = createServerFn().handler(async ({ context }) => {
156
- if (!context.user) throw new Error('Not signed in')
157
-
158
- return await ds.list('e4b7c2a1-9d3f-4e68-b05a-7f1c6d2e8a93', {
159
- select: q.select({ owner: 'Gq5wNt8rJy3Hb1', amount: 'Vk9cXm2pSz6Ld4' }),
160
- where: q.text('owner').is(context.user.id),
161
- })
162
- })
163
- ```
164
-
165
- See [current-user](../current-user/SKILL.md) for how the visitor gets onto `context`.
166
-
167
- A server function is its own endpoint, reachable whether or not the visitor ever matched the route that displays the data. A route's visibility rule decides who sees a page. The server function decides for itself who gets the records.
168
-
169
- A read the visitor is not allowed to make throws rather than coming back empty, and it throws a plain `Error` carrying the status. There is no typed predicate to narrow it with. Handle it where you would handle any other failed fetch: an `errorComponent` on the route, or a check in the handler.
170
-
171
- ## References
172
-
173
- - [references/field-types.md](./references/field-types.md): TypeScript shape for every Softr field type
174
- - [references/query-builder.md](./references/query-builder.md): every `q` field type and operator
175
- - [current-user/SKILL.md](../current-user/SKILL.md): reading the visitor off `context` to scope a query
176
- - [routes-and-visibility/SKILL.md](../routes-and-visibility/SKILL.md): deciding who sees the page the records land on
@@ -1,70 +0,0 @@
1
- # Softr field types — TypeScript shapes
2
-
3
- When you write a TypeScript type for a record's fields, use these shapes. The field's **type** (shown in the datasource metadata or described by the user) determines the shape, not the field's name.
4
-
5
- ```ts
6
- // Simple scalar types
7
- SINGLE_LINE_TEXT: string
8
- LONG_TEXT: string
9
- EMAIL: string
10
- PHONE: string
11
- URL: string
12
- ADDRESS: string
13
- LOCATION: string
14
- BUTTON: string
15
- RECORD_ID: string
16
- DATETIME: string // ISO timestamp string
17
- DATE: string // ISO date string
18
- TIME: string
19
- CREATED_AT: string
20
- UPDATED_AT: string
21
- CHECKBOX: string | boolean
22
- AUTONUMBER: number | null
23
- NUMBER: number | null
24
- PERCENT: number | null
25
- CURRENCY: number | null
26
- PROGRESS: number | null
27
- DURATION: number | null
28
- COUNT: number | null
29
- RATING: string | number | null
30
- FORMULA: string | number
31
-
32
- // Object types — these are NOT plain strings
33
- SELECT: { id: string; label: string }
34
- LINKED_RECORD: { id: string; label: string }
35
-
36
- DATE_RANGE: { from: string; to: string }
37
-
38
- ATTACHMENT: {
39
- filename: string | null | undefined
40
- id: string | null | undefined
41
- type: string | null | undefined
42
- url: string
43
- thumbnails?: Array<{ size: 'small' | 'medium' | 'large'; url: string }>
44
- }
45
-
46
- USER: { avatarUrl: string | null; id: string; name: string; email: string }
47
-
48
- CREATED_BY: string | string[] | { avatarUrl: string | null; id: string; name: string; email: string }
49
- UPDATED_BY: string | string[] | { avatarUrl: string | null; id: string; name: string; email: string }
50
-
51
- // These depend on what the linked field/aggregation resolves to
52
- LOOKUP: unknown
53
- ROLLUP: unknown
54
- ```
55
-
56
- ## The non-obvious ones
57
-
58
- **SELECT and LINKED_RECORD** are the most commonly mistyped. They are never a plain string — always `{ id: string; label: string }`. To display the value, use `.label`. To filter or compare, use `.id`.
59
-
60
- ```tsx
61
- // Correct
62
- <td>{record.fields.status?.label}</td>
63
-
64
- // Wrong — status is not a string
65
- <td>{record.fields.status}</td>
66
- ```
67
-
68
- **CHECKBOX** can be either a string (`'true'` / `'false'`) or a boolean depending on the datasource. Type it as `string | boolean` and coerce when needed: `!!record.fields.active`.
69
-
70
- **CREATED_BY / UPDATED_BY** can be a plain id string, an array of ids, or a full user object. Narrow before using.
@@ -1,144 +0,0 @@
1
- # `q`, the query builder
2
-
3
- Every filter, sort and field map passed to `ds` is built with `q`, imported from `@softr/sdk`. Filters and sorts built any other way are rejected at runtime.
4
-
5
- ```ts
6
- import { q } from '@softr/sdk'
7
- ```
8
-
9
- ## Shape
10
-
11
- ```ts
12
- await ds.list(datasourceId, {
13
- select: q.select({ alias: '<field id>', ... }), // optional field map
14
- where: <one filter, or q.and/q.or of filters>,
15
- orderBy: q.asc('alias') | [q.desc('a'), q.asc('b')],
16
- limit: number, // default 20, clamped down to 100
17
- offset: number | null,
18
- })
19
- ```
20
-
21
- `where` takes exactly one value. For more than one condition, wrap them in `q.and(...)` or `q.or(...)`.
22
-
23
- ## Field types and operators
24
-
25
- Pick the builder that matches the field's type. The type travels with the operator and decides how the value is compared.
26
-
27
- ### `q.text(field)`
28
-
29
- | Call | Meaning |
30
- | --- | --- |
31
- | `.is(value: string)` | Exactly equal |
32
- | `.isNot(value: string)` | Not equal |
33
- | `.contains(value: string)` | Substring match |
34
- | `.startsWith(value: string)` | Prefix match |
35
- | `.endsWith(value: string)` | Suffix match |
36
- | `.isOneOf(values: string[])` | Equal to any of |
37
- | `.isNoneOf(values: string[])` | Equal to none of |
38
- | `.hasAllOf(values: string[])` | Contains all of |
39
- | `.isEmpty()` | No value |
40
- | `.isNotEmpty()` | Has a value |
41
-
42
- ### `q.number(field)`
43
-
44
- | Call | Meaning |
45
- | --- | --- |
46
- | `.is(value: number)` | Equal |
47
- | `.isNot(value: number)` | Not equal |
48
- | `.gt(value: number)` | Greater than |
49
- | `.gte(value: number)` | Greater than or equal |
50
- | `.lt(value: number)` | Less than |
51
- | `.lte(value: number)` | Less than or equal |
52
- | `.between(start: number, end: number)` | Inclusive range |
53
- | `.isEmpty()` / `.isNotEmpty()` | No value / has a value |
54
-
55
- Takes JavaScript numbers.
56
-
57
- ### `q.boolean(field)`
58
-
59
- | Call | Meaning |
60
- | --- | --- |
61
- | `.is(value: boolean)` | Equal |
62
- | `.isNot(value: boolean)` | Not equal |
63
- | `.isEmpty()` / `.isNotEmpty()` | No value / has a value |
64
-
65
- ### `q.date(field)`
66
-
67
- | Call | Meaning |
68
- | --- | --- |
69
- | `.is(value: string)` | On that date |
70
- | `.isNot(value: string)` | Not on that date |
71
- | `.gt(value: string)` | After |
72
- | `.gte(value: string)` | On or after |
73
- | `.lt(value: string)` | Before |
74
- | `.lte(value: string)` | On or before |
75
- | `.between(start: string, end: string)` | Inclusive range |
76
- | `.isNotBetween(start: string, end: string)` | Outside the range |
77
- | `.isEmpty()` / `.isNotEmpty()` | No value / has a value |
78
-
79
- Every value is an ISO date string, either `'2026-01-31'` or a full timestamp. A `Date` instance is not accepted. Call `.toISOString()` first.
80
-
81
- ### `q.array(field)`
82
-
83
- For multi-value fields: linked records, multi-selects, collaborators.
84
-
85
- | Call | Meaning |
86
- | --- | --- |
87
- | `.is(values: string[])` | Exactly this set |
88
- | `.isOneOf(values: string[])` | Contains at least one of |
89
- | `.isNoneOf(values: string[])` | Contains none of |
90
- | `.hasAllOf(values: string[])` | Contains all of |
91
- | `.isEmpty()` / `.isNotEmpty()` | Empty / non-empty |
92
-
93
- ## Combining
94
-
95
- ```ts
96
- q.and(...filters) // all must match
97
- q.or(...filters) // any may match
98
- ```
99
-
100
- Both take filters or nested groups:
101
-
102
- ```ts
103
- where: q.and(
104
- q.text('status').is('active'),
105
- q.or(
106
- q.number('amount').gte(1000),
107
- q.array('tags').hasAllOf(['priority']),
108
- ),
109
- )
110
- ```
111
-
112
- Nesting goes two levels, a group inside a group. A third level throws `Cannot nest filter groups more than three levels deep.` Flatten by distributing the outer condition rather than nesting further.
113
-
114
- ## Sorting
115
-
116
- ```ts
117
- orderBy: q.asc('title')
118
- orderBy: [q.desc('publishedAt'), q.asc('title')]
119
- ```
120
-
121
- Sorts are applied in array order.
122
-
123
- ## Field maps
124
-
125
- ```ts
126
- const select = q.select({ title: 'fZk3Qm9pLw2Xa1', views: 'Ru7bVx2cNq0Ed9' })
127
- ```
128
-
129
- `q.select` maps names you choose onto Softr field ids — opaque strings copied from the table's schema. Two rules follow from that:
130
-
131
- 1. The returned record carries exactly the keys in the map. A field left out is not returned, and no error is raised.
132
- 2. `where` and `orderBy` name aliases, and every one of them must be in the map. A name that is not throws `Could not find an alias for subject "..."` at request time, and so does a `where` or `orderBy` passed with no `select` at all.
133
-
134
- So `select` must list every field the query touches, not just the ones being displayed.
135
-
136
- ## Errors
137
-
138
- | Message | Cause |
139
- | --- | --- |
140
- | `Filters cannot be constructed manually. Use the 'q' helper.` | A `where` value built as a plain object |
141
- | `orderBy conditions cannot be constructed manually. Use the 'q' helper.` | An `orderBy` value not from `q.asc` / `q.desc` |
142
- | `Cannot nest filter groups more than three levels deep.` | A group nested one level too far |
143
- | `Could not find an alias for subject "..."` | A sort field missing from `select`, or an `orderBy` with no `select` at all |
144
- | `Could not find an alias for subject "undefined"` | The same thing on a filter, which does not report the field name |