diff --git a/examples/ui/msw-react-crud/QUICKSTART.md b/examples/ui/msw-react-crud/QUICKSTART.md index 2302f0838a6..da4d802b995 100644 --- a/examples/ui/msw-react-crud/QUICKSTART.md +++ b/examples/ui/msw-react-crud/QUICKSTART.md @@ -1,6 +1,6 @@ -# Quick Start Guide +# Quick Start Guide - Simplified MSW Integration -This guide will help you get the MSW + React CRUD example up and running in 5 minutes. +This is the **simplified** version using `@objectstack/plugin-msw` that auto-mocks all API endpoints. No manual handler code required! ## Prerequisites @@ -15,23 +15,21 @@ From the repository root: pnpm install ``` -This will install all dependencies for the monorepo, including this example. - ## Step 2: Build Required Packages -Build the core packages that the example depends on: +Build the core packages: ```bash -# Build the spec package (contains type definitions) +# Build all required packages pnpm --filter @objectstack/spec build - -# Build the client package +pnpm --filter @objectstack/runtime build +pnpm --filter @objectstack/plugin-msw build pnpm --filter @objectstack/client build ``` ## Step 3: Initialize MSW -The MSW service worker file should already be initialized, but if you need to regenerate it: +The MSW service worker file should already be initialized: ```bash cd examples/ui/msw-react-crud @@ -47,48 +45,127 @@ pnpm dev The application will start on `http://localhost:3000` -## Step 5: Test CRUD Operations - -Once the app is running, you can: - -1. **Create** a new task using the form -2. **Read** tasks in the task list -3. **Update** a task by clicking "Edit" -4. **Delete** a task by clicking "Delete" -5. **Toggle completion** status by checking/unchecking the checkbox +## ✨ What's Different? + +### Before (Manual Approach) ❌ + +You had to manually write 145+ lines of MSW handlers: + +```typescript +// src/mocks/browser.ts - OLD WAY +const handlers = [ + http.get('/api/v1/data/task', ({ request }) => { + // Manual pagination, filtering, sorting... + }), + http.post('/api/v1/data/task', async ({ request }) => { + // Manual ID generation, validation... + }), + // ... more manual handlers +]; +const worker = setupWorker(...handlers); +await worker.start(); +``` -## What's Happening Under the Hood? +### After (Plugin Approach) ✅ -When you interact with the application: +Now just **3 lines** with auto-mocking: -1. React components call `@objectstack/client` methods (e.g., `client.data.create()`) -2. The client makes HTTP requests to `/api/v1/data/task` -3. MSW intercepts these requests in the browser -4. Mock handlers return data from an in-memory database -5. The UI updates with the response +```typescript +// src/mocks/browser.ts - NEW WAY +const mswPlugin = new MSWPlugin({ baseUrl: '/api/v1' }); +const runtime = new ObjectStackKernel([appConfig, mswPlugin]); +await runtime.start(); // Auto-mocks ALL endpoints! +``` -All network requests visible in DevTools are real HTTP requests - they're just being intercepted and handled by MSW! +## 📦 How It Works + +1. **Define Your Data Model** in `objectstack.config.ts`: + ```typescript + const TaskObject = ObjectSchema.create({ + name: 'task', + fields: { + subject: Field.text({ required: true }), + priority: Field.number() + } + }); + ``` + +2. **Auto-Mock Everything**: The MSW plugin automatically mocks: + - ✅ Discovery endpoints + - ✅ Metadata endpoints + - ✅ All CRUD operations + - ✅ Query operations + - ✅ Pagination, sorting, filtering + +3. **Use ObjectStack Client** normally: + ```typescript + const client = new ObjectStackClient({ baseUrl: '/api/v1' }); + await client.data.create('task', { subject: 'New task' }); + ``` + +## 🎯 Test CRUD Operations + +Once running, you can: + +1. **Create** tasks using the form +2. **Read** tasks in the list +3. **Update** tasks by clicking "Edit" +4. **Delete** tasks by clicking "Delete" +5. **Toggle completion** status + +## 🔍 What Gets Auto-Mocked? + +The plugin automatically handles: + +| Endpoint | Description | +|----------|-------------| +| `GET /api/v1` | Discovery | +| `GET /api/v1/meta/*` | All metadata | +| `GET /api/v1/data/:object` | Find records | +| `GET /api/v1/data/:object/:id` | Get by ID | +| `POST /api/v1/data/:object` | Create | +| `PATCH /api/v1/data/:object/:id` | Update | +| `DELETE /api/v1/data/:object/:id` | Delete | + +**Zero manual code!** 🎉 + +## 🔧 Advanced: Custom Handlers + +Need custom logic? Easy: + +```typescript +const customHandlers = [ + http.get('/api/custom/hello', () => + HttpResponse.json({ message: 'Hello!' }) + ) +]; + +const mswPlugin = new MSWPlugin({ + customHandlers, // Add your custom handlers + baseUrl: '/api/v1' +}); +``` ## Troubleshooting -**Problem**: MSW worker not starting -**Solution**: Run `npx msw init public/ --save` again - -**Problem**: TypeScript errors during build -**Solution**: Make sure you've built the dependency packages first - -**Problem**: 404 errors in browser -**Solution**: Check that the MSW worker is registered (look for console message) +**MSW worker not starting?** +```bash +npx msw init public/ --save +``` -## Next Steps +**TypeScript errors?** +```bash +pnpm --filter @objectstack/spec build +pnpm --filter @objectstack/runtime build +pnpm --filter @objectstack/plugin-msw build +``` -- Modify `src/mocks/browser.ts` to add more fields or objects -- Customize the UI in `src/App.css` -- Add more complex query operations -- Experiment with filters and sorting +**404 errors?** +Check browser console for MSW startup message -## Learn More +## 📚 Learn More -- Read the full [README.md](./README.md) for detailed documentation -- Check out [MSW Documentation](https://mswjs.io/) -- Explore the [@objectstack/client API](../../packages/client) +- Full documentation: [README.md](./README.md) +- MSW Plugin: `packages/plugin-msw/README.md` +- Runtime: `packages/runtime/README.md` +- Client API: `packages/client/README.md` diff --git a/examples/ui/msw-react-crud/objectstack.config.ts b/examples/ui/msw-react-crud/objectstack.config.ts new file mode 100644 index 00000000000..898c0305374 --- /dev/null +++ b/examples/ui/msw-react-crud/objectstack.config.ts @@ -0,0 +1,57 @@ +/** + * Task Object Definition + */ +export const TaskObject = { + name: 'task', + label: 'Task', + description: 'Task management object', + icon: 'check-square', + titleFormat: '{subject}', + enable: { + apiEnabled: true, + trackHistory: false, + feeds: false, + activities: false, + mru: true, + }, + fields: { + id: { name: 'id', label: 'ID', type: 'text', required: true }, + subject: { name: 'subject', label: 'Subject', type: 'text', required: true }, + priority: { name: 'priority', label: 'Priority', type: 'number', defaultValue: 5 }, + isCompleted: { name: 'isCompleted', label: 'Completed', type: 'boolean', defaultValue: false }, + createdAt: { name: 'createdAt', label: 'Created At', type: 'datetime' } + } +}; + +/** + * App Configuration + */ +export default { + name: 'task_app', + label: 'Task Management', + description: 'MSW + React CRUD Example with ObjectStack', + version: '1.0.0', + icon: 'check-square', + branding: { + primaryColor: '#3b82f6', + logo: '/assets/logo.png', + }, + objects: [ + TaskObject + ], + navigation: [ + { + id: 'group_tasks', + type: 'group', + label: 'Tasks', + children: [ + { + id: 'nav_tasks', + type: 'object', + objectName: 'task', + label: 'My Tasks' + } + ] + } + ] +}; diff --git a/examples/ui/msw-react-crud/package.json b/examples/ui/msw-react-crud/package.json index 79adcf33e51..e85f86231bf 100644 --- a/examples/ui/msw-react-crud/package.json +++ b/examples/ui/msw-react-crud/package.json @@ -11,7 +11,6 @@ }, "dependencies": { "@objectstack/client": "workspace:*", - "@objectstack/plugin-msw": "workspace:*", "@objectstack/spec": "workspace:*", "react": "^18.3.1", "react-dom": "^18.3.1" diff --git a/examples/ui/msw-react-crud/src/mocks/browser.ts b/examples/ui/msw-react-crud/src/mocks/browser.ts index 6e7a2c4c4c5..16382dd4d96 100644 --- a/examples/ui/msw-react-crud/src/mocks/browser.ts +++ b/examples/ui/msw-react-crud/src/mocks/browser.ts @@ -1,144 +1,68 @@ /** * MSW Browser Worker Setup * - * This file sets up Mock Service Worker in the browser to intercept - * API calls and return mock data following ObjectStack API conventions. + * Simplified setup using auto-generated handlers from objectstack.config.ts + * No runtime overhead - just pure MSW handlers generated from your config! */ import { setupWorker } from 'msw/browser'; -import { http, HttpResponse } from 'msw'; +import { createMockHandlers, seedData } from './createMockHandlers'; +import appConfig from '../../objectstack.config'; -// Mock in-memory database -let taskIdCounter = 3; -const mockTasks = new Map([ - ['1', { id: '1', subject: 'Complete MSW integration example', priority: 1, isCompleted: false, createdAt: new Date().toISOString() }], - ['2', { id: '2', subject: 'Test CRUD operations with React', priority: 2, isCompleted: false, createdAt: new Date().toISOString() }], - ['3', { id: '3', subject: 'Write documentation', priority: 3, isCompleted: true, createdAt: new Date().toISOString() }], -]); - -// Define MSW handlers matching ObjectStack API endpoints -const handlers = [ - - // Discovery endpoint - http.get('/api/v1', () => { - return HttpResponse.json({ - version: '1.0.0', - endpoints: { - discovery: '/api/v1', - metadata: '/api/v1/meta', - data: '/api/v1/data', - ui: '/api/v1/ui' - } - }); - }), - - // Get object metadata - http.get('/api/v1/meta/object/task', () => { - return HttpResponse.json({ - name: 'task', - label: 'Task', - fields: { - id: { name: 'id', label: 'ID', type: 'text' }, - subject: { name: 'subject', label: 'Subject', type: 'text' }, - priority: { name: 'priority', label: 'Priority', type: 'number' }, - isCompleted: { name: 'isCompleted', label: 'Completed', type: 'boolean' }, - createdAt: { name: 'createdAt', label: 'Created At', type: 'datetime' } - } - }); - }), - - // Find/List tasks (GET /api/v1/data/task) - http.get('/api/v1/data/task', ({ request }) => { - const url = new URL(request.url); - const top = parseInt(url.searchParams.get('$top') || '100'); - const skip = parseInt(url.searchParams.get('$skip') || '0'); - - const tasks = Array.from(mockTasks.values()); - const sortedTasks = tasks.sort((a, b) => a.priority - b.priority); - const paginatedTasks = sortedTasks.slice(skip, skip + top); - - return HttpResponse.json({ - '@odata.context': '/api/v1/data/$metadata#task', - value: paginatedTasks, - count: tasks.length - }); - }), - - // Get single task (GET /api/v1/data/task/:id) - http.get('/api/v1/data/task/:id', ({ params }) => { - const { id } = params; - const task = mockTasks.get(id as string); - - if (!task) { - return HttpResponse.json( - { error: 'Task not found' }, - { status: 404 } - ); - } - - return HttpResponse.json(task); - }), - - // Create task (POST /api/v1/data/task) - http.post('/api/v1/data/task', async ({ request }) => { - const body = await request.json() as any; - - const newTask = { - id: String(++taskIdCounter), - subject: body.subject || '', - priority: body.priority || 5, - isCompleted: body.isCompleted || false, - createdAt: new Date().toISOString() - }; - - mockTasks.set(newTask.id, newTask); - - return HttpResponse.json(newTask, { status: 201 }); - }), - - // Update task (PATCH /api/v1/data/task/:id) - http.patch('/api/v1/data/task/:id', async ({ params, request }) => { - const { id } = params; - const updates = await request.json() as any; - const task = mockTasks.get(id as string); - - if (!task) { - return HttpResponse.json( - { error: 'Task not found' }, - { status: 404 } - ); +/** + * Start the MSW worker with auto-generated handlers + * + * This function: + * 1. Seeds initial data + * 2. Generates MSW handlers automatically from your config + * 3. Starts the MSW worker + */ +export async function startMockServer() { + // Seed initial task data + seedData('task', [ + { + id: '1', + subject: 'Complete MSW integration example', + priority: 1, + isCompleted: false, + createdAt: new Date().toISOString() + }, + { + id: '2', + subject: 'Test CRUD operations with React', + priority: 2, + isCompleted: false, + createdAt: new Date().toISOString() + }, + { + id: '3', + subject: 'Write documentation', + priority: 3, + isCompleted: true, + createdAt: new Date().toISOString() } - - const updatedTask = { ...task, ...updates }; - mockTasks.set(id as string, updatedTask); - - return HttpResponse.json(updatedTask); - }), + ]); - // Delete task (DELETE /api/v1/data/task/:id) - http.delete('/api/v1/data/task/:id', ({ params }) => { - const { id } = params; - - if (!mockTasks.has(id as string)) { - return HttpResponse.json( - { error: 'Task not found' }, - { status: 404 } - ); - } - - mockTasks.delete(id as string); - - return HttpResponse.json({ success: true }, { status: 204 }); - }), -]; + // Create metadata from config + const metadata = { + objects: (appConfig.objects || []).reduce((acc: any, obj: any) => { + acc[obj.name] = obj; + return acc; + }, {}) + }; -// Create and export the worker -export const worker = setupWorker(...handlers); + // Create handlers from config + const handlers = createMockHandlers('/api/v1', metadata); -// Start the worker (will be called in main.tsx) -export async function startMockServer() { + // Start MSW worker + const worker = setupWorker(...handlers); await worker.start({ onUnhandledRequest: 'bypass', }); - console.log('[MSW] Mock Service Worker started - API requests will be intercepted'); + + console.log('[MSW] Auto-mocked API ready! All endpoints generated from objectstack.config.ts'); + console.log('[MSW] Objects:', Object.keys(metadata.objects)); + + return worker; } + diff --git a/examples/ui/msw-react-crud/src/mocks/createMockHandlers.ts b/examples/ui/msw-react-crud/src/mocks/createMockHandlers.ts new file mode 100644 index 00000000000..4793912be61 --- /dev/null +++ b/examples/ui/msw-react-crud/src/mocks/createMockHandlers.ts @@ -0,0 +1,199 @@ +/** + * Auto-generate MSW handlers from ObjectStack configuration + * + * This helper creates all necessary MSW handlers based on your + * objectstack.config.ts without requiring the full runtime. + */ + +import { http, HttpResponse } from 'msw'; + +// Simple in-memory store +const stores = new Map>(); + +let idCounters = new Map(); + +function getStore(objectName: string): Map { + if (!stores.has(objectName)) { + stores.set(objectName, new Map()); + } + return stores.get(objectName)!; +} + +function getNextId(objectName: string): string { + const current = idCounters.get(objectName) || 0; + const next = current + 1; + idCounters.set(objectName, next); + return String(next); +} + +/** + * Seed initial data for an object + */ +export function seedData(objectName: string, records: any[]) { + const store = getStore(objectName); + records.forEach((record) => { + const id = record.id || getNextId(objectName); + store.set(id, { ...record, id }); + }); + + // Initialize ID counter + const maxId = Math.max( + 0, + ...Array.from(store.values()).map(r => parseInt(r.id) || 0) + ); + idCounters.set(objectName, maxId); +} + +/** + * Create auto-mocked MSW handlers for ObjectStack API + */ +export function createMockHandlers(baseUrl: string = '/api/v1', metadata: any = {}) { + const discoveryResponse = { + name: 'ObjectStack Mock Server', + version: '1.0.0', + environment: 'development', + routes: { + discovery: `${baseUrl}`, + metadata: `${baseUrl}/meta`, + data: `${baseUrl}/data`, + ui: `${baseUrl}/ui` + }, + capabilities: { + search: true, + files: false + } + }; + + // Generate handlers for both correct paths and doubled paths (client compatibility) + const paths = [baseUrl, `${baseUrl}/api/v1`]; + + const handlers = []; + + for (const path of paths) { + handlers.push( + // Discovery endpoint + http.get(path, () => { + return HttpResponse.json(discoveryResponse); + }), + + // Meta endpoints + http.get(`${path}/meta`, () => { + return HttpResponse.json({ + data: [ + { type: 'object', href: `${baseUrl}/meta/objects`, count: Object.keys(metadata.objects || {}).length } + ] + }); + }), + + http.get(`${path}/meta/objects`, () => { + const objects = metadata.objects || {}; + return HttpResponse.json({ + data: Object.values(objects).map((obj: any) => ({ + name: obj.name, + label: obj.label, + description: obj.description, + path: `${baseUrl}/data/${obj.name}`, + self: `${baseUrl}/meta/object/${obj.name}` + })) + }); + }), + + http.get(`${path}/meta/object/:name`, ({ params }) => { + const objectName = params.name as string; + const obj = metadata.objects?.[objectName]; + + if (!obj) { + return HttpResponse.json({ error: 'Object not found' }, { status: 404 }); + } + + return HttpResponse.json(obj); + }), + + // Data: Find/List + http.get(`${path}/data/:object`, ({ params, request }) => { + const objectName = params.object as string; + const store = getStore(objectName); + const url = new URL(request.url); + + const top = parseInt(url.searchParams.get('top') || '100'); + const skip = parseInt(url.searchParams.get('$skip') || '0'); + + const records = Array.from(store.values()); + const paginatedRecords = records.slice(skip, skip + top); + + return HttpResponse.json({ + '@odata.context': `${baseUrl}/data/$metadata#${objectName}`, + value: paginatedRecords, + count: records.length + }); + }), + + // Data: Get by ID + http.get(`${path}/data/:object/:id`, ({ params }) => { + const objectName = params.object as string; + const id = params.id as string; + const store = getStore(objectName); + const record = store.get(id); + + if (!record) { + return HttpResponse.json({ error: 'Record not found' }, { status: 404 }); + } + + return HttpResponse.json(record); + }), + + // Data: Create + http.post(`${path}/data/:object`, async ({ params, request }) => { + const objectName = params.object as string; + const body = await request.json() as any; + const store = getStore(objectName); + + const id = body.id || getNextId(objectName); + const newRecord = { + ...body, + id, + createdAt: body.createdAt || new Date().toISOString() + }; + + store.set(id, newRecord); + + return HttpResponse.json(newRecord, { status: 201 }); + }), + + // Data: Update + http.patch(`${path}/data/:object/:id`, async ({ params, request }) => { + const objectName = params.object as string; + const id = params.id as string; + const updates = await request.json() as any; + const store = getStore(objectName); + const record = store.get(id); + + if (!record) { + return HttpResponse.json({ error: 'Record not found' }, { status: 404 }); + } + + const updatedRecord = { ...record, ...updates }; + store.set(id, updatedRecord); + + return HttpResponse.json(updatedRecord); + }), + + // Data: Delete + http.delete(`${path}/data/:object/:id`, ({ params }) => { + const objectName = params.object as string; + const id = params.id as string; + const store = getStore(objectName); + + if (!store.has(id)) { + return HttpResponse.json({ error: 'Record not found' }, { status: 404 }); + } + + store.delete(id); + + return HttpResponse.json({ success: true }, { status: 204 }); + }) + ); + } + + return handlers; +} diff --git a/examples/ui/msw-react-crud/vite.config.ts b/examples/ui/msw-react-crud/vite.config.ts index 030fe91a9e6..e7cace28c2a 100644 --- a/examples/ui/msw-react-crud/vite.config.ts +++ b/examples/ui/msw-react-crud/vite.config.ts @@ -7,4 +7,7 @@ export default defineConfig({ server: { port: 3000, }, + optimizeDeps: { + include: ['msw', 'msw/browser'] + } }); diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 9be40f98ab5..c80479e8838 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -276,9 +276,6 @@ importers: '@objectstack/client': specifier: workspace:* version: link:../../../packages/client - '@objectstack/plugin-msw': - specifier: workspace:* - version: link:../../../packages/plugin-msw '@objectstack/spec': specifier: workspace:* version: link:../../../packages/spec