Skip to Content
TelamonJS

CrudConfig

The central concept of TelamonJS — one object that drives an entire CRUD module

CrudConfig<T, TFormData> is the central concept of TelamonJS. One object holds everything a CRUD module needs — module metadata, list columns, form sections, data fetching, mutations, row actions and dialogs — and ListPage reads it all from a single prop.

<ListPage config={config} />

'use client' is required

The config.tsx file MUST start with 'use client': query and mutations are wired to React Query hooks, which only run client-side.


Anatomy

KeyTypeRequiredPurpose
moduleModuleMetadataYesIdentification: name, title, description, route (all required)
listListConfig<T>Yestitle, description (required), columns, search placeholder, sorting, page size, toolbar
formFormConfigNoForm sections + Zod validation (optional), shared by the create and edit dialogs. Omit it for a read-only list
queryQueryConfig<T>YesReact Query: queryKey, queryFn, staleTime?, refetchInterval?
mutationsMutationsConfig<T, TFormData>Yescreate/update/delete (each a MutationConfig) with declarative invalidates, plus getForEdit/getForView
actionsConfigDataTableActionsConfig<T> | falseNoRow action buttons: standard: { view, edit, delete } + custom actions
dialogsDialogsConfig<T>NoView/edit/create dialogs: rich headers, the view body, deep links via urlParam
pagesPagesConfig<T>NoDedicated pages instead of dialogs (see Standalone form pages)
permissionsCrudPermissionsNoWho may create, edit, delete, view and export (see Permissions)

create, update and delete are each optional: an omitted one resolves { success: false } instead of throwing, so a read-only module needs no stub mutations.

A read-only list also needs no form: without form, ListPage offers no "New" button and no create or edit dialog, even if dialogs.create / dialogs.edit are set. The view dialog keeps working.

Permissions

permissions names the permission each operation needs (a string, or an array meaning any of them). An operation without one stays allowed:

import { createPermissionChecker } from '@telamonjs/permissions'
import type { AuthUser } from '@telamonjs/auth'

const checker = createPermissionChecker({ bypassRoles: ['superadmin'] })

export function usuariosConfigFor(user: AuthUser): CrudConfig<Usuario, UsuarioFormData> {
  return {
    ...usuariosConfig,
    permissions: {
      can: perm => checker.can(user, perm),
      create: 'usuarios.create',
      edit: 'usuarios.update',
      delete: 'usuarios.delete',
      view: 'usuarios.read',
    },
  }
}
OperationGates
createthe "New" button and the create dialog (?create=1 included)
editthe row edit, the view dialog's Edit, the edit dialog and dialogs.view.portal.onSaveSection
deletethe row delete and the view dialog's Delete
viewthe row view and the view dialog (row click included)
exportthe toolbar export menu (list.enableExport / list.onExport)

The checker is can when set, so bypass roles and wildcards work as your checker defines them. Without can, the names are looked up in actionsConfig.userPermissions; without either, the can of a PermissionsProvider above the list decides. The row view/edit/delete inherit the operation's permission unless their own ActionConfig declares a permission, and the same checker decides the permission of custom actions (permissions.can becomes actionsConfig.can).

With no checker at all, everything is allowed: the gate is fail-open, so a config that forgot the checker shows every write button. In development the list warns once per config when that happens. Set failClosed: true (same meaning as in @telamonjs/permissions) to deny every declared operation and every action permission until a checker exists — for example while the session that feeds can is still loading:

permissions: {
  failClosed: true,
  can: session ? perm => checker.can(session.user, perm) : undefined,
  create: 'usuarios.create',
},

One checker for the whole app

Instead of injecting can into every config, give it once to a PermissionsProvider where the session is readable (inside the app's SessionProvider, around the AdminShell). Every ListPage below uses it for permissions.* and action permissions, and AdminShell filters the menu with it. A config then only names its permissions:

components/providers/LayoutProviders.tsx
'use client'

import { useCallback } from 'react'
import { useSession } from 'next-auth/react'
import { AdminShell, PermissionsProvider } from '@telamonjs/ui'

export function LayoutProviders({ children }: { children: React.ReactNode }) {
  const { data: session } = useSession()
  const can = useCallback((perm: string) => checker.can(session?.user, perm), [session])
  return (
    <PermissionsProvider can={can}>
      <AdminShell menuConfig={menuConfig}>{children}</AdminShell>
    </PermissionsProvider>
  )
}
config.tsx
permissions: { create: 'usuarios.create', edit: 'usuarios.update', export: 'usuarios.export' },

A checker the config declares itself (permissions.can, actionsConfig.can or actionsConfig.userPermissions) wins over the provider's, and so does AdminShell's own can for the menu. Without a provider, nothing changes.


Canonical example

This is the reference module every generated app ships (src/app/admin/usuarios/config.tsx). It is compiled in CI, so it always matches the current API. Other pages show excerpts of it and link here.

src/app/admin/usuarios/config.tsx
'use client'

import { z } from 'zod'
import {
  Badge,
  type CrudColumnDef,
  type CrudConfig,
  type DialogHeaderConfig,
  type FormSection,
} from '@telamonjs/ui'
import { msg, Msg } from '@telamonjs/ui/i18n'
import { getIcon } from '@/lib/icons'
import { usuariosApi, type Usuario } from '@/lib/api/usuarios-client'
import { rolesApi } from '@/lib/api/roles-client'
import { formatDate } from '@/lib/utils'
import UsuarioDetail from './_components/UsuarioDetail'

// ============================================================================
// 1. VALIDATION SCHEMA
// ============================================================================
export const validationSchema = z.object({
  name: z.string().min(1),
  email: z.string().email(),
  // Required on create, optional on edit (blank keeps the current password) --
  // enforced server-side in the API route, not here.
  password: z.string().min(5).optional().or(z.literal('')),
  // Multi-role: the user holds the union of the roles' permissions
  roleIds: z.array(z.string()).default([]),
  // AdminForm's FormData submit path serializes booleans as the literal
  // strings 'true'/'false' -- z.coerce.boolean() would treat ANY non-empty
  // string (including 'false') as true, so coerce explicitly instead.
  active: z.preprocess((v) => (typeof v === 'string' ? v === 'true' : v), z.boolean()).default(true),
})

export type UsuarioFormData = z.infer<typeof validationSchema>

// ============================================================================
// 2. HEADER CONFIG (view/edit/create dialogs)
// ============================================================================
const headerConfig: DialogHeaderConfig<Usuario> = {
  icon: 'User',
  iconColor: 'blue',
  title: (u) => u.name ?? u.email,
  subtitle: (u) => u.email,
  gradient: 'from-blue-50 to-indigo-50',
  badge: {
    field: 'active',
    variants: { true: 'default', false: 'secondary' },
    labels: { true: msg('usuarios.statusActive'), false: msg('usuarios.statusInactive') },
  },
}

// ============================================================================
// 3. COLUMNS
// ============================================================================
export const columns: CrudColumnDef<Usuario>[] = [
  {
    header: msg('usuarios.columns.name'),
    accessorKey: 'name',
    enableGlobalFilter: true,
    cell: ({ row }) => (
      <div>
        <div className='font-medium'>{row.original.name || <Msg k='usuarios.noName' />}</div>
        <div className='text-xs text-muted-foreground'>{row.original.email}</div>
      </div>
    ),
  },
  {
    header: msg('usuarios.columns.roles'),
    id: 'roles',
    enableSorting: false,
    cell: ({ row }) =>
      row.original.roles.length ? (
        <div className='flex flex-wrap gap-1'>
          {row.original.roles.map((role) => (
            <Badge key={role.id} variant='outline'>
              {role.name}
            </Badge>
          ))}
        </div>
      ) : (
        <span className='text-sm text-muted-foreground'>
          <Msg k='usuarios.noRoles' />
        </span>
      ),
  },
  {
    header: msg('usuarios.columns.status'),
    accessorKey: 'active',
    cell: ({ row }) => (
      <Badge variant={row.original.active ? 'default' : 'secondary'}>
        <Msg k={row.original.active ? 'usuarios.statusActive' : 'usuarios.statusInactive'} />
      </Badge>
    ),
  },
  {
    header: msg('usuarios.columns.createdAt'),
    accessorKey: 'createdAt',
    cell: ({ row }) => (
      <span className='text-sm text-muted-foreground'>{formatDate(row.original.createdAt)}</span>
    ),
  },
]

// ============================================================================
// 4. FORM SECTIONS (rendered inside the create/edit dialogs)
// ============================================================================
export const formSections: FormSection[] = [
  {
    label: msg('usuarios.sections.personal.label'),
    description: msg('usuarios.sections.personal.description'),
    grid: '2',
    fields: [
      {
        name: 'name',
        label: msg('usuarios.fields.name'),
        type: 'text',
        placeholder: msg('usuarios.fields.namePlaceholder'),
        required: true,
        focus: true,
      },
      {
        name: 'email',
        label: msg('usuarios.fields.email'),
        type: 'email',
        placeholder: msg('usuarios.fields.emailPlaceholder'),
        required: true,
      },
    ],
  },
  {
    label: msg('usuarios.sections.access.label'),
    description: msg('usuarios.sections.access.description'),
    grid: '2',
    fields: [
      {
        name: 'password',
        label: msg('usuarios.fields.password'),
        type: 'password',
        placeholder: msg('usuarios.fields.passwordPlaceholder'),
        description: msg('usuarios.fields.passwordDescription'),
      },
      {
        name: 'roleIds',
        label: msg('usuarios.fields.roles'),
        type: 'multiselect',
        description: msg('usuarios.fields.rolesDescription'),
        // Options are domain data (role names), not chrome text.
        loadField: async () => {
          const { data } = await rolesApi.list({ page: 1, pageSize: 100 })
          return data.map((role) => ({ value: role.id, label: role.name }))
        },
      },
      {
        name: 'active',
        label: msg('usuarios.fields.active'),
        type: 'boolean',
        description: msg('usuarios.fields.activeDescription'),
        // span = section grid -> full width (className 'w-full' is a no-op: CSS Grid)
        span: '2',
      },
    ],
  },
]

// ============================================================================
// 5. CRUD CONFIG
// ============================================================================
export const usuariosConfig: CrudConfig<Usuario, UsuarioFormData> = {
  module: {
    name: 'usuarios',
    title: msg('usuarios.title'),
    description: msg('usuarios.description'),
    route: '/admin/usuarios',
  },

  // Checked with the PermissionsProvider's `can` (LayoutProviders): a denied
  // operation loses its button, row action and dialog deep link. The Route
  // Handlers enforce the same codes.
  permissions: {
    view: 'users.read',
    create: 'users.write',
    edit: 'users.write',
  },

  list: {
    // Empty: the shell breadcrumb already names the page; the list is content, not a header.
    title: '',
    description: '',
    searchPlaceholder: msg('usuarios.searchPlaceholder'),
    columns,
    defaultSortBy: 'name',
    defaultSortOrder: 'asc',
    serverSidePagination: true,
    infiniteScroll: true,
    defaultPageSize: 100,
    // ICU plural: the message takes `{count}` (messages/*.json)
    toolbar: { counterLabel: msg('usuarios.counter') },
  },

  form: { sections: formSections, validation: validationSchema },

  query: { queryKey: ['usuarios'], queryFn: usuariosApi.list, staleTime: 30_000 },

  mutations: {
    // mutationFn must resolve to { success, data? } -- usuariosApi.* returns
    // the raw entity, so we shape the result here rather than in the client.
    create: {
      mutationFn: async (data) => ({ success: true, data: await usuariosApi.create(data) }),
      invalidates: [['usuarios']],
    },
    update: {
      mutationFn: async ({ id, data }) => {
        // Blank password means "keep the current one" -- don't send it.
        const { password, ...rest } = data
        return { success: true, data: await usuariosApi.update(id, password ? data : rest) }
      },
      invalidates: [['usuarios']],
    },
    // No delete: users are deactivated (row action below), never removed.
    getForEdit: async (id) => {
      const u = await usuariosApi.getById(id)
      return {
        name: u.name ?? '',
        email: u.email,
        password: '',
        roleIds: u.roles.map((role) => role.id),
        active: u.active,
      }
    },
    getForView: usuariosApi.getById,
  },

  actionsConfig: {
    standard: {
      view: { icon: getIcon('Eye'), tooltip: msg('usuarios.actions.view') },
      edit: { icon: getIcon('Pencil'), tooltip: msg('usuarios.actions.edit') },
    },
    // The list refetches after a custom handler succeeds.
    custom: [
      {
        id: 'deactivate',
        icon: getIcon('UserX'),
        tooltip: msg('usuarios.actions.deactivate'),
        permission: 'users.write',
        visible: (row) => row.active,
        handler: (row) => usuariosApi.update(row.id, { active: false }),
        successMessage: msg('usuarios.actions.deactivated'),
        confirmDialog: {
          title: (row) => msg('usuarios.confirmDeactivate.title', { name: row.name ?? row.email }),
          description: msg('usuarios.confirmDeactivate.description'),
          confirmText: msg('usuarios.confirmDeactivate.confirmText'),
          cancelText: msg('usuarios.confirmDeactivate.cancelText'),
          variant: 'destructive',
        },
      },
      {
        id: 'activate',
        icon: getIcon('UserCheck'),
        tooltip: msg('usuarios.actions.activate'),
        permission: 'users.write',
        visible: (row) => !row.active,
        handler: (row) => usuariosApi.update(row.id, { active: true }),
        successMessage: msg('usuarios.actions.activated'),
      },
    ],
  },

  dialogs: {
    view: {
      urlParam: 'view',
      title: msg('usuarios.dialogs.view.title'),
      headerConfig,
      renderContent: (item) => <UsuarioDetail usuario={item} />,
    },
    edit: {
      urlParam: 'edit',
      title: msg('usuarios.dialogs.edit.title'),
      description: msg('usuarios.dialogs.edit.description'),
      headerConfig,
    },
    create: {
      urlParam: 'create',
      title: msg('usuarios.dialogs.create.title'),
      description: msg('usuarios.dialogs.create.description'),
      headerConfig: {
        ...headerConfig,
        title: msg('usuarios.dialogs.create.title'),
        subtitle: undefined,
        badge: undefined,
      },
      defaultValues: { active: true, roleIds: [] },
    },
  },
}

The page stays a one-liner:

src/app/admin/usuarios/page.tsx
'use client'

import { ListPage } from '@telamonjs/ui'
import { usuariosConfig } from './config'

// All CRUD (view/create/edit/delete) happens in dialogs on this list —
// there are no adicionar/ or [id]/ routes.
export default function UsuariosPage() {
  return <ListPage config={usuariosConfig} />
}

What to notice:

  • query.queryFn resolves PaginatedResponse<T> (data, page, total, totalPages). The list is an infinite, virtualized scroll by default and needs that metadata to page.
  • Every mutationFn resolves { success, data? }. The API client returns the raw entity; the config shapes it, not the client.
  • getForEdit maps the record to the form's shape (here it blanks the password and turns roles into roleIds); getForView passes the record to the view dialog as is.
  • permissions names the code each operation needs; the app's PermissionsProvider checks them, and the Route Handlers enforce the same codes. There is no delete: users are deactivated by a custom row action, and the list refetches after its handler succeeds.
  • dialogs replace create, edit and detail routes. urlParam makes each one linkable (?view=<id>, ?edit=<id>, ?create=1), and Back closes it.
  • Text slots take msg('<key>') (from @telamonjs/ui/i18n) so they follow the active locale. Text rendered inside a cell uses <Msg k='<key>' />.
  • Icons are strings resolved through the app's registry (getIcon('Eye')), never Lucide components imported into the config.
  • relationship and multiselect (the roles here) load their options with loadField. There is no 'select' field type and no options prop.

Data flow

The generated app has one direction: Route Handler (Prisma) → <module>-client.ts (fetch) → config.tsx. In the monorepo layout the client calls the NestJS API instead. Either way, React Query manages it:

  • query.queryFn loads the list, cached under query.queryKey.
  • mutations.*.mutationFn calls the API client.
  • invalidates declares which query keys to refresh on success — it must match query.queryKey for the list to update.

All exported from @telamonjs/ui:

  • CrudConfig<T, TFormData> — the main interface
  • ModuleMetadata, ListConfig<T>, FormConfig
  • QueryConfig<T>, MutationConfig<TInput, TOutput>, MutationsConfig<T, TFormData>
  • DialogConfig<T>, DialogsConfig<T>, PagesConfig<T>
  • CrudPermissions — the permissions key
  • CrudConfigWithAnyForm<T> — alias for CrudConfig<T, any> when a context must accept any config (TFormData is invariant)

Next steps

  • Quick Start — generate a module like this one from a Prisma model
  • ListPage Pattern — everything ListPage does with your config
  • Dialogs — headers, detail tabs, the portal view
  • Form Pattern — sections, validation and field types

On this page