-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathserver.ts
More file actions
223 lines (190 loc) · 7.92 KB
/
Copy pathserver.ts
File metadata and controls
223 lines (190 loc) · 7.92 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
/**
* MSW Server Setup for Tests
*
* This creates a complete ObjectStack environment for testing using MSW setupServer
* instead of setupWorker (which is for browser only).
*/
import { ObjectKernel, DriverPlugin, AppPlugin } from '@objectstack/runtime';
import { ObjectQLPlugin } from '@objectstack/objectql';
import { InMemoryDriver } from '@objectstack/driver-memory';
import { setupServer } from 'msw/node';
import { http, HttpResponse } from 'msw';
import appConfig from '../../objectstack.config';
let kernel: ObjectKernel | null = null;
let driver: InMemoryDriver | null = null;
let server: ReturnType<typeof setupServer> | null = null;
export async function startMockServer() {
if (kernel) {
console.log('[MSW] ObjectStack Runtime already initialized');
return kernel;
}
console.log('[MSW] Starting ObjectStack Runtime (Test Mode)...');
driver = new InMemoryDriver();
// Create kernel
kernel = new ObjectKernel();
kernel
.use(new ObjectQLPlugin())
.use(new DriverPlugin(driver, 'memory'))
.use(new AppPlugin(appConfig));
// Bootstrap kernel WITHOUT MSW plugin (we'll handle MSW separately for tests)
await kernel.bootstrap();
// Load initial data from manifest
const manifest = (appConfig as any).manifest;
if (manifest && Array.isArray(manifest.data)) {
console.log('[MSW] Loading initial data...');
for (const dataset of manifest.data) {
if (dataset.object && Array.isArray(dataset.records)) {
for (const record of dataset.records) {
await driver.create(dataset.object, record);
}
console.log(`[MSW] Loaded ${dataset.records.length} records for ${dataset.object}`);
}
}
}
// Create MSW handlers manually
const baseUrl = 'http://localhost:3000/api/v1';
const handlers = createHandlers(baseUrl, kernel, driver!);
// Setup MSW server for Node.js environment
server = setupServer(...handlers);
server.listen({ onUnhandledRequest: 'bypass' });
console.log('[MSW] ObjectStack Runtime ready');
return kernel;
}
export function stopMockServer() {
if (server) {
server.close();
server = null;
}
kernel = null;
driver = null;
}
export function getKernel(): ObjectKernel | null {
return kernel;
}
export function getDriver(): InMemoryDriver | null {
return driver;
}
/**
* Create MSW request handlers for ObjectStack API
*/
function createHandlers(baseUrl: string, kernel: ObjectKernel, driver: InMemoryDriver) {
const protocol = kernel.getService('protocol') as any;
return [
// Discovery endpoint - Handle both with and without trailing slash
http.get(`${baseUrl}`, async () => {
const response = await protocol.getDiscovery();
return HttpResponse.json(response, { status: 200 });
}),
http.get(`${baseUrl}/`, async () => {
const response = await protocol.getDiscovery();
return HttpResponse.json(response, { status: 200 });
}),
// Metadata endpoints - Support both legacy /meta and new /metadata paths
http.get(`${baseUrl}/meta/objects`, async () => {
const response = await protocol.getMetaItems({ type: 'object' });
return HttpResponse.json(response, { status: 200 });
}),
http.get(`${baseUrl}/metadata/objects`, async () => {
const response = await protocol.getMetaItems({ type: 'object' });
return HttpResponse.json(response, { status: 200 });
}),
http.get(`${baseUrl}/meta/objects/:objectName`, async ({ params }) => {
console.log('MSW: getting meta item for (legacy)', params.objectName);
try {
const response = await protocol.getMetaItem({
type: 'object',
name: params.objectName as string
});
return HttpResponse.json(response || { error: 'Not found' }, { status: response ? 200 : 404 });
} catch (e) {
return HttpResponse.json({ error: String(e) }, { status: 500 });
}
}),
http.get(`${baseUrl}/meta/object/:objectName`, async ({ params }) => {
console.log('MSW: getting meta item for /meta/object', params.objectName);
try {
const response = await protocol.getMetaItem({
type: 'object',
name: params.objectName as string
});
// Unwrap item if present
const payload = (response && response.item) ? response.item : response;
return HttpResponse.json(payload || { error: 'Not found' }, { status: payload ? 200 : 404 });
} catch (e) {
console.error('MSW: error getting meta item', e);
return HttpResponse.json({ error: String(e) }, { status: 500 });
}
}),
http.get(`${baseUrl}/metadata/object/:objectName`, async ({ params }) => {
console.log('MSW: getting meta item for', params.objectName);
try {
const response = await protocol.getMetaItem({
type: 'object',
name: params.objectName as string
});
// Unwrap item if present
const payload = (response && response.item) ? response.item : response;
return HttpResponse.json(payload || { error: 'Not found' }, { status: payload ? 200 : 404 });
} catch (e) {
console.error('MSW: error getting meta item', e);
return HttpResponse.json({ error: String(e) }, { status: 500 });
}
}),
// Data endpoints - Find all
http.get(`${baseUrl}/data/:objectName`, async ({ params, request }) => {
const url = new URL(request.url);
const query: any = {};
// Parse query parameters
url.searchParams.forEach((value, key) => {
try {
query[key] = JSON.parse(value);
} catch {
query[key] = value;
}
});
// Use driver directly
const response = await driver.find(params.objectName as string, query);
return HttpResponse.json({ value: response }, { status: 200 }); // Wrap in value for OData/Client?
}),
// Data endpoints - Find by ID
http.get(`${baseUrl}/data/:objectName/:id`, async ({ params }) => {
try {
console.log('MSW: getData', params.objectName, params.id);
// Use driver directly
// Try simple find first
const records = await driver.find(params.objectName as string, {
object: params.objectName as string,
where: [['_id', '=', params.id]]
});
// Manual filter to ensure we get the correct record if driver ignores filters
const record = records ? records.find((r: any) => r.id === params.id || r._id === params.id) : null;
console.log('MSW: getData result', JSON.stringify(record));
return HttpResponse.json(record, { status: record ? 200 : 404 });
} catch (e) {
console.error('MSW: getData error', e);
return HttpResponse.json({ error: String(e) }, { status: 500 });
}
}),
// Data endpoints - Create
http.post(`${baseUrl}/data/:objectName`, async ({ params, request }) => {
const body = await request.json();
console.log('MSW: createData', params.objectName, JSON.stringify(body));
const response = await driver.create(params.objectName as string, body as any);
console.log('MSW: createData result', JSON.stringify(response));
return HttpResponse.json(response, { status: 201 });
}),
// Data endpoints - Update
http.patch(`${baseUrl}/data/:objectName/:id`, async ({ params, request }) => {
const body = await request.json();
console.log('MSW: updateData', params.objectName, params.id, JSON.stringify(body));
const response = await driver.update(params.objectName as string, params.id as string, body as any);
console.log('MSW: updateData result', JSON.stringify(response));
return HttpResponse.json(response, { status: 200 });
}),
// Data endpoints - Delete
http.delete(`${baseUrl}/data/:objectName/:id`, async ({ params }) => {
const response = await driver.delete(params.objectName as string, params.id as string);
return HttpResponse.json(response, { status: 200 });
}),
];
}