Skip to content

Commit 5d6009d

Browse files
authored
Merge pull request #93 from objectstack-ai/copilot/add-msn-plugin-support
2 parents 87292f9 + 08dfa96 commit 5d6009d

File tree

12 files changed

+1248
-7
lines changed

12 files changed

+1248
-7
lines changed

examples/msw-demo/README.md

Lines changed: 88 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,88 @@
1+
# MSW Demo Example
2+
3+
This example demonstrates how to use the `@objectstack/plugin-msw` package to mock ObjectStack APIs using Mock Service Worker (MSW).
4+
5+
## Features
6+
7+
- **Browser Mode**: Shows how to use MSW in a browser environment with standalone handlers
8+
- **Server Mode**: Demonstrates MSW plugin integration with ObjectStack Runtime
9+
10+
## Files
11+
12+
- `src/browser.ts` - Browser-based MSW setup matching the problem statement
13+
- `src/server.ts` - Server-side MSW plugin integration with Runtime
14+
15+
## Usage
16+
17+
### Browser Mode
18+
19+
```typescript
20+
import { setupWorker } from 'msw/browser';
21+
import { http, HttpResponse } from 'msw';
22+
import { ObjectStackServer } from '@objectstack/plugin-msw';
23+
24+
// Initialize mock server
25+
ObjectStackServer.init(protocol);
26+
27+
// Define handlers
28+
const handlers = [
29+
http.get('/api/user/:id', async ({ params }) => {
30+
const result = await ObjectStackServer.getUser(params.id);
31+
return HttpResponse.json(result.data, { status: result.status });
32+
})
33+
];
34+
35+
// Start worker
36+
const worker = setupWorker(...handlers);
37+
await worker.start();
38+
```
39+
40+
### Runtime Integration
41+
42+
```typescript
43+
import { ObjectStackKernel } from '@objectstack/runtime';
44+
import { MSWPlugin } from '@objectstack/plugin-msw';
45+
46+
const kernel = new ObjectStackKernel([
47+
// Your manifests...
48+
new MSWPlugin({
49+
baseUrl: '/api/v1',
50+
logRequests: true
51+
})
52+
]);
53+
54+
await kernel.start();
55+
```
56+
57+
## Running
58+
59+
```bash
60+
# Install dependencies
61+
pnpm install
62+
63+
# Build
64+
pnpm build
65+
66+
# Run server example
67+
pnpm dev
68+
```
69+
70+
## API Endpoints Mocked
71+
72+
The MSW plugin automatically mocks the following endpoints:
73+
74+
- `GET /api/v1` - Discovery
75+
- `GET /api/v1/meta` - Metadata types
76+
- `GET /api/v1/meta/:type` - Metadata items
77+
- `GET /api/v1/meta/:type/:name` - Specific metadata
78+
- `GET /api/v1/data/:object` - Find records
79+
- `GET /api/v1/data/:object/:id` - Get record
80+
- `POST /api/v1/data/:object` - Create record
81+
- `PATCH /api/v1/data/:object/:id` - Update record
82+
- `DELETE /api/v1/data/:object/:id` - Delete record
83+
- `GET /api/v1/ui/view/:object` - UI view config
84+
85+
## See Also
86+
87+
- [@objectstack/plugin-msw](../../packages/plugin-msw) - MSW Plugin package
88+
- [MSW Documentation](https://mswjs.io/) - Official MSW docs

examples/msw-demo/package.json

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
{
2+
"name": "@objectstack/example-msw-demo",
3+
"version": "0.1.0",
4+
"private": true,
5+
"description": "Example demonstrating MSW plugin usage with ObjectStack",
6+
"scripts": {
7+
"build": "tsc",
8+
"dev": "ts-node src/server.ts",
9+
"clean": "rm -rf dist node_modules"
10+
},
11+
"dependencies": {
12+
"@objectstack/driver-memory": "workspace:*",
13+
"@objectstack/example-crm": "workspace:*",
14+
"@objectstack/objectql": "workspace:*",
15+
"@objectstack/plugin-msw": "workspace:*",
16+
"@objectstack/runtime": "workspace:*",
17+
"msw": "^2.0.0"
18+
},
19+
"devDependencies": {
20+
"@types/node": "^20.0.0",
21+
"ts-node": "^10.9.1",
22+
"typescript": "^5.0.0"
23+
}
24+
}

examples/msw-demo/src/browser.ts

Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
/**
2+
* MSW Browser Example - Standalone Usage
3+
*
4+
* This example shows how to use MSW with ObjectStack in a browser environment.
5+
* It matches the example from the problem statement.
6+
*/
7+
8+
import { setupWorker } from 'msw/browser';
9+
import { http, HttpResponse } from 'msw';
10+
import { ObjectStackServer } from '@objectstack/plugin-msw';
11+
12+
// Mock protocol - in real usage, this would come from runtime
13+
// For this example, we'll simulate it
14+
const mockProtocol = {
15+
getData: async (object: string, id: string) => {
16+
return { id, object, name: `Mock ${object}`, status: 'active' };
17+
},
18+
createData: async (object: string, data: any) => {
19+
return { id: 'new-id', ...data };
20+
},
21+
// Add other methods as needed
22+
} as any;
23+
24+
// 1. Initialize the mock server (equivalent to ObjectStackServer.init())
25+
ObjectStackServer.init(mockProtocol);
26+
27+
// 2. Define request handlers (similar to Express/Koa routes, but in Service Worker)
28+
const handlers = [
29+
30+
// Intercept GET /api/user/:id
31+
http.get('/api/user/:id', async ({ params }) => {
32+
const { id } = params;
33+
34+
// Call local logic
35+
const result = await ObjectStackServer.getUser(id as string);
36+
37+
// Return constructed Response
38+
return HttpResponse.json(result.data, { status: result.status });
39+
}),
40+
41+
// Intercept POST /api/user
42+
http.post('/api/user', async ({ request }) => {
43+
const body = await request.json();
44+
45+
// Call local logic
46+
const result = await ObjectStackServer.createUser(body);
47+
48+
return HttpResponse.json(result.data, { status: result.status });
49+
}),
50+
];
51+
52+
// 3. Create Worker instance
53+
export const worker = setupWorker(...handlers);
54+
55+
// Start the worker (typically called in your app entry point)
56+
if (typeof window !== 'undefined') {
57+
worker.start({
58+
onUnhandledRequest: 'bypass',
59+
}).then(() => {
60+
console.log('[MSW] Mock Service Worker started');
61+
});
62+
}

examples/msw-demo/src/server.ts

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
/**
2+
* MSW Server Example - Runtime Integration
3+
*
4+
* This example shows how to use the MSW plugin with ObjectStack Runtime.
5+
* This is useful for Node.js testing environments or development.
6+
*/
7+
8+
import { ObjectStackKernel } from '@objectstack/runtime';
9+
import { InMemoryDriver } from '@objectstack/driver-memory';
10+
import { MSWPlugin } from '@objectstack/plugin-msw';
11+
12+
import CrmApp from '@objectstack/example-crm/objectstack.config';
13+
14+
(async () => {
15+
console.log('🚀 Starting ObjectStack with MSW Plugin...');
16+
17+
const kernel = new ObjectStackKernel([
18+
CrmApp,
19+
new InMemoryDriver(),
20+
21+
// Add MSW Plugin for API mocking
22+
new MSWPlugin({
23+
enableBrowser: false, // Disable browser mode for Node.js
24+
baseUrl: '/api/v1',
25+
logRequests: true,
26+
customHandlers: [
27+
// You can add custom handlers here
28+
]
29+
})
30+
]);
31+
32+
await kernel.start();
33+
34+
console.log('✅ MSW Plugin initialized');
35+
console.log('📝 All API endpoints are now mocked and ready for testing');
36+
})();

examples/msw-demo/tsconfig.json

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
{
2+
"compilerOptions": {
3+
"target": "ES2022",
4+
"module": "NodeNext",
5+
"moduleResolution": "NodeNext",
6+
"strict": true,
7+
"esModuleInterop": true,
8+
"declaration": true,
9+
"outDir": "./dist",
10+
"skipLibCheck": true
11+
},
12+
"include": ["src/**/*"]
13+
}

packages/plugin-msw/CHANGELOG.md

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
# @objectstack/plugin-msw
2+
3+
## 0.3.1
4+
5+
### Added
6+
7+
- Initial release of MSW plugin for ObjectStack
8+
- `MSWPlugin` class implementing RuntimePlugin interface
9+
- `ObjectStackServer` mock server for handling API calls
10+
- Automatic generation of MSW handlers for ObjectStack API endpoints
11+
- Support for browser and Node.js environments
12+
- Custom handler support
13+
- Comprehensive documentation and examples
14+
- TypeScript type definitions
15+
16+
### Features
17+
18+
- Discovery endpoint mocking
19+
- Metadata endpoint mocking
20+
- Data CRUD operation mocking
21+
- UI protocol endpoint mocking
22+
- Request logging support
23+
- Configurable base URL
24+
- Integration with ObjectStack Runtime Protocol

0 commit comments

Comments
 (0)