Skip to content

Commit 9aee62e

Browse files
committed
feat: integrate MSW worker setup with dynamic service worker path handling
1 parent 8a1fe40 commit 9aee62e

1 file changed

Lines changed: 26 additions & 2 deletions

File tree

apps/console/src/mocks/browser.ts

Lines changed: 26 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ import { ObjectKernel, DriverPlugin, AppPlugin } from '@objectstack/runtime';
99
import { ObjectQLPlugin } from '@objectstack/objectql';
1010
import { InMemoryDriver } from '@objectstack/driver-memory';
1111
import { MSWPlugin } from '@objectstack/plugin-msw';
12+
import { setupWorker } from 'msw/browser';
1213
import appConfig from '../../objectstack.shared';
1314

1415
let kernel: ObjectKernel | null = null;
@@ -49,8 +50,9 @@ export async function startMockServer() {
4950
await kernel.use(new AppPlugin(appConfig))
5051

5152
// MSW Plugin (intercepts network requests)
53+
// Disable auto-start to manually control worker registration with correct path
5254
const mswPlugin = new MSWPlugin({
53-
enableBrowser: true,
55+
enableBrowser: false,
5456
baseUrl: '/api/v1',
5557
logRequests: true
5658
});
@@ -61,13 +63,35 @@ export async function startMockServer() {
6163
const fixedMswPlugin = {
6264
...mswPlugin,
6365
init: mswPlugin.init.bind(mswPlugin),
64-
start: mswPlugin.start ? mswPlugin.start.bind(mswPlugin) : undefined
66+
start: mswPlugin.start ? mswPlugin.start.bind(mswPlugin) : undefined,
67+
getHandlers: mswPlugin.getHandlers.bind(mswPlugin) // Bind getHandlers too
6568
};
6669

6770
await kernel.use(fixedMswPlugin);
6871

6972
await kernel.bootstrap();
7073

74+
// Manually start MSW worker with correct service worker path
75+
if (typeof window !== 'undefined') {
76+
const handlers = mswPlugin.getHandlers();
77+
const worker = setupWorker(...handlers);
78+
79+
// Check if we are served under a base path (e.g. /console/)
80+
const isConsolePath = window.location.pathname.startsWith('/console/');
81+
// If the app is at /console/, the mockServiceWorker.js is likely served at /console/mockServiceWorker.js
82+
// unless vite base is handled strangely. But typically public assets follow base.
83+
const swUrl = isConsolePath ? '/console/mockServiceWorker.js' : '/mockServiceWorker.js';
84+
85+
console.log(`[MSW] Starting worker with script at: ${swUrl}`);
86+
87+
await worker.start({
88+
onUnhandledRequest: 'bypass',
89+
serviceWorker: {
90+
url: swUrl
91+
}
92+
});
93+
}
94+
7195
// Initialize default data from manifest if available
7296
const manifest = (appConfig as any).manifest;
7397
if (manifest && Array.isArray(manifest.data)) {

0 commit comments

Comments
 (0)