@softr/sdk
Version:
The SDK for building Softr apps on TanStack Start. It lets an app interact with Softr: auth, datasources, workflows and integrations.
301 lines (299 loc) • 10.4 kB
JavaScript
import { assert, panic } from "../assertions.js";
import { fetch } from "../fetch.js";
import { readUserTimezone } from "../cookies.js";
import { readSessionToken } from "../auth/session.js";
import { INTERNAL_KIND, buildOrderBy } from "./filter.js";
import { makeFieldSet, makeSortSet } from "./fields.js";
import { describeFailure, dsUrl, readFilterCriteria, refererHeader, resolveTarget } from "./record.js";
//#region src/datasource/chart.ts
const COUNT_CNT = "COUNT_CNT";
const COUNT_HANDLE = {
aggregation: "COUNT",
fieldId: null,
[INTERNAL_KIND]: "MEASURE"
};
function makeDimensionSet(select) {
const set = {};
for (const [alias, fieldId] of Object.entries(select)) set[alias] = Object.assign(dimension(fieldId), {
byDay: dimension(fieldId, {
timeInterval: "DAY",
displayFormat: "YYYY-MM-DD"
}),
byWeek: dimension(fieldId, { timeInterval: "WEEK" }),
byMonth: dimension(fieldId, {
timeInterval: "MONTH",
displayFormat: "YYYY-MM"
}),
byQuarter: dimension(fieldId, { timeInterval: "QUARTER" }),
byYear: dimension(fieldId, { timeInterval: "YEAR" }),
byHourOfDay: dimension(fieldId, { timeInterval: "HOUR_OF_DAY" }),
byDayOfWeek: dimension(fieldId, { timeInterval: "DAY_OF_WEEK" }),
byMonthOfYear: dimension(fieldId, { timeInterval: "MONTH_OF_YEAR" }),
byQuarterOfYear: dimension(fieldId, { timeInterval: "QUARTER_OF_YEAR" })
});
return set;
}
function dimension(fieldId, options) {
return options ? {
fieldId,
options,
[INTERNAL_KIND]: "DIMENSION"
} : {
fieldId,
[INTERNAL_KIND]: "DIMENSION"
};
}
function makeMeasureSet(select) {
const set = {};
for (const [alias, fieldId] of Object.entries(select)) set[alias] = {
sum: measure("SUM", fieldId),
avg: measure("AVG", fieldId),
min: measure("MIN", fieldId),
max: measure("MAX", fieldId),
distinct: measure("DISTINCT", fieldId)
};
set["$count"] = COUNT_HANDLE;
return set;
}
function measure(aggregation, fieldId) {
return {
aggregation,
fieldId,
[INTERNAL_KIND]: "MEASURE"
};
}
function isHandle(value, kind) {
return typeof value === "object" && value !== null && value[INTERNAL_KIND] === kind;
}
/**
* Aggregates records into chart rows: one row per group, keyed by the caller's own names.
*
* `groupBy` is required and takes one or two columns. `metrics` is optional; without it the
* rows hold the distinct group values. `orderBy` comes last, over the chart's own keys.
*
* @example
* const { data } = await ds
* .chart(sales)
* .groupBy((q) => ({ month: q.closedAt.byMonth }))
* .metrics((q) => ({ revenue: q.amount.sum, orders: q.$count }))
* .where((q) => q.status.is("paid"))
* .orderBy((q) => q.month.asc)
* // data: Array<{ month: string | null; revenue: number | null; orders: number }>
*/
function chart(query) {
const { select } = resolveTarget(query, "read");
const aliases = Object.keys(select);
const state = {
filters: [],
orderBys: []
};
let result;
const run = () => result ??= executeChart(query, state);
const builder = {
[Symbol.toStringTag]: "ChartQuery",
groupBy(build) {
assert(!state.groups, "groupBy may only be called once");
const entries = Object.entries(build(makeDimensionSet(select)));
for (const [, handle] of entries) assert(isHandle(handle, "DIMENSION"), "a chart column must come from the callback a chart hands you");
assert(entries.length <= 2, "a chart may group by at most two columns");
const groups = entries;
assert(groups.length < 2 || groups[0][1].fieldId !== groups[1][1].fieldId, "a chart may group by a field only once");
state.groups = groups;
return builder;
},
metrics(build) {
assert(!state.metrics, "metrics may only be called once");
const entries = Object.entries(build(makeMeasureSet(select)));
for (const [, handle] of entries) assert(isHandle(handle, "MEASURE"), "a chart column must come from the callback a chart hands you");
const metrics = entries;
const seen = /* @__PURE__ */ new Set();
for (const [, handle] of metrics) {
const pair = `${handle.aggregation} ${handle.fieldId ?? ""}`;
assert(!seen.has(pair), "two metrics ask for the same value");
seen.add(pair);
}
state.metrics = metrics;
return builder;
},
where(build) {
state.filters.push(build(makeFieldSet(aliases)));
return builder;
},
orderBy(build) {
const sorting = build(makeSortSet([...state.groups ?? [], ...state.metrics ?? []].map(([key]) => key)));
state.orderBys.push(...buildOrderBy(Array.isArray(sorting) ? sorting : [sorting]));
return builder;
},
then(onfulfilled, onrejected) {
return run().then(onfulfilled, onrejected);
},
catch(onrejected) {
return run().catch(onrejected);
},
finally(onfinally) {
return run().finally(onfinally);
}
};
return builder;
}
function buildChartRequest(state, filterCriteria) {
const groups = state.groups;
assert(groups && groups.length > 0, "a chart needs at least one column to group by");
const metrics = state.metrics ?? [];
const grouped = new Set(groups.map(([, handle]) => handle.fieldId));
for (const [, handle] of metrics) assert(handle.fieldId === null || !grouped.has(handle.fieldId), "a field cannot be grouped and aggregated in one chart");
const suffixed = metrics.length > 1;
const columns = [...groups.map(([key, handle]) => ({
key,
responseKey: handle.fieldId
})), ...metrics.map(([key, handle]) => ({
key,
responseKey: handle.aggregation === "COUNT" && !handle.fieldId ? COUNT_CNT : `${handle.fieldId}${suffixed ? `_${handle.aggregation.toLowerCase()}` : ""}`
}))];
let orderBys = state.orderBys;
if (orderBys.length === 0) {
const bucketed = groups.find(([, handle]) => handle.options !== void 0);
const [key, sortType] = bucketed ? [bucketed[0], "ASC"] : metrics.length > 0 ? [metrics[0][0], "DESC"] : [groups[0][0], "ASC"];
orderBys = [{
sortingField: key,
sortType
}];
}
const responseKeyOf = new Map(columns.map((column) => [column.key, column.responseKey]));
return {
body: {
filterCriteria,
sortingOptions: orderBys.map((orderBy) => ({
sortingField: responseKeyOf.get(orderBy.sortingField) ?? panic(() => `"${orderBy.sortingField}" is not a column of this chart`),
sortType: orderBy.sortType
})),
groupBy: groups.map(([, handle]) => handle.options ? {
field: handle.fieldId,
options: handle.options
} : { field: handle.fieldId }),
metrics: (metrics.length > 0 ? metrics.map(([, handle]) => handle) : [COUNT_HANDLE]).map((handle) => ({
field: handle.fieldId ?? "",
aggregation: handle.aggregation
}))
},
columns
};
}
function mapChartRows(columns, data) {
return data.map((item) => {
const row = {};
for (const { key, responseKey } of columns) {
assert(responseKey in item, () => `the response has no column for "${key}"`);
row[key] = item[responseKey];
}
return row;
});
}
async function executeChart(query, state) {
const target = resolveTarget(query, "read");
const { actionId } = target;
const filterCriteria = await readFilterCriteria(target, state.filters);
if (filterCriteria === null) return {
data: [],
executionTimestamp: /* @__PURE__ */ new Date()
};
const { body, columns } = buildChartRequest(state, filterCriteria);
const res = await fetch(`${dsUrl(actionId)}/chart/data`, {
method: "POST",
headers: {
"Content-Type": "application/json",
"X-User-Timezone": readUserTimezone() ?? "UTC",
Authorization: `Bearer ${readSessionToken()}`,
...refererHeader()
},
body: JSON.stringify(body)
});
if (!res.ok) throw new Error(`datasource chart failed for action "${actionId}": ${await describeFailure(res)}`);
const payload = await res.json();
return {
data: mapChartRows(columns, payload.data),
executionTimestamp: /* @__PURE__ */ new Date(payload.executionTimestamp * 1e3)
};
}
/**
* Aggregates records into one value, with no grouping.
*
* @example
* const { value } = await ds
* .metric(sales, (q) => q.amount.sum)
* .where((q) => q.status.is("paid"))
* // value: number | null
*/
function metric(query, pick) {
const { select } = resolveTarget(query, "read");
const aliases = Object.keys(select);
const picked = pick(makeMeasureSet(select));
assert(isHandle(picked, "MEASURE"), "a metric must come from the callback a metric hands you");
const handle = picked;
const filters = [];
let result;
const run = () => result ??= executeMetric(query, handle, filters);
const builder = {
[Symbol.toStringTag]: "MetricQuery",
where(build) {
filters.push(build(makeFieldSet(aliases)));
return builder;
},
then(onfulfilled, onrejected) {
return run().then(onfulfilled, onrejected);
},
catch(onrejected) {
return run().catch(onrejected);
},
finally(onfinally) {
return run().finally(onfinally);
}
};
return builder;
}
function buildMetricRequest(handle, filterCriteria) {
return {
body: {
groupBy: [],
metrics: [{
field: handle.fieldId ?? void 0,
aggregation: handle.aggregation
}],
filterCriteria
},
responseKey: handle.aggregation === "COUNT" && !handle.fieldId ? COUNT_CNT : handle.fieldId
};
}
function readMetricValue(responseKey, data) {
const row = data.find((item) => responseKey in item);
assert(row, "the response has no value for the metric");
return row[responseKey];
}
async function executeMetric(query, handle, filters) {
const target = resolveTarget(query, "read");
const filterCriteria = await readFilterCriteria(target, filters);
if (filterCriteria === null) return {
value: handle.aggregation === "COUNT" || handle.aggregation === "DISTINCT" ? 0 : null,
executionTimestamp: /* @__PURE__ */ new Date()
};
const { actionId } = target;
const { body, responseKey } = buildMetricRequest(handle, filterCriteria);
const res = await fetch(`${dsUrl(actionId)}/chart/data`, {
method: "POST",
headers: {
"Content-Type": "application/json",
"X-User-Timezone": readUserTimezone() ?? "UTC",
Authorization: `Bearer ${readSessionToken()}`,
...refererHeader()
},
body: JSON.stringify(body)
});
if (!res.ok) throw new Error(`datasource metric failed for action "${actionId}": ${await describeFailure(res)}`);
const payload = await res.json();
return {
value: readMetricValue(responseKey, payload.data),
executionTimestamp: /* @__PURE__ */ new Date(payload.executionTimestamp * 1e3)
};
}
//#endregion
export { chart, metric };