-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathobjectstack-adapter.ts
More file actions
213 lines (189 loc) · 5.86 KB
/
objectstack-adapter.ts
File metadata and controls
213 lines (189 loc) · 5.86 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
/**
* ObjectUI
* Copyright (c) 2024-present ObjectStack Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
import { ObjectStackClient, type QueryOptions as ObjectStackQueryOptions } from '@objectstack/client';
import type { DataSource, QueryParams, QueryResult } from '@object-ui/types';
import { convertFiltersToAST } from '../utils/filter-converter';
/**
* ObjectStack Data Source Adapter
*
* Bridges the ObjectStack Client SDK with the ObjectUI DataSource interface.
* This allows Object UI applications to seamlessly integrate with ObjectStack
* backends while maintaining the universal DataSource abstraction.
*
* @example
* ```typescript
* import { ObjectStackAdapter } from '@object-ui/core/adapters';
*
* const dataSource = new ObjectStackAdapter({
* baseUrl: 'https://api.example.com',
* token: 'your-api-token'
* });
*
* const users = await dataSource.find('users', {
* $filter: { status: 'active' },
* $top: 10
* });
* ```
*/
export class ObjectStackAdapter<T = any> implements DataSource<T> {
private client: ObjectStackClient;
private connected: boolean = false;
constructor(config: {
baseUrl: string;
token?: string;
fetch?: (input: RequestInfo | URL, init?: RequestInit) => Promise<Response>;
}) {
this.client = new ObjectStackClient(config);
}
/**
* Ensure the client is connected to the server.
* Call this before making requests or it will auto-connect on first request.
*/
async connect(): Promise<void> {
if (!this.connected) {
await this.client.connect();
this.connected = true;
}
}
/**
* Find multiple records with query parameters.
* Converts OData-style params to ObjectStack query options.
*/
async find(resource: string, params?: QueryParams): Promise<QueryResult<T>> {
await this.connect();
const queryOptions = this.convertQueryParams(params);
const result = await this.client.data.find<T>(resource, queryOptions);
return {
data: result.value,
total: result.count,
page: params?.$skip ? Math.floor(params.$skip / (params.$top || 20)) + 1 : 1,
pageSize: params?.$top,
hasMore: result.value.length === params?.$top,
};
}
/**
* Find a single record by ID.
*/
async findOne(resource: string, id: string | number, _params?: QueryParams): Promise<T | null> {
await this.connect();
try {
const record = await this.client.data.get<T>(resource, String(id));
return record;
} catch (error) {
// If record not found, return null instead of throwing
if ((error as any)?.status === 404) {
return null;
}
throw error;
}
}
/**
* Create a new record.
*/
async create(resource: string, data: Partial<T>): Promise<T> {
await this.connect();
return this.client.data.create<T>(resource, data);
}
/**
* Update an existing record.
*/
async update(resource: string, id: string | number, data: Partial<T>): Promise<T> {
await this.connect();
return this.client.data.update<T>(resource, String(id), data);
}
/**
* Delete a record.
*/
async delete(resource: string, id: string | number): Promise<boolean> {
await this.connect();
const result = await this.client.data.delete(resource, String(id));
return result.success;
}
/**
* Bulk operations (optional implementation).
*/
async bulk(resource: string, operation: 'create' | 'update' | 'delete', data: Partial<T>[]): Promise<T[]> {
await this.connect();
switch (operation) {
case 'create':
return this.client.data.createMany<T>(resource, data);
case 'delete': {
const ids = data.map(item => (item as any).id).filter(Boolean);
await this.client.data.deleteMany(resource, ids);
return [];
}
case 'update': {
// For update, we need to handle each record individually
// or use the batch update if all records get the same changes
const results = await Promise.all(
data.map(item =>
this.client.data.update<T>(resource, String((item as any).id), item)
)
);
return results;
}
default:
throw new Error(`Unsupported bulk operation: ${operation}`);
}
}
/**
* Convert ObjectUI QueryParams to ObjectStack QueryOptions.
* Maps OData-style conventions to ObjectStack conventions.
*/
private convertQueryParams(params?: QueryParams): ObjectStackQueryOptions {
if (!params) return {};
const options: ObjectStackQueryOptions = {};
// Selection
if (params.$select) {
options.select = params.$select;
}
// Filtering - convert to ObjectStack FilterNode AST format
if (params.$filter) {
options.filters = convertFiltersToAST(params.$filter);
}
// Sorting - convert to ObjectStack format
if (params.$orderby) {
const sortArray = Object.entries(params.$orderby).map(([field, order]) => {
return order === 'desc' ? `-${field}` : field;
});
options.sort = sortArray;
}
// Pagination
if (params.$skip !== undefined) {
options.skip = params.$skip;
}
if (params.$top !== undefined) {
options.top = params.$top;
}
return options;
}
/**
* Get access to the underlying ObjectStack client for advanced operations.
*/
getClient(): ObjectStackClient {
return this.client;
}
}
/**
* Factory function to create an ObjectStack data source.
*
* @example
* ```typescript
* const dataSource = createObjectStackAdapter({
* baseUrl: process.env.API_URL,
* token: process.env.API_TOKEN
* });
* ```
*/
export function createObjectStackAdapter<T = any>(config: {
baseUrl: string;
token?: string;
fetch?: (input: RequestInfo | URL, init?: RequestInit) => Promise<Response>;
}): DataSource<T> {
return new ObjectStackAdapter<T>(config);
}