Skip to Content
TelamonJS

Data

The server half of a list — the ListPage wire contract, sort and paging sanitizers, a Prisma adapter with scope-safe where and paginated services, and NestJS plumbing

@telamonjs/data (current version: 1.4.0) is what an endpoint runs on what a ListPage sends: page, page size, search, sort and filters. It has no dependencies and imports neither React, Next nor Prisma, so a NestJS or plain Node API installs it alone. A NestJS API also gets the Prisma exception filter, health endpoint and audit interceptor every API repeats.

pnpm add @telamonjs/data
EntryWhat it hasNeeds an ORM?
@telamonjs/dataThe wire contract (PaginationParams, PaginatedResponse, SortField, createPaginatedResponse), sanitizePaginationParams, resolveSort, resolveSortPath; the audit helpers computeDiff, redactPayload, DEFAULT_REDACT_KEYSNo
@telamonjs/data/prismabuildPrismaOrderBy, buildPrismaOrderByMulti, buildSearchConditions, buildFilterConditions, buildWhereClause, createPaginationContextBuilds Prisma's object shape; never imports @prisma/client
@telamonjs/data/nestPrismaExceptionFilter, HealthModule, createAuditInterceptor, SkipAudit, isPrismaKnownRequestError, isPrismaValidationErrorNeeds @nestjs/common and rxjs (optional peers); never imports @prisma/client

Sort

A list sends the sort field as the column's data path (customer.name, with list.sortParam: 'path') or as the TanStack column id (customer_name, the default). Both resolve to the same path, and _count.<relation> orders by a relation count:

import { resolveSortPath } from '@telamonjs/data'
import { buildPrismaOrderBy } from '@telamonjs/data/prisma'

resolveSortPath('customer_name')                          // 'customer.name'
buildPrismaOrderBy('customer_name', 'asc')                // { customer: { name: 'asc' } }
buildPrismaOrderBy('_count.items', 'desc')                // { items: { _count: 'desc' } }
buildPrismaOrderBy('created_at', 'asc', ['created_at'])   // { created_at: 'asc' }

Pass the endpoint's sortableFields. A listed snake_case field (created_at) then stays a scalar instead of being read as created.at, and resolveSort rejects any field that is not listed, falling back to the default sort.

import { resolveSort } from '@telamonjs/data'

const sort = resolveSort(query.sortBy ?? 'name', query.sortOrder, {
  defaultOrderBy: 'name',
  defaultOrderDirection: 'asc',
  sortableFields: ['name', 'customer.name', 'created_at'],
})

With another ORM or plain SQL, resolveSort and resolveSortPath are all you need to build your own ORDER BY.

Where

buildWhereClause combines search and filters with the endpoint's baseWhere and the user's visibility rule using AND. None of them can overwrite another, even when they share a key or use OR:

import { buildSearchConditions, buildWhereClause } from '@telamonjs/data/prisma'

const where = buildWhereClause(
  buildSearchConditions(query.search, ['name', 'customer.name']),
  [],
  { deletedAt: null },
  { OR: [{ ownerId: user.id }, { public: true }] }
)

Paginated services

createPaginationContext builds a list (and getFilterOptions) per model from a declarative config: search fields, typed filters, sortableFields, visibility, relation counts and hooks.

import { createPaginationContext } from '@telamonjs/data/prisma'

export const { createPaginatedService } = createPaginationContext({
  prisma,
  auth, // () => Promise<{ user } | null>
  filterLabels: () => ({ yes: 'Sim', no: 'Não', active: 'Ativo', inactive: 'Inativo' }),
})

export const customers = createPaginatedService({
  model: 'customer',
  searchFields: ['name', 'email'],
  filters: { active: 'boolean', state: 'string' },
  sortableFields: ['name', 'created_at', '_count.orders'],
})

filterLabels receives the locale passed to getFilterOptions and returns the labels of boolean filter options; without it they are in English. Configuration warnings go to onWarning (default console.warn).

NestJS

@telamonjs/data/nest needs @nestjs/common and rxjs, optional peers that only this entry imports (every Nest app already has both):

Peer dependencyRange
@nestjs/common (optional)^10.0.0 || ^11.0.0
rxjs (optional)^7.1.0

Prisma errors as HTTP statuses

PrismaExceptionFilter answers Prisma errors with a status instead of a 500. It matches Prisma's known-request and validation errors by shape (code + name/clientVersion), so it works with any @prisma/client copy, and it never claims other errors: your own filters and Nest's default handling still get them.

import { PrismaExceptionFilter } from '@telamonjs/data/nest'

app.useGlobalFilters(new PrismaExceptionFilter())
PrismaHTTP
P2002 unique409, field = first target field
P2003 foreign key400, field = constraint
P2025 not found404
P2011, P2012, P2014, PrismaClientValidationError400
P1000–P1003 connection503
any other code500, logged with Nest's Logger

The body is { statusCode, message, error, field?, timestamp, path }, written with Express's res.status().json(). Outside HTTP (RPC, WebSocket, GraphQL) the error is rethrown. Messages are English; replace them (in your app's language, say) per code, validation or default, with a string or a function of the reported fields:

new PrismaExceptionFilter({
  messages: {
    P2025: 'Nothing here',
    P2002: (fields) => `${fields.join(', ')} is already taken`,
  },
})

To change one case (say, P2003 on a DELETE as 409), subclass it, handle that case in catch and call super.catch(exception, host) for the rest.

Health endpoint

HealthModule.forRoot() serves GET /health. It runs the checks in parallel and answers 200, or 503 with status: 'error' when any check is down, so Docker and load balancers can read the status code (downStatus: 200 keeps 200 for setups that read only the body):

import { Public } from '@telamonjs/auth/nest'
import { HealthModule } from '@telamonjs/data/nest'

HealthModule.forRoot({
  decorators: [Public()],             // class decorators for the controller
  inject: [PrismaService, REDIS],
  checks: (prisma: PrismaService, redis: Redis) => ({
    database: () => prisma.$queryRaw`SELECT 1`,
    redis: () => redis.ping(),
  }),
})
// GET /health → { status: 'ok', timestamp, uptime, database: 'connected', redis: 'connected' }

A check is down when it throws, rejects or resolves false. path changes the route (default 'health'); imports brings in the modules of the inject tokens when they are not global. The package imports no auth: pass the auth package's @Public() in decorators when a global guard protects every route.

Audit trail

createAuditInterceptor() returns an interceptor class that turns every successful, authenticated POST/PUT/PATCH/DELETE into an AuditEntry and hands it to your write. The package owns no table: you persist the entry wherever you keep audit rows.

import { APP_INTERCEPTOR } from '@nestjs/core'
import { createAuditInterceptor } from '@telamonjs/data/nest'

export const AuditInterceptor = createAuditInterceptor({
  inject: [PrismaService],
  write: (entry, _context, prisma: PrismaService) => prisma.auditLog.create({ data: entry }),
})

// app.module.ts
providers: [{ provide: APP_INTERCEPTOR, useClass: AuditInterceptor }]

A Prisma model that takes the entry as it is:

model AuditLog {
  id             String   @id @default(cuid())
  userId         String
  impersonatedBy String?
  action         String   // CREATE | UPDATE | DELETE
  entityType     String
  entityId       String?
  changes        Json?
  ipAddress      String?
  userAgent      String?
  method         String
  path           String
  statusCode     Int
  createdAt      DateTime @default(now())

  @@index([entityType, entityId])
  @@index([userId, createdAt])
}
Entry fieldComes from
userId, impersonatedByrequest.user.id and request.user.originalUser.id, the @telamonjs/auth user (user option to read another shape)
actionPOST → CREATE, PUT/PATCH → UPDATE, DELETE → DELETE; any other audited method as is
entityType, entityIdThe first path segment that is not api or a version (/v1/orders/42 → orders), and the :id param or the response body's id (resolveEntity option to change both)
changesThe request body through redactPayload; absent when the body is empty
ipAddress, userAgentrequest.ip (set Express's trust proxy behind a proxy) and the User-Agent header
method, path, statusCodeThe request, without the query string, and the status Nest answered with

Nothing is written when the handler throws, when there is no user (logins, public sign-ups) or outside HTTP. The response does not wait for write (await: true makes it wait), and a write that throws or rejects goes to onError (default: Nest's Logger) and never fails the request.

createAuditInterceptor({
  write,
  methods: ['POST', 'PUT', 'PATCH', 'DELETE'],     // the default
  ignore: (ctx) => ctx.switchToHttp().getRequest().path.startsWith('/v1/webhooks'),
  redact: ['ssn'],                                 // added to DEFAULT_REDACT_KEYS
  resolveEntity: (ctx, body) => ({ type: ctx.getClass().name, id: (body as { id?: string })?.id }),
  onError: (error, entry) => logger.warn({ error, entry }, 'audit write failed'),
})

@SkipAudit() on a handler or a controller skips it, the same as ignore.

Audit helpers

The root entry has the two pure helpers the interceptor and hand-written audit calls share. redactPayload(value, keys = DEFAULT_REDACT_KEYS) returns a deep copy with the value of every secret key replaced by '[REDACTED]'. A key is secret when, lowercased and without -/_, it contains one of keys: password catches newPassword, senha catches novaSenha, token catches REFRESH_TOKEN, apikey catches api-key. Spread DEFAULT_REDACT_KEYS to add your own.

computeDiff(before, after) returns the fields of after that changed, as { key: { old, new } }. It reads only the keys of after, so a partial DTO works; null equals undefined, dates compare by instant, a Decimal or numeric string compares as a number, and nested objects and arrays compare as JSON. createdAt and updatedAt are skipped ({ ignore } replaces that list). Use it where you already load the record, for an UPDATE row with before and after:

import { computeDiff } from '@telamonjs/data'

const before = await prisma.order.findUniqueOrThrow({ where: { id } })
await prisma.order.update({ where: { id }, data: dto })
const changes = computeDiff(before, dto)   // { status: { old: 'OPEN', new: 'PAID' } }; {} when nothing changed

On this page