Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
88 changes: 88 additions & 0 deletions examples/msw-demo/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
# MSW Demo Example

This example demonstrates how to use the `@objectstack/plugin-msw` package to mock ObjectStack APIs using Mock Service Worker (MSW).

## Features

- **Browser Mode**: Shows how to use MSW in a browser environment with standalone handlers
- **Server Mode**: Demonstrates MSW plugin integration with ObjectStack Runtime

## Files

- `src/browser.ts` - Browser-based MSW setup matching the problem statement
- `src/server.ts` - Server-side MSW plugin integration with Runtime

## Usage

### Browser Mode

```typescript
import { setupWorker } from 'msw/browser';
import { http, HttpResponse } from 'msw';
import { ObjectStackServer } from '@objectstack/plugin-msw';

// Initialize mock server
ObjectStackServer.init(protocol);

// Define handlers
const handlers = [
http.get('/api/user/:id', async ({ params }) => {
const result = await ObjectStackServer.getUser(params.id);
return HttpResponse.json(result.data, { status: result.status });
})
];

// Start worker
const worker = setupWorker(...handlers);
await worker.start();
```

### Runtime Integration

```typescript
import { ObjectStackKernel } from '@objectstack/runtime';
import { MSWPlugin } from '@objectstack/plugin-msw';

const kernel = new ObjectStackKernel([
// Your manifests...
new MSWPlugin({
baseUrl: '/api/v1',
logRequests: true
})
]);

await kernel.start();
```

## Running

```bash
# Install dependencies
pnpm install

# Build
pnpm build

# Run server example
pnpm dev
```

## API Endpoints Mocked

The MSW plugin automatically mocks the following endpoints:

- `GET /api/v1` - Discovery
- `GET /api/v1/meta` - Metadata types
- `GET /api/v1/meta/:type` - Metadata items
- `GET /api/v1/meta/:type/:name` - Specific metadata
- `GET /api/v1/data/:object` - Find records
- `GET /api/v1/data/:object/:id` - Get record
- `POST /api/v1/data/:object` - Create record
- `PATCH /api/v1/data/:object/:id` - Update record
- `DELETE /api/v1/data/:object/:id` - Delete record
- `GET /api/v1/ui/view/:object` - UI view config

## See Also

- [@objectstack/plugin-msw](../../packages/plugin-msw) - MSW Plugin package
- [MSW Documentation](https://mswjs.io/) - Official MSW docs
24 changes: 24 additions & 0 deletions examples/msw-demo/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
{
"name": "@objectstack/example-msw-demo",
"version": "0.1.0",
"private": true,
"description": "Example demonstrating MSW plugin usage with ObjectStack",
"scripts": {
"build": "tsc",
"dev": "ts-node src/server.ts",
"clean": "rm -rf dist node_modules"
},
"dependencies": {
"@objectstack/driver-memory": "workspace:*",
"@objectstack/example-crm": "workspace:*",
"@objectstack/objectql": "workspace:*",
"@objectstack/plugin-msw": "workspace:*",
"@objectstack/runtime": "workspace:*",
"msw": "^2.0.0"
},
"devDependencies": {
"@types/node": "^20.0.0",
"ts-node": "^10.9.1",
"typescript": "^5.0.0"
}
}
62 changes: 62 additions & 0 deletions examples/msw-demo/src/browser.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
/**
* MSW Browser Example - Standalone Usage
*
* This example shows how to use MSW with ObjectStack in a browser environment.
* It matches the example from the problem statement.
*/

import { setupWorker } from 'msw/browser';
import { http, HttpResponse } from 'msw';
import { ObjectStackServer } from '@objectstack/plugin-msw';

// Mock protocol - in real usage, this would come from runtime
// For this example, we'll simulate it
const mockProtocol = {
getData: async (object: string, id: string) => {
return { id, object, name: `Mock ${object}`, status: 'active' };
},
createData: async (object: string, data: any) => {
return { id: 'new-id', ...data };
},
// Add other methods as needed
} as any;
Comment on lines +14 to +22
Copy link

Copilot AI Jan 24, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The mock protocol object uses TypeScript any type casting without proper error handling or type checking. This could lead to runtime errors if the protocol methods are not properly implemented. Consider creating a proper mock that implements the expected protocol interface or using a testing library to create type-safe mocks.

Suggested change
const mockProtocol = {
getData: async (object: string, id: string) => {
return { id, object, name: `Mock ${object}`, status: 'active' };
},
createData: async (object: string, data: any) => {
return { id: 'new-id', ...data };
},
// Add other methods as needed
} as any;
interface MockProtocol {
getData(object: string, id: string): Promise<unknown>;
createData(object: string, data: unknown): Promise<unknown>;
}
const mockProtocol: MockProtocol = {
getData: async (object: string, id: string) => {
return { id, object, name: `Mock ${object}`, status: 'active' };
},
createData: async (object: string, data: unknown) => {
return { id: 'new-id', ...data as Record<string, unknown> };
},
// Add other methods as needed
};

Copilot uses AI. Check for mistakes.

// 1. Initialize the mock server (equivalent to ObjectStackServer.init())
ObjectStackServer.init(mockProtocol);

// 2. Define request handlers (similar to Express/Koa routes, but in Service Worker)
const handlers = [

// Intercept GET /api/user/:id
http.get('/api/user/:id', async ({ params }) => {
const { id } = params;

// Call local logic
const result = await ObjectStackServer.getUser(id as string);

// Return constructed Response
return HttpResponse.json(result.data, { status: result.status });
}),

// Intercept POST /api/user
http.post('/api/user', async ({ request }) => {
const body = await request.json();

// Call local logic
const result = await ObjectStackServer.createUser(body);

return HttpResponse.json(result.data, { status: result.status });
}),
];

// 3. Create Worker instance
export const worker = setupWorker(...handlers);

// Start the worker (typically called in your app entry point)
if (typeof window !== 'undefined') {
worker.start({
onUnhandledRequest: 'bypass',
}).then(() => {
console.log('[MSW] Mock Service Worker started');
});
}
36 changes: 36 additions & 0 deletions examples/msw-demo/src/server.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
/**
* MSW Server Example - Runtime Integration
*
* This example shows how to use the MSW plugin with ObjectStack Runtime.
* This is useful for Node.js testing environments or development.
*/

import { ObjectStackKernel } from '@objectstack/runtime';
import { InMemoryDriver } from '@objectstack/driver-memory';
import { MSWPlugin } from '@objectstack/plugin-msw';

import CrmApp from '@objectstack/example-crm/objectstack.config';

(async () => {
console.log('🚀 Starting ObjectStack with MSW Plugin...');

const kernel = new ObjectStackKernel([
CrmApp,
new InMemoryDriver(),

// Add MSW Plugin for API mocking
new MSWPlugin({
enableBrowser: false, // Disable browser mode for Node.js
baseUrl: '/api/v1',
logRequests: true,
customHandlers: [
// You can add custom handlers here
]
})
]);

await kernel.start();

console.log('✅ MSW Plugin initialized');
console.log('📝 All API endpoints are now mocked and ready for testing');
})();
13 changes: 13 additions & 0 deletions examples/msw-demo/tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
{
"compilerOptions": {
"target": "ES2022",
"module": "NodeNext",
"moduleResolution": "NodeNext",
"strict": true,
"esModuleInterop": true,
"declaration": true,
"outDir": "./dist",
"skipLibCheck": true
},
"include": ["src/**/*"]
}
24 changes: 24 additions & 0 deletions packages/plugin-msw/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
# @objectstack/plugin-msw

## 0.3.1

### Added

- Initial release of MSW plugin for ObjectStack
- `MSWPlugin` class implementing RuntimePlugin interface
- `ObjectStackServer` mock server for handling API calls
- Automatic generation of MSW handlers for ObjectStack API endpoints
- Support for browser and Node.js environments
- Custom handler support
- Comprehensive documentation and examples
- TypeScript type definitions

### Features

- Discovery endpoint mocking
- Metadata endpoint mocking
- Data CRUD operation mocking
- UI protocol endpoint mocking
- Request logging support
- Configurable base URL
- Integration with ObjectStack Runtime Protocol
Loading
Loading