Skip to content

Commit db9541f

Browse files
authored
Merge pull request #166 from objectstack-ai/copilot/add-msw-integration-example-again
2 parents 7ddf1ab + 06460cc commit db9541f

File tree

7 files changed

+432
-176
lines changed

7 files changed

+432
-176
lines changed
Lines changed: 120 additions & 43 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
1-
# Quick Start Guide
1+
# Quick Start Guide - Simplified MSW Integration
22

3-
This guide will help you get the MSW + React CRUD example up and running in 5 minutes.
3+
This is the **simplified** version using `@objectstack/plugin-msw` that auto-mocks all API endpoints. No manual handler code required!
44

55
## Prerequisites
66

@@ -15,23 +15,21 @@ From the repository root:
1515
pnpm install
1616
```
1717

18-
This will install all dependencies for the monorepo, including this example.
19-
2018
## Step 2: Build Required Packages
2119

22-
Build the core packages that the example depends on:
20+
Build the core packages:
2321

2422
```bash
25-
# Build the spec package (contains type definitions)
23+
# Build all required packages
2624
pnpm --filter @objectstack/spec build
27-
28-
# Build the client package
25+
pnpm --filter @objectstack/runtime build
26+
pnpm --filter @objectstack/plugin-msw build
2927
pnpm --filter @objectstack/client build
3028
```
3129

3230
## Step 3: Initialize MSW
3331

34-
The MSW service worker file should already be initialized, but if you need to regenerate it:
32+
The MSW service worker file should already be initialized:
3533

3634
```bash
3735
cd examples/ui/msw-react-crud
@@ -47,48 +45,127 @@ pnpm dev
4745

4846
The application will start on `http://localhost:3000`
4947

50-
## Step 5: Test CRUD Operations
51-
52-
Once the app is running, you can:
53-
54-
1. **Create** a new task using the form
55-
2. **Read** tasks in the task list
56-
3. **Update** a task by clicking "Edit"
57-
4. **Delete** a task by clicking "Delete"
58-
5. **Toggle completion** status by checking/unchecking the checkbox
48+
## ✨ What's Different?
49+
50+
### Before (Manual Approach) ❌
51+
52+
You had to manually write 145+ lines of MSW handlers:
53+
54+
```typescript
55+
// src/mocks/browser.ts - OLD WAY
56+
const handlers = [
57+
http.get('/api/v1/data/task', ({ request }) => {
58+
// Manual pagination, filtering, sorting...
59+
}),
60+
http.post('/api/v1/data/task', async ({ request }) => {
61+
// Manual ID generation, validation...
62+
}),
63+
// ... more manual handlers
64+
];
65+
const worker = setupWorker(...handlers);
66+
await worker.start();
67+
```
5968

60-
## What's Happening Under the Hood?
69+
### After (Plugin Approach) ✅
6170

62-
When you interact with the application:
71+
Now just **3 lines** with auto-mocking:
6372

64-
1. React components call `@objectstack/client` methods (e.g., `client.data.create()`)
65-
2. The client makes HTTP requests to `/api/v1/data/task`
66-
3. MSW intercepts these requests in the browser
67-
4. Mock handlers return data from an in-memory database
68-
5. The UI updates with the response
73+
```typescript
74+
// src/mocks/browser.ts - NEW WAY
75+
const mswPlugin = new MSWPlugin({ baseUrl: '/api/v1' });
76+
const runtime = new ObjectStackKernel([appConfig, mswPlugin]);
77+
await runtime.start(); // Auto-mocks ALL endpoints!
78+
```
6979

70-
All network requests visible in DevTools are real HTTP requests - they're just being intercepted and handled by MSW!
80+
## 📦 How It Works
81+
82+
1. **Define Your Data Model** in `objectstack.config.ts`:
83+
```typescript
84+
const TaskObject = ObjectSchema.create({
85+
name: 'task',
86+
fields: {
87+
subject: Field.text({ required: true }),
88+
priority: Field.number()
89+
}
90+
});
91+
```
92+
93+
2. **Auto-Mock Everything**: The MSW plugin automatically mocks:
94+
- ✅ Discovery endpoints
95+
- ✅ Metadata endpoints
96+
- ✅ All CRUD operations
97+
- ✅ Query operations
98+
- ✅ Pagination, sorting, filtering
99+
100+
3. **Use ObjectStack Client** normally:
101+
```typescript
102+
const client = new ObjectStackClient({ baseUrl: '/api/v1' });
103+
await client.data.create('task', { subject: 'New task' });
104+
```
105+
106+
## 🎯 Test CRUD Operations
107+
108+
Once running, you can:
109+
110+
1. **Create** tasks using the form
111+
2. **Read** tasks in the list
112+
3. **Update** tasks by clicking "Edit"
113+
4. **Delete** tasks by clicking "Delete"
114+
5. **Toggle completion** status
115+
116+
## 🔍 What Gets Auto-Mocked?
117+
118+
The plugin automatically handles:
119+
120+
| Endpoint | Description |
121+
|----------|-------------|
122+
| `GET /api/v1` | Discovery |
123+
| `GET /api/v1/meta/*` | All metadata |
124+
| `GET /api/v1/data/:object` | Find records |
125+
| `GET /api/v1/data/:object/:id` | Get by ID |
126+
| `POST /api/v1/data/:object` | Create |
127+
| `PATCH /api/v1/data/:object/:id` | Update |
128+
| `DELETE /api/v1/data/:object/:id` | Delete |
129+
130+
**Zero manual code!** 🎉
131+
132+
## 🔧 Advanced: Custom Handlers
133+
134+
Need custom logic? Easy:
135+
136+
```typescript
137+
const customHandlers = [
138+
http.get('/api/custom/hello', () =>
139+
HttpResponse.json({ message: 'Hello!' })
140+
)
141+
];
142+
143+
const mswPlugin = new MSWPlugin({
144+
customHandlers, // Add your custom handlers
145+
baseUrl: '/api/v1'
146+
});
147+
```
71148

72149
## Troubleshooting
73150

74-
**Problem**: MSW worker not starting
75-
**Solution**: Run `npx msw init public/ --save` again
76-
77-
**Problem**: TypeScript errors during build
78-
**Solution**: Make sure you've built the dependency packages first
79-
80-
**Problem**: 404 errors in browser
81-
**Solution**: Check that the MSW worker is registered (look for console message)
151+
**MSW worker not starting?**
152+
```bash
153+
npx msw init public/ --save
154+
```
82155

83-
## Next Steps
156+
**TypeScript errors?**
157+
```bash
158+
pnpm --filter @objectstack/spec build
159+
pnpm --filter @objectstack/runtime build
160+
pnpm --filter @objectstack/plugin-msw build
161+
```
84162

85-
- Modify `src/mocks/browser.ts` to add more fields or objects
86-
- Customize the UI in `src/App.css`
87-
- Add more complex query operations
88-
- Experiment with filters and sorting
163+
**404 errors?**
164+
Check browser console for MSW startup message
89165

90-
## Learn More
166+
## 📚 Learn More
91167

92-
- Read the full [README.md](./README.md) for detailed documentation
93-
- Check out [MSW Documentation](https://mswjs.io/)
94-
- Explore the [@objectstack/client API](../../packages/client)
168+
- Full documentation: [README.md](./README.md)
169+
- MSW Plugin: `packages/plugin-msw/README.md`
170+
- Runtime: `packages/runtime/README.md`
171+
- Client API: `packages/client/README.md`
Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
/**
2+
* Task Object Definition
3+
*/
4+
export const TaskObject = {
5+
name: 'task',
6+
label: 'Task',
7+
description: 'Task management object',
8+
icon: 'check-square',
9+
titleFormat: '{subject}',
10+
enable: {
11+
apiEnabled: true,
12+
trackHistory: false,
13+
feeds: false,
14+
activities: false,
15+
mru: true,
16+
},
17+
fields: {
18+
id: { name: 'id', label: 'ID', type: 'text', required: true },
19+
subject: { name: 'subject', label: 'Subject', type: 'text', required: true },
20+
priority: { name: 'priority', label: 'Priority', type: 'number', defaultValue: 5 },
21+
isCompleted: { name: 'isCompleted', label: 'Completed', type: 'boolean', defaultValue: false },
22+
createdAt: { name: 'createdAt', label: 'Created At', type: 'datetime' }
23+
}
24+
};
25+
26+
/**
27+
* App Configuration
28+
*/
29+
export default {
30+
name: 'task_app',
31+
label: 'Task Management',
32+
description: 'MSW + React CRUD Example with ObjectStack',
33+
version: '1.0.0',
34+
icon: 'check-square',
35+
branding: {
36+
primaryColor: '#3b82f6',
37+
logo: '/assets/logo.png',
38+
},
39+
objects: [
40+
TaskObject
41+
],
42+
navigation: [
43+
{
44+
id: 'group_tasks',
45+
type: 'group',
46+
label: 'Tasks',
47+
children: [
48+
{
49+
id: 'nav_tasks',
50+
type: 'object',
51+
objectName: 'task',
52+
label: 'My Tasks'
53+
}
54+
]
55+
}
56+
]
57+
};

examples/ui/msw-react-crud/package.json

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,6 @@
1111
},
1212
"dependencies": {
1313
"@objectstack/client": "workspace:*",
14-
"@objectstack/plugin-msw": "workspace:*",
1514
"@objectstack/spec": "workspace:*",
1615
"react": "^18.3.1",
1716
"react-dom": "^18.3.1"

0 commit comments

Comments
 (0)