JavaScript SDK

Data filters

Turn a permission into a Prisma or SQL WHERE clause so a list returns only the rows the user may see.

A permission check answers one row at a time. For a list, ask for a filter once and put it in the query.

Get the filter#

const { data, error } = await admin.authzFilter({  userId,  action: "view",  resourceType: "invoice",  context: { region: "eu" },});// data: { permission, filter, step_up?, truncated? }

filter is "all", "none", or a condition over resource.key (the row key) and resource.<field> (row fields). A condition is JSON:

FormMeaning
{ "all": [c, ...] }, { "any": [c, ...] }, { "not": c }And, or, not
{ "eq": [a, b] }Also ne, lt, lte, gt, gte, in, contains, starts_with
{ "exists": { "var": "resource.x" } }The field has a value

An operand is a literal or { "var": "resource.field" }.

Missing values follow SQL's three-valued logic: a comparison that reads a missing field is unknown, not keeps it unknown, and a row matches only when the result is definitely true.

Prisma#

import { toPrismaWhere } from "@scute/js-core";const where = toPrismaWhere(data.filter, { key: "id", fields: { amount: "totalCents" } });const invoices = await prisma.invoice.findMany({ where });
OptionDefault
key"id": the model field that holds the row key
fieldsMaps condition fields to model fields; unmapped names are used as they are

"all" becomes {} and "none" becomes { OR: [] }, which matches no row.

SQL#

import { toSqlWhere } from "@scute/js-core";const { sql, params } = toSqlWhere(data.filter, {  columns: { key: "invoices.id", amount: "invoices.amount", region: "invoices.region" },});const rows = await db.query(`SELECT * FROM invoices WHERE ${sql}`, params);
Option
columnsRequired. Maps condition fields to column SQL. A field with no column throws (No column for resource.<name>). Column names never come from the filter.
placeholder(n) => string for the nth parameter. Default Postgres style $1.

Values are always bound as parameters. "all" becomes TRUE and "none" becomes FALSE. contains on a string and starts_with use strpos.

In memory#

import { matchesFilter, evaluateCondition } from "@scute/js-core";const visible = invoices.filter((row) => matchesFilter(data.filter, row));evaluateCondition({ lt: [{ var: "resource.amount" }, 5000] }, { resource: { amount: 1200 } }); // true

matchesFilter(filter, row) reads row fields by name; a condition on resource.key reads a field named key, so put the row key there. evaluateCondition(condition, attrs) returns true, false or "unknown"; null counts as missing.