-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathrest-data-source.ts
More file actions
201 lines (160 loc) · 5.07 KB
/
rest-data-source.ts
File metadata and controls
201 lines (160 loc) · 5.07 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
/**
* 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.
*/
/**
* Example: Data Source Adapter
*
* This example demonstrates implementing a REST API data source adapter
* using the DataSource interface from @object-ui/types.
*/
import type { DataSource, QueryParams, QueryResult } from '../src/index';
/**
* REST API Data Source Implementation
*
* A generic REST API adapter that works with any REST backend.
*/
export class RestDataSource<T = any> implements DataSource<T> {
constructor(private baseUrl: string) {}
/**
* Build query string from QueryParams
*/
private buildQueryString(params?: QueryParams): string {
if (!params) return '';
const searchParams = new URLSearchParams();
if (params.$select) {
searchParams.append('select', params.$select.join(','));
}
if (params.$filter) {
searchParams.append('filter', JSON.stringify(params.$filter));
}
if (params.$orderby) {
const sort = Object.entries(params.$orderby)
.map(([key, dir]) => `${key}:${dir}`)
.join(',');
searchParams.append('sort', sort);
}
if (params.$skip !== undefined) {
searchParams.append('skip', params.$skip.toString());
}
if (params.$top !== undefined) {
searchParams.append('limit', params.$top.toString());
}
if (params.$search) {
searchParams.append('search', params.$search);
}
return searchParams.toString();
}
/**
* Fetch multiple records
*/
async find(resource: string, params?: QueryParams): Promise<QueryResult<T>> {
const queryString = this.buildQueryString(params);
const url = `${this.baseUrl}/${resource}${queryString ? '?' + queryString : ''}`;
const response = await fetch(url);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const data = await response.json();
// Assume API returns { data: [], total: number }
return {
data: data.data || data,
total: data.total,
page: params?.$skip && params?.$top
? Math.floor(params.$skip / params.$top) + 1
: 1,
pageSize: params?.$top,
hasMore: data.hasMore
};
}
/**
* Fetch a single record by ID
*/
async findOne(resource: string, id: string | number, params?: QueryParams): Promise<T | null> {
const queryString = this.buildQueryString(params);
const url = `${this.baseUrl}/${resource}/${id}${queryString ? '?' + queryString : ''}`;
const response = await fetch(url);
if (response.status === 404) {
return null;
}
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
return response.json();
}
/**
* Create a new record
*/
async create(resource: string, data: Partial<T>): Promise<T> {
const url = `${this.baseUrl}/${resource}`;
const response = await fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(data),
});
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
return response.json();
}
/**
* Update an existing record
*/
async update(resource: string, id: string | number, data: Partial<T>): Promise<T> {
const url = `${this.baseUrl}/${resource}/${id}`;
const response = await fetch(url, {
method: 'PATCH',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(data),
});
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
return response.json();
}
/**
* Delete a record
*/
async delete(resource: string, id: string | number): Promise<boolean> {
const url = `${this.baseUrl}/${resource}/${id}`;
const response = await fetch(url, {
method: 'DELETE',
});
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
return true;
}
/**
* Get object schema/metadata
*/
async getObjectSchema(objectName: string): Promise<any> {
if (!objectName || typeof objectName !== 'string') {
throw new Error('Invalid object name');
}
// Validate object name to prevent path traversal
if (objectName.includes('/') || objectName.includes('\\') || objectName.includes('..')) {
throw new Error('Invalid object name: must not contain path separators');
}
const url = `${this.baseUrl}/_schema/${encodeURIComponent(objectName)}`;
const response = await fetch(url);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
return response.json();
}
}
// Usage example:
// const dataSource = new RestDataSource('https://api.example.com');
// const users = await dataSource.find('users', {
// $filter: { status: 'active' },
// $orderby: { createdAt: 'desc' },
// $top: 10
// });