@objectstack/client-react 0.6.1

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.
@@ -0,0 +1,312 @@
1
+ /**
2
+ * Metadata Hooks
3
+ *
4
+ * React hooks for accessing ObjectStack metadata (schemas, views, fields)
5
+ */
6
+
7
+ import { useState, useEffect, useCallback } from 'react';
8
+ import { useClient } from './context';
9
+
10
+ /**
11
+ * Metadata query options
12
+ */
13
+ export interface UseMetadataOptions {
14
+ /** Enable/disable automatic query execution */
15
+ enabled?: boolean;
16
+ /** Use cached metadata if available */
17
+ useCache?: boolean;
18
+ /** ETag for conditional requests */
19
+ ifNoneMatch?: string;
20
+ /** If-Modified-Since header for conditional requests */
21
+ ifModifiedSince?: string;
22
+ /** Callback on successful query */
23
+ onSuccess?: (data: any) => void;
24
+ /** Callback on error */
25
+ onError?: (error: Error) => void;
26
+ }
27
+
28
+ /**
29
+ * Metadata query result
30
+ */
31
+ export interface UseMetadataResult<T = any> {
32
+ /** Metadata data */
33
+ data: T | null;
34
+ /** Loading state */
35
+ isLoading: boolean;
36
+ /** Error state */
37
+ error: Error | null;
38
+ /** Refetch the metadata */
39
+ refetch: () => Promise<void>;
40
+ /** ETag from last fetch */
41
+ etag?: string;
42
+ /** Whether data came from cache (304 Not Modified) */
43
+ fromCache: boolean;
44
+ }
45
+
46
+ /**
47
+ * Hook for fetching object schema/metadata
48
+ *
49
+ * @example
50
+ * ```tsx
51
+ * function ObjectSchemaViewer({ objectName }: { objectName: string }) {
52
+ * const { data: schema, isLoading, error } = useObject(objectName);
53
+ *
54
+ * if (isLoading) return <div>Loading schema...</div>;
55
+ * if (error) return <div>Error: {error.message}</div>;
56
+ *
57
+ * return (
58
+ * <div>
59
+ * <h2>{schema.label}</h2>
60
+ * <p>Fields: {Object.keys(schema.fields).length}</p>
61
+ * </div>
62
+ * );
63
+ * }
64
+ * ```
65
+ */
66
+ export function useObject(
67
+ objectName: string,
68
+ options: UseMetadataOptions = {}
69
+ ): UseMetadataResult {
70
+ const client = useClient();
71
+ const [data, setData] = useState<any>(null);
72
+ const [isLoading, setIsLoading] = useState(true);
73
+ const [error, setError] = useState<Error | null>(null);
74
+ const [etag, setEtag] = useState<string>();
75
+ const [fromCache, setFromCache] = useState(false);
76
+
77
+ const {
78
+ enabled = true,
79
+ useCache = true,
80
+ ifNoneMatch,
81
+ ifModifiedSince,
82
+ onSuccess,
83
+ onError
84
+ } = options;
85
+
86
+ const fetchMetadata = useCallback(async () => {
87
+ if (!enabled) return;
88
+
89
+ try {
90
+ setIsLoading(true);
91
+ setError(null);
92
+ setFromCache(false);
93
+
94
+ if (useCache) {
95
+ // Use cached metadata endpoint
96
+ const result = await client.meta.getCached(objectName, {
97
+ ifNoneMatch: ifNoneMatch || etag,
98
+ ifModifiedSince
99
+ });
100
+
101
+ if (result.notModified) {
102
+ setFromCache(true);
103
+ } else {
104
+ setData(result.data);
105
+ if (result.etag) {
106
+ setEtag(result.etag.value);
107
+ }
108
+ }
109
+
110
+ onSuccess?.(result.data || data);
111
+ } else {
112
+ // Direct fetch without cache
113
+ const result = await client.meta.getObject(objectName);
114
+ setData(result);
115
+ onSuccess?.(result);
116
+ }
117
+ } catch (err) {
118
+ const error = err instanceof Error ? err : new Error('Failed to fetch object metadata');
119
+ setError(error);
120
+ onError?.(error);
121
+ } finally {
122
+ setIsLoading(false);
123
+ }
124
+ }, [client, objectName, enabled, useCache, ifNoneMatch, ifModifiedSince, etag, data, onSuccess, onError]);
125
+
126
+ useEffect(() => {
127
+ fetchMetadata();
128
+ }, [fetchMetadata]);
129
+
130
+ const refetch = useCallback(async () => {
131
+ await fetchMetadata();
132
+ }, [fetchMetadata]);
133
+
134
+ return {
135
+ data,
136
+ isLoading,
137
+ error,
138
+ refetch,
139
+ etag,
140
+ fromCache
141
+ };
142
+ }
143
+
144
+ /**
145
+ * Hook for fetching view configuration
146
+ *
147
+ * @example
148
+ * ```tsx
149
+ * function ViewConfiguration({ objectName }: { objectName: string }) {
150
+ * const { data: view, isLoading } = useView(objectName, 'list');
151
+ *
152
+ * if (isLoading) return <div>Loading view...</div>;
153
+ *
154
+ * return (
155
+ * <div>
156
+ * <h3>List View for {objectName}</h3>
157
+ * <p>Columns: {view?.columns?.length}</p>
158
+ * </div>
159
+ * );
160
+ * }
161
+ * ```
162
+ */
163
+ export function useView(
164
+ objectName: string,
165
+ viewType: 'list' | 'form' = 'list',
166
+ options: UseMetadataOptions = {}
167
+ ): UseMetadataResult {
168
+ const client = useClient();
169
+ const [data, setData] = useState<any>(null);
170
+ const [isLoading, setIsLoading] = useState(true);
171
+ const [error, setError] = useState<Error | null>(null);
172
+
173
+ const { enabled = true, onSuccess, onError } = options;
174
+
175
+ const fetchView = useCallback(async () => {
176
+ if (!enabled) return;
177
+
178
+ try {
179
+ setIsLoading(true);
180
+ setError(null);
181
+
182
+ const result = await client.meta.getView(objectName, viewType);
183
+ setData(result);
184
+ onSuccess?.(result);
185
+ } catch (err) {
186
+ const error = err instanceof Error ? err : new Error('Failed to fetch view configuration');
187
+ setError(error);
188
+ onError?.(error);
189
+ } finally {
190
+ setIsLoading(false);
191
+ }
192
+ }, [client, objectName, viewType, enabled, onSuccess, onError]);
193
+
194
+ useEffect(() => {
195
+ fetchView();
196
+ }, [fetchView]);
197
+
198
+ const refetch = useCallback(async () => {
199
+ await fetchView();
200
+ }, [fetchView]);
201
+
202
+ return {
203
+ data,
204
+ isLoading,
205
+ error,
206
+ refetch,
207
+ fromCache: false
208
+ };
209
+ }
210
+
211
+ /**
212
+ * Hook for extracting fields from object schema
213
+ *
214
+ * @example
215
+ * ```tsx
216
+ * function FieldList({ objectName }: { objectName: string }) {
217
+ * const { data: fields, isLoading } = useFields(objectName);
218
+ *
219
+ * if (isLoading) return <div>Loading fields...</div>;
220
+ *
221
+ * return (
222
+ * <ul>
223
+ * {fields?.map(field => (
224
+ * <li key={field.name}>{field.label} ({field.type})</li>
225
+ * ))}
226
+ * </ul>
227
+ * );
228
+ * }
229
+ * ```
230
+ */
231
+ export function useFields(
232
+ objectName: string,
233
+ options: UseMetadataOptions = {}
234
+ ): UseMetadataResult<any[]> {
235
+ const objectResult = useObject(objectName, options);
236
+
237
+ const fields = objectResult.data?.fields
238
+ ? Object.entries(objectResult.data.fields).map(([name, field]: [string, any]) => ({
239
+ name,
240
+ ...field
241
+ }))
242
+ : null;
243
+
244
+ return {
245
+ ...objectResult,
246
+ data: fields
247
+ };
248
+ }
249
+
250
+ /**
251
+ * Generic metadata hook for custom metadata queries
252
+ *
253
+ * @example
254
+ * ```tsx
255
+ * function CustomMetadata() {
256
+ * const { data, isLoading } = useMetadata(async (client) => {
257
+ * // Custom metadata fetching logic
258
+ * const object = await client.meta.getObject('custom_object');
259
+ * const view = await client.meta.getView('custom_object', 'list');
260
+ * return { object, view };
261
+ * });
262
+ *
263
+ * return <pre>{JSON.stringify(data, null, 2)}</pre>;
264
+ * }
265
+ * ```
266
+ */
267
+ export function useMetadata<T = any>(
268
+ fetcher: (client: ReturnType<typeof useClient>) => Promise<T>,
269
+ options: Omit<UseMetadataOptions, 'useCache' | 'ifNoneMatch' | 'ifModifiedSince'> = {}
270
+ ): UseMetadataResult<T> {
271
+ const client = useClient();
272
+ const [data, setData] = useState<T | null>(null);
273
+ const [isLoading, setIsLoading] = useState(true);
274
+ const [error, setError] = useState<Error | null>(null);
275
+
276
+ const { enabled = true, onSuccess, onError } = options;
277
+
278
+ const fetchMetadata = useCallback(async () => {
279
+ if (!enabled) return;
280
+
281
+ try {
282
+ setIsLoading(true);
283
+ setError(null);
284
+
285
+ const result = await fetcher(client);
286
+ setData(result);
287
+ onSuccess?.(result);
288
+ } catch (err) {
289
+ const error = err instanceof Error ? err : new Error('Failed to fetch metadata');
290
+ setError(error);
291
+ onError?.(error);
292
+ } finally {
293
+ setIsLoading(false);
294
+ }
295
+ }, [client, fetcher, enabled, onSuccess, onError]);
296
+
297
+ useEffect(() => {
298
+ fetchMetadata();
299
+ }, [fetchMetadata]);
300
+
301
+ const refetch = useCallback(async () => {
302
+ await fetchMetadata();
303
+ }, [fetchMetadata]);
304
+
305
+ return {
306
+ data,
307
+ isLoading,
308
+ error,
309
+ refetch,
310
+ fromCache: false
311
+ };
312
+ }
package/tsconfig.json ADDED
@@ -0,0 +1,12 @@
1
+ {
2
+ "extends": "../../tsconfig.json",
3
+ "compilerOptions": {
4
+ "outDir": "./dist",
5
+ "rootDir": "./src",
6
+ "declaration": true,
7
+ "declarationMap": true,
8
+ "jsx": "react"
9
+ },
10
+ "include": ["src/**/*"],
11
+ "exclude": ["node_modules", "dist", "**/*.test.ts"]
12
+ }