@objectstack/objectql 0.6.1 → 0.7.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/protocol.ts CHANGED
@@ -1,57 +1,94 @@
1
- import { IObjectStackProtocol } from '@objectstack/spec/api';
1
+ import { ObjectStackProtocol } from '@objectstack/spec/api';
2
2
  import { IDataEngine } from '@objectstack/core';
3
+ import type {
4
+ BatchUpdateRequest,
5
+ BatchUpdateResponse,
6
+ UpdateManyDataRequest,
7
+ DeleteManyDataRequest
8
+ } from '@objectstack/spec/api';
9
+ import type { MetadataCacheRequest, MetadataCacheResponse } from '@objectstack/spec/api';
10
+ import type {
11
+ CreateViewRequest,
12
+ UpdateViewRequest,
13
+ ListViewsRequest,
14
+ ViewResponse,
15
+ ListViewsResponse,
16
+ SavedView
17
+ } from '@objectstack/spec/api';
3
18
 
4
19
  // We import SchemaRegistry directly since this class lives in the same package
5
20
  import { SchemaRegistry } from './registry';
6
21
 
7
- export class ObjectStackProtocolImplementation implements IObjectStackProtocol {
22
+ /**
23
+ * Simple hash function for ETag generation (browser-compatible)
24
+ * Uses a basic hash algorithm instead of crypto.createHash
25
+ */
26
+ function simpleHash(str: string): string {
27
+ let hash = 0;
28
+ for (let i = 0; i < str.length; i++) {
29
+ const char = str.charCodeAt(i);
30
+ hash = ((hash << 5) - hash) + char;
31
+ hash = hash & hash; // Convert to 32bit integer
32
+ }
33
+ return Math.abs(hash).toString(16);
34
+ }
35
+
36
+ export class ObjectStackProtocolImplementation implements ObjectStackProtocol {
8
37
  private engine: IDataEngine;
38
+ private viewStorage: Map<string, SavedView> = new Map();
9
39
 
10
40
  constructor(engine: IDataEngine) {
11
41
  this.engine = engine;
12
42
  }
13
43
 
14
- getDiscovery() {
44
+ async getDiscovery(_request: {}) {
15
45
  return {
16
- name: 'ObjectStack API',
17
46
  version: '1.0',
18
- capabilities: {
19
- metadata: true,
20
- data: true,
21
- ui: true
22
- }
47
+ apiName: 'ObjectStack API',
48
+ capabilities: ['metadata', 'data', 'ui'],
49
+ endpoints: {}
23
50
  };
24
51
  }
25
52
 
26
- getMetaTypes() {
27
- return SchemaRegistry.getRegisteredTypes();
53
+ async getMetaTypes(_request: {}) {
54
+ return {
55
+ types: SchemaRegistry.getRegisteredTypes()
56
+ };
28
57
  }
29
58
 
30
- getMetaItems(type: string) {
31
- return SchemaRegistry.listItems(type);
59
+ async getMetaItems(request: { type: string }) {
60
+ return {
61
+ type: request.type,
62
+ items: SchemaRegistry.listItems(request.type)
63
+ };
32
64
  }
33
65
 
34
- getMetaItem(type: string, name: string) {
35
- return SchemaRegistry.getItem(type, name);
66
+ async getMetaItem(request: { type: string, name: string }) {
67
+ return {
68
+ type: request.type,
69
+ name: request.name,
70
+ item: SchemaRegistry.getItem(request.type, request.name)
71
+ };
36
72
  }
37
73
 
38
- getUiView(object: string, type: 'list' | 'form') {
39
- const schema = SchemaRegistry.getObject(object);
40
- if (!schema) throw new Error(`Object ${object} not found`);
74
+ async getUiView(request: { object: string, type: 'list' | 'form' }) {
75
+ const schema = SchemaRegistry.getObject(request.object);
76
+ if (!schema) throw new Error(`Object ${request.object} not found`);
41
77
 
42
- if (type === 'list') {
43
- return {
78
+ let view: any;
79
+ if (request.type === 'list') {
80
+ view = {
44
81
  type: 'list',
45
- object: object,
82
+ object: request.object,
46
83
  columns: Object.keys(schema.fields || {}).slice(0, 5).map(f => ({
47
84
  field: f,
48
85
  label: schema.fields[f].label || f
49
86
  }))
50
87
  };
51
88
  } else {
52
- return {
89
+ view = {
53
90
  type: 'form',
54
- object: object,
91
+ object: request.object,
55
92
  sections: [
56
93
  {
57
94
  label: 'General',
@@ -62,43 +99,212 @@ export class ObjectStackProtocolImplementation implements IObjectStackProtocol {
62
99
  ]
63
100
  };
64
101
  }
102
+ return {
103
+ object: request.object,
104
+ type: request.type,
105
+ view
106
+ };
65
107
  }
66
108
 
67
- findData(object: string, query: any) {
68
- return this.engine.find(object, query);
69
- }
70
-
71
- async getData(object: string, id: string) {
72
- // IDataEngine doesn't have findOne, so we simulate it with find and limit 1
73
- // Assuming the ID field is named '_id' or 'id'.
74
- // For broad compatibility, we might need to know the ID field name.
75
- // But traditionally it is _id in ObjectStack/mongo or id in others.
76
- // Let's rely on finding by ID if the engine supports it via find?
77
- // Actually, ObjectQL (the implementation) DOES have findOne.
78
- // But we are programming against IDataEngine interface here.
109
+ async findData(request: { object: string, query?: any }) {
110
+ // TODO: Normalize query from HTTP Query params (string values) to DataEngineQueryOptions (typed)
111
+ // For now, we assume query is partially compatible or simple enough.
112
+ // We should parse 'top', 'skip', 'limit' to numbers if they are strings.
113
+ const options: any = { ...request.query };
114
+ if (options.top) options.top = Number(options.top);
115
+ if (options.skip) options.skip = Number(options.skip);
116
+ if (options.limit) options.limit = Number(options.limit);
79
117
 
80
- // If the engine IS ObjectQL (which it practically is), we could cast it.
81
- // But let's try to stick to interface.
118
+ // Handle OData style $filter if present, or flat filters
119
+ // This is a naive implementation, a real OData parser is needed for complex scenarios.
82
120
 
83
- const results = await this.engine.find(object, {
84
- filter: { _id: id }, // Default Assumption: _id
85
- limit: 1
121
+ const records = await this.engine.find(request.object, options);
122
+ return {
123
+ object: request.object,
124
+ value: records, // OData compaibility
125
+ records, // Legacy
126
+ total: records.length,
127
+ hasMore: false
128
+ };
129
+ }
130
+
131
+ async getData(request: { object: string, id: string }) {
132
+ const result = await this.engine.findOne(request.object, {
133
+ filter: { _id: request.id }
86
134
  });
87
- if (results && results.length > 0) {
88
- return results[0];
135
+ if (result) {
136
+ return {
137
+ object: request.object,
138
+ id: request.id,
139
+ record: result
140
+ };
89
141
  }
90
- throw new Error(`Record ${id} not found in ${object}`);
142
+ throw new Error(`Record ${request.id} not found in ${request.object}`);
143
+ }
144
+
145
+ async createData(request: { object: string, data: any }) {
146
+ const result = await this.engine.insert(request.object, request.data);
147
+ return {
148
+ object: request.object,
149
+ id: result._id || result.id,
150
+ record: result
151
+ };
152
+ }
153
+
154
+ async updateData(request: { object: string, id: string, data: any }) {
155
+ // Adapt: update(obj, id, data) -> update(obj, data, options)
156
+ const result = await this.engine.update(request.object, request.data, { filter: { _id: request.id } });
157
+ return {
158
+ object: request.object,
159
+ id: request.id,
160
+ record: result
161
+ };
91
162
  }
92
163
 
93
- createData(object: string, data: any) {
94
- return this.engine.insert(object, data);
164
+ async deleteData(request: { object: string, id: string }) {
165
+ // Adapt: delete(obj, id) -> delete(obj, options)
166
+ await this.engine.delete(request.object, { filter: { _id: request.id } });
167
+ return {
168
+ object: request.object,
169
+ id: request.id,
170
+ success: true
171
+ };
95
172
  }
96
173
 
97
- updateData(object: string, id: string, data: any) {
98
- return this.engine.update(object, id, data);
174
+ // ==========================================
175
+ // Metadata Caching
176
+ // ==========================================
177
+
178
+ async getMetaItemCached(request: { type: string, name: string, cacheRequest?: MetadataCacheRequest }): Promise<MetadataCacheResponse> {
179
+ try {
180
+ const item = SchemaRegistry.getItem(request.type, request.name);
181
+ if (!item) {
182
+ throw new Error(`Metadata item ${request.type}/${request.name} not found`);
183
+ }
184
+
185
+ // Calculate ETag (simple hash of the stringified metadata)
186
+ const content = JSON.stringify(item);
187
+ const hash = simpleHash(content);
188
+ const etag = { value: hash, weak: false };
189
+
190
+ // Check If-None-Match header
191
+ if (request.cacheRequest?.ifNoneMatch) {
192
+ const clientEtag = request.cacheRequest.ifNoneMatch.replace(/^"(.*)"$/, '$1').replace(/^W\/"(.*)"$/, '$1');
193
+ if (clientEtag === hash) {
194
+ // Return 304 Not Modified
195
+ return {
196
+ notModified: true,
197
+ etag,
198
+ };
199
+ }
200
+ }
201
+
202
+ // Return full metadata with cache headers
203
+ return {
204
+ data: item,
205
+ etag,
206
+ lastModified: new Date().toISOString(),
207
+ cacheControl: {
208
+ directives: ['public', 'max-age'],
209
+ maxAge: 3600, // 1 hour
210
+ },
211
+ notModified: false,
212
+ };
213
+ } catch (error: any) {
214
+ throw error;
215
+ }
216
+ }
217
+
218
+ // ==========================================
219
+ // Batch Operations
220
+ // ==========================================
221
+
222
+ async batchData(_request: { object: string, request: BatchUpdateRequest }): Promise<BatchUpdateResponse> {
223
+ // Map high-level batch request to DataEngine batch if available
224
+ // Or implement loop here.
225
+ // For now, let's just fail or implement basic loop to satisfying interface
226
+ // since full batch mapping requires careful type handling.
227
+ throw new Error('Batch operations not yet fully implemented in protocol adapter');
228
+ }
229
+
230
+ async createManyData(request: { object: string, records: any[] }): Promise<any> {
231
+ const records = await this.engine.insert(request.object, request.records);
232
+ return {
233
+ object: request.object,
234
+ records,
235
+ count: records.length
236
+ };
237
+ }
238
+
239
+ async updateManyData(_request: UpdateManyDataRequest): Promise<any> {
240
+ // TODO: Implement proper updateMany in DataEngine
241
+ throw new Error('updateManyData not implemented');
242
+ }
243
+
244
+ async deleteManyData(request: DeleteManyDataRequest): Promise<any> {
245
+ // This expects deleting by IDs.
246
+ return this.engine.delete(request.object, {
247
+ filter: { _id: { $in: request.ids } },
248
+ ...request.options
249
+ });
250
+ }
251
+
252
+ // ==========================================
253
+ // View Storage (Mock Implementation for now)
254
+ // ==========================================
255
+
256
+ async createView(request: CreateViewRequest): Promise<ViewResponse> {
257
+ const id = Math.random().toString(36).substring(7);
258
+ // Cast to unknown then SavedView to bypass strict type checks for the mock
259
+ const view: SavedView = {
260
+ id,
261
+ ...request,
262
+ createdAt: new Date().toISOString(),
263
+ updatedAt: new Date().toISOString(),
264
+ createdBy: 'system',
265
+ updatedBy: 'system'
266
+ } as unknown as SavedView;
267
+
268
+ this.viewStorage.set(id, view);
269
+ return { success: true, data: view };
270
+ }
271
+
272
+ async getView(request: { id: string }): Promise<ViewResponse> {
273
+ const view = this.viewStorage.get(request.id);
274
+ if (!view) throw new Error(`View ${request.id} not found`);
275
+ return { success: true, data: view };
276
+ }
277
+
278
+ async listViews(request: ListViewsRequest): Promise<ListViewsResponse> {
279
+ const views = Array.from(this.viewStorage.values())
280
+ .filter(v => !request?.object || v.object === request.object);
281
+
282
+ return {
283
+ success: true,
284
+ data: views,
285
+ pagination: {
286
+ total: views.length,
287
+ limit: request.limit || 50,
288
+ offset: request.offset || 0,
289
+ hasMore: false
290
+ }
291
+ };
292
+ }
293
+
294
+ async updateView(request: UpdateViewRequest): Promise<ViewResponse> {
295
+ const view = this.viewStorage.get(request.id);
296
+ if (!view) throw new Error(`View ${request.id} not found`);
297
+
298
+ const { id, ...updates } = request;
299
+ // Cast to unknown then SavedView to bypass strict type checks for the mock
300
+ const updated = { ...view, ...updates, updatedAt: new Date().toISOString() } as unknown as SavedView;
301
+ this.viewStorage.set(request.id, updated);
302
+ return { success: true, data: updated };
99
303
  }
100
304
 
101
- deleteData(object: string, id: string) {
102
- return this.engine.delete(object, id);
305
+ async deleteView(request: { id: string }): Promise<{ success: boolean, object: string, id: string }> {
306
+ const deleted = this.viewStorage.delete(request.id);
307
+ if (!deleted) throw new Error(`View ${request.id} not found`);
308
+ return { success: true, object: 'view', id: request.id };
103
309
  }
104
310
  }