UNPKG

@softr/sdk

Version:

The SDK for building Softr apps on TanStack Start. It lets an app interact with Softr: auth, datasources, workflows and integrations.

205 lines (157 loc) • 10.1 kB
--- name: charts-and-metrics description: >- Aggregate records in a server function: ds.chart with groupBy, metrics, where, orderBy and date buckets for chart rows, ds.metric for one number, and distinct values for filter controls, through the query's filter that keeps them to the records the visitor may read. Use for a chart, a stat tile or any counted, summed or averaged number, or when a chart comes back wrong. Single records are record-queries. metadata: type: sub-skill library: softr-sdk library_version: 1.19.0 --- **Boundary.** `ds` lives on `@softr/sdk/server` and runs only inside a `createServerFn` handler — importing it into a component fails the build. A helper that calls `ds` outside a handler goes in `createServerOnlyFn` from `@tanstack/react-start` (the `record-queries` boundary). `defineQuery` and every type come from `@softr/sdk` and can be imported anywhere. # Charts and metrics `ds.chart` groups records and aggregates each group into one row: the data behind a bar chart, a line, a pie. `ds.metric` aggregates everything into one value: the number on a stat tile. Both live on `@softr/sdk/server` and run inside a `createServerFn` handler, and both take the same query `ds.list` takes, with the same `where` filters. A figure over a list's filters, such as the count and the total above a filtered table, is a `ds.metric` or a `ds.chart` with the list's `where`. It covers every matching record in one request. Records loaded with `ds.list` come 100 at a time, so math over them covers only the pages read. `ds.export` reads every record, but it is for downloads and takes seconds on a large table. ## Setup ```ts import { createServerFn } from '@tanstack/react-start' import { defineQuery } from '@softr/sdk' import { ds } from '@softr/sdk/server' const sales = defineQuery({ id: 'sales', datasourceId: '00000000-0000-0000-0000-000000000000', fields: { amount: 'Vk9cXm2pSz6Ld4', // CURRENCY region: 'fZk3Qm9pLw2Xa1', // SELECT status: 'Ru7bVx2cNq0Ed9', // SELECT, choice ids 'paid' | 'open' | 'void' closedAt: 'Xp2dLh6vKz9Fa3', // DATETIME rep: 'Gq5wNt8rJy3Hb1', // LINKED_RECORD }, permissions: { userGroupTypes: ['LOGGED_IN_USERS'] }, }) ``` A chart only sees the query's declared fields, so a field to group, aggregate or filter by must be in `fields`. Declaring a query belongs to [record-queries](../record-queries/SKILL.md); one query serves `ds.list`, `ds.chart` and `ds.metric`. ## Core Patterns ### A bar chart ```ts const ordersByRegion = createServerFn().handler(async () => { const { data } = await ds .chart(sales) .groupBy((q) => ({ region: q.region })) .metrics((q) => ({ orders: q.$count })) .orderBy((q) => q.orders.desc) return data }) // data: Array<{ region: string | null; orders: number }> ``` One row per group, keyed by the names you chose in `groupBy` and `metrics`. `orders` is `number`, not `number | null`: a group that exists holds at least one record. The `null` region is the bucket of records with no value. The result also carries `executionTimestamp: Date`, when the numbers were computed. A SELECT or LINKED_RECORD group column comes back as the choice's display label, not its id. Labels are user-editable and a `where` on the same field compares ids, so a clicked bar's value cannot be fed straight back into a filter. ### A time series ```ts const { data } = await ds .chart(sales) .groupBy((q) => ({ month: q.closedAt.byMonth })) .metrics((q) => ({ revenue: q.amount.sum })) .where((q) => q.status.is('paid')) .orderBy((q) => q.month.asc) // data: Array<{ month: string | null; revenue: number | null }> ``` `q.closedAt` bare groups by the field's value. The bucket leaves hanging off it group a date field by the bucket: `byDay`, `byWeek`, `byMonth`, `byQuarter`, `byYear`, and the cyclic `byHourOfDay`, `byDayOfWeek`, `byMonthOfYear`, `byQuarterOfYear`. What each one holds is in [references/aggregations.md](./references/aggregations.md); `byMonth` reads as `"2025-06"`. **Sort the time axis ascending yourself.** Left unsorted, rows come back by the first bucket ascending when there is one, else by the first metric descending. A time axis that misses the fallback arrives in value order, which draws a scrambled line rather than failing. ### Spread, not just totals ```ts const { data } = await ds .chart(sales) .groupBy((q) => ({ region: q.region })) .metrics((q) => ({ smallest: q.amount.min, typical: q.amount.avg, biggest: q.amount.max, })) .orderBy((q) => q.typical.desc) ``` Any number of metrics in one request, several over the same field included. Each row carries all of them, so one request can feed two panels. A metric key may not reuse a group key, and two metrics may not ask for the same value. `avg` comes back rounded to two decimals. ### Two group columns, which is the ceiling ```ts const { data } = await ds .chart(sales) .groupBy((q) => ({ month: q.closedAt.byMonth, region: q.region })) .metrics((q) => ({ revenue: q.amount.sum })) .orderBy((q) => [q.month.asc, q.revenue.desc]) // data: Array<{ month: string | null; region: string | null; revenue: number | null }> ``` The result is long format, one row per month and region pair, so the app pivots into one array per series before charting. **A chart groups by at most two columns**, each a different field, and a field cannot be grouped and aggregated in the same chart. A third group column is a compile error. ### Distinct values, for a filter control ```ts const { data } = await ds.chart(sales).groupBy((q) => ({ region: q.region })) // data: Array<{ region: string | null }> ``` Skip `metrics` entirely and the rows hold the distinct group values, one each. This is the cheapest way to fill a dropdown from a real column. ### A headline number ```ts const { value } = await ds .metric(sales, (q) => q.amount.sum) .where((q) => q.status.is('paid')) // value: number | null ``` One aggregation, no grouping, one value. Whenever the answer is a single number, a stat tile or a count, reach for `ds.metric` rather than a one-row chart: there is nothing to group by and nothing to unpack out of `data`. The same measure handles apply, `q.$count` included: ```ts const { value: open } = await ds.metric(sales, (q) => q.$count).where((q) => q.status.is('open')) // open: number ``` ### Top N ```ts const { data } = await ds .chart(sales) .groupBy((q) => ({ rep: q.rep })) .metrics((q) => ({ revenue: q.amount.sum })) .orderBy((q) => q.revenue.desc) const top5 = data.slice(0, 5) ``` A chart has no row limit to set, so a top-N is a client-side slice of the fully sorted rows. ### A dashboard load ```ts const loadDashboard = createServerFn().handler(async () => { const [mtd, series] = await Promise.all([ ds .metric(sales, (q) => q.amount.sum) .where((q) => q.$and(q.status.is('paid'), q.closedAt.gte('2026-09-01'))), ds .chart(sales) .groupBy((q) => ({ month: q.closedAt.byMonth })) .metrics((q) => ({ revenue: q.amount.sum })) .where((q) => q.status.is('paid')) .orderBy((q) => q.month.asc), ]) return { mtd: mtd.value, series: series.data } }) ``` Each tile and panel is its own request, fired in parallel from one handler. ### Scope a figure like the records behind it A chart or a metric reads through the `filter` of its query, like `ds.list` (see [record-queries](../record-queries/SKILL.md#keep-each-visitor-to-their-own-records)). So a figure over a filtered query counts only the records its visitor may read. A chart over another query of the same table needs the same filter. Without it, a "my revenue" tile adds up everyone's sales, and a chart grouped by a person shows the names of people the visitor may not see. Here a rep sees only their own sales. `rep` links to Users, and 'Rk2mVx9pQa4Lz7' is the Record ID field of the users table, declared in softr.json under `user.properties`: ```ts const mySales = defineQuery({ id: 'mySales', datasourceId: '00000000-0000-0000-0000-000000000000', fields: { amount: 'Vk9cXm2pSz6Ld4', closedAt: 'Xp2dLh6vKz9Fa3' }, filterFields: { rep: 'Gq5wNt8rJy3Hb1' }, filter: { rep: { isOneOf: ['USER:::Rk2mVx9pQa4Lz7'] } }, permissions: { userGroupTypes: ['LOGGED_IN_USERS'], customGroups: ['00000000-0000-0000-0000-00000000000c'] }, }) const myRevenue = createServerFn().handler(async () => { const { value } = await ds.metric(mySales, (q) => q.amount.sum) return value }) ``` A chart can group, aggregate and `where` only on `fields`, not on `filterFields`. For a visitor who is signed out, or who has no value for the token, the chart has no rows, a count is `0` and every other metric is `null`. ## Order of calls `groupBy` comes first and exactly once; a chart cannot be awaited before it. `metrics` follows, at most once, or not at all for distinct values. `where` can be chained anywhere, repeatedly, and calling it more than once ands the filters together. `orderBy` sorts by the chart's own keys, group and metric alike, and only sees the keys declared so far, so call it last. A builder is for one read. `where` adds to the builder it is called on, so a `ds.chart` or `ds.metric` kept in a variable and read again carries the filters of the earlier read. Start each figure from its own `ds.chart` or `ds.metric`, as the dashboard load above does. ## References - [references/aggregations.md](./references/aggregations.md): every bucket interval and its value type, and which aggregations each kind of field offers. Load it when choosing a bucket or when a field does not offer the aggregation you expected. - [record-queries/SKILL.md](../record-queries/SKILL.md): declaring the query a chart aggregates over. Load it when the declaration itself is what you are writing. - [record-queries/references/filters-and-sorting.md](../record-queries/references/filters-and-sorting.md): every filter operator by field type. Load it when the `where` you need is not shown here, or when a filter is rejected.