@rationalbloks/frontblok-crud
v0.1.0
Published
Universal CRUD API layer for RationalBloks frontends
Downloads
31
Maintainers
Readme
@rationalbloks/frontblok-crud
Universal CRUD API Layer for RationalBloks Frontends
The TypeScript equivalent of builderblok - a single, generic API layer that works with ANY entity schema.
🎯 Philosophy
┌─────────────────────────────────────────────────────────────────────────┐
│ THE BUILDERBLOK PATTERN │
├─────────────────────────────────────────────────────────────────────────┤
│ │
│ BACKEND (builderblok) FRONTEND (frontblok-crud) │
│ ═══════════════════ ════════════════════════ │
│ │
│ JSON Schema JSON Schema │
│ │ │ │
│ ▼ ▼ │
│ entities.py ◄── ONLY GENERATED entities.ts ◄── ONLY GENERATED │
│ │ │ │
│ ▼ ▼ │
│ models.py ─┐ api.ts ──────┐ │
│ crud.py ───┼── 100% GENERIC hooks.ts ────┼── 100% GENERIC │
│ routes.py ─┘ utils.ts ────┘ │
│ │
└─────────────────────────────────────────────────────────────────────────┘Only ONE file is generated (entities.ts). Everything else is generic and works with ANY schema.
📦 Installation
npm install @rationalbloks/frontblok-crudRequires peer dependencies:
npm install react @rationalbloks/frontblok-auth🚀 Quick Start
1. Initialize API (once at app startup)
// main.tsx or App.tsx
import { initApi } from '@rationalbloks/frontblok-crud';
initApi(import.meta.env.VITE_DATABASE_API_URL);2. Use Hooks in Components
// TaskList.tsx
import { useEntityList, useMutation } from '@rationalbloks/frontblok-crud';
import type { Task } from './entities'; // Generated file
function TaskList() {
const { items, loading, error, refetch } = useEntityList<Task>('tasks');
const { mutate } = useMutation<Task>('tasks');
const handleDelete = async (id: string) => {
await mutate.remove(id);
refetch();
};
if (loading) return <CircularProgress />;
if (error) return <Alert severity="error">{error.message}</Alert>;
return (
<ul>
{items.map(task => (
<li key={task.id}>
{task.title}
<button onClick={() => handleDelete(task.id)}>Delete</button>
</li>
))}
</ul>
);
}3. Use Direct API Access
import { getApi } from '@rationalbloks/frontblok-crud';
import type { Task } from './entities';
// Get all tasks
const tasks = await getApi().getAll<Task>('tasks');
// Get single task
const task = await getApi().getOne<Task>('tasks', 'uuid-here');
// Create task
const newTask = await getApi().create<Task>('tasks', { title: 'New Task' });
// Update task
const updated = await getApi().update<Task>('tasks', 'uuid-here', { status: 'done' });
// Delete task
await getApi().remove('tasks', 'uuid-here');📚 API Reference
Initialization
| Function | Description |
|----------|-------------|
| initApi(baseUrl, getToken?) | Initialize the global API instance |
| getApi() | Get the global API instance (throws if not initialized) |
| isApiInitialized() | Check if API has been initialized |
| resetApi() | Reset the API instance (for testing) |
Hooks
| Hook | Description |
|------|-------------|
| useEntityList<T>(entityName, options?) | Fetch list of entities |
| useEntity<T>(entityName, id?) | Fetch single entity by ID |
| useMutation<T>(entityName) | Create, update, delete entities |
| useEntityForm<T>(entityName, id?) | Combined entity + mutation for forms |
Generator (MCP use only)
| Function | Description |
|----------|-------------|
| generateEntitiesTs(schema) | Generate complete entities.ts from schema |
| validateSchema(schema) | Validate schema before generation |
📁 Generated entities.ts Example
Given this schema:
{
"tasks": {
"title": { "type": "string", "max_length": 200, "required": true },
"status": { "type": "string", "max_length": 50, "enum": ["pending", "done"] },
"due_date": { "type": "date" }
}
}The generator creates:
// entities.ts - Generated by RationalBloks MCP
// DO NOT EDIT MANUALLY
import type { BaseEntity, CreateInput, UpdateInput, EntityRegistry } from '@rationalbloks/frontblok-crud';
// ----------------------------------------------------------------------------
// Task
// ----------------------------------------------------------------------------
export interface Task extends BaseEntity {
title: string;
status?: 'pending' | 'done';
due_date?: string;
}
export type CreateTaskInput = CreateInput<Task>;
export type UpdateTaskInput = UpdateInput<Task>;
// ============================================================================
// ENTITY REGISTRY
// ============================================================================
export const entities = {
tasks: {
singular: 'task',
plural: 'tasks',
fields: {
title: { type: 'string', required: true, max_length: 200 },
status: { type: 'string', enum: ['pending', 'done'] },
due_date: { type: 'date' }
},
},
} as const satisfies EntityRegistry;
export type Entities = typeof entities;
export type EntityName = keyof Entities;🏗️ Architecture
Files in this package:
| File | Purpose | Generated? |
|------|---------|------------|
| api.ts | Universal CRUD API client | ❌ NO (generic) |
| hooks.ts | React hooks for data fetching | ❌ NO (generic) |
| types.ts | TypeScript type definitions | ❌ NO (generic) |
| utils.ts | Helper functions | ❌ NO (generic) |
| generator.ts | Generates entities.ts | ❌ NO (used by MCP) |
What gets generated in user's project:
| File | Purpose | Generated? |
|------|---------|------------|
| entities.ts | TypeScript interfaces + entity registry | ✅ YES |
That's it. ONE file. ~50 lines.
🔗 Integration with frontblok-auth
This package builds on top of @rationalbloks/frontblok-auth:
┌─────────────────────────────────────────────────────────────────────────┐
│ USER'S PROJECT │
├─────────────────────────────────────────────────────────────────────────┤
│ │
│ ┌───────────────────────────────────────────────────────────────────┐ │
│ │ UI LAYER (user's choice) │ │
│ │ - React components │ │
│ │ - Routing (react-router) │ │
│ │ - Styling (MUI, Tailwind, etc.) │ │
│ └───────────────────────────────────────────────────────────────────┘ │
│ │ │
│ ▼ │
│ ┌───────────────────────────────────────────────────────────────────┐ │
│ │ @rationalbloks/frontblok-crud │ │
│ │ - entities.ts (GENERATED - types + metadata) │ │
│ │ - api.ts (GENERIC - universal CRUD) │ │
│ │ - hooks.ts (GENERIC - React data hooks) │ │
│ └───────────────────────────────────────────────────────────────────┘ │
│ │ │
│ ▼ │
│ ┌───────────────────────────────────────────────────────────────────┐ │
│ │ @rationalbloks/frontblok-auth │ │
│ │ - BaseApi (HTTP client with auth) │ │
│ │ - Auth hooks │ │
│ │ - Token management │ │
│ └───────────────────────────────────────────────────────────────────┘ │
│ │ │
└───────────────────────────────┼─────────────────────────────────────────┘
│
▼
┌──────────────────────┐
│ RationalBloks API │
│ (generated by │
│ builderblok) │
└──────────────────────┘📝 License
MIT © RationalBloks Team
