-
Notifications
You must be signed in to change notification settings - Fork 1
Add MSW plugin for API mocking in testing and development #93
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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" | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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; | ||
|
|
||
| // 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'); | ||
| }); | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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'); | ||
| })(); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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/**/*"] | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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 |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
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
anytype 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.