|
| 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 | +} |
0 commit comments