Skip to content

Commit b405d01

Browse files
ClemsazertSimonClo
authored andcommitted
✨ useGristCrudRecords hook
1 parent 1037dcb commit b405d01

File tree

2 files changed

+89
-0
lines changed

2 files changed

+89
-0
lines changed
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
11
export * from './useGristTableData';
22
export * from './useListGristDocs';
33
export * from './useListGristTables';
4+
export * from './useGristCrudRecords';
Lines changed: 88 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,88 @@
1+
import { gristFetchApi } from '@/api';
2+
3+
export const useGristCrudRecords = () => {
4+
const createRecords = async (
5+
documentId: string,
6+
tableId: string,
7+
records: { fields: unknown }[],
8+
) => {
9+
const url = `docs/${documentId}/tables/${tableId}/records`;
10+
try {
11+
const response = await gristFetchApi(url, {
12+
method: 'POST',
13+
headers: {
14+
'Content-Type': 'application/json',
15+
},
16+
body: JSON.stringify(records),
17+
});
18+
19+
if (!response.ok) {
20+
const errorBody = await response.text();
21+
throw new Error(
22+
`Failed to create record: ${response.status} ${response.statusText} - ${errorBody}`,
23+
);
24+
}
25+
26+
return (await response.json()) as Promise<{ records: { id: string }[] }>;
27+
} catch (error) {
28+
console.error('Error creating Grist record:', error);
29+
throw error;
30+
}
31+
};
32+
33+
const deleteRecords = async (
34+
documentId: string,
35+
tableId: string,
36+
recordIds: number[],
37+
) => {
38+
const url = `docs/${documentId}/tables/${tableId}/data/delete`;
39+
try {
40+
const response = await gristFetchApi(url, {
41+
method: 'POST',
42+
headers: {
43+
'Content-Type': 'application/json',
44+
},
45+
body: JSON.stringify(recordIds),
46+
});
47+
48+
if (!response.ok) {
49+
const errorBody = await response.text();
50+
throw new Error(
51+
`Failed to delete records: ${response.status} ${response.statusText} - ${errorBody}`,
52+
);
53+
}
54+
} catch (error) {
55+
console.error('Error deleting Grist records:', error);
56+
throw error;
57+
}
58+
};
59+
60+
const updateRecords = async (
61+
documentId: string,
62+
tableId: string,
63+
records: { id: number; fields: unknown }[],
64+
) => {
65+
const url = `docs/${documentId}/tables/${tableId}/records`;
66+
try {
67+
const response = await gristFetchApi(url, {
68+
method: 'PATCH',
69+
headers: {
70+
'Content-Type': 'application/json',
71+
},
72+
body: JSON.stringify(records),
73+
});
74+
75+
if (!response.ok) {
76+
const errorBody = await response.text();
77+
throw new Error(
78+
`Failed to update records: ${response.status} ${response.statusText} - ${errorBody}`,
79+
);
80+
}
81+
} catch (error) {
82+
console.error('Error updating Grist records:', error);
83+
throw error;
84+
}
85+
};
86+
87+
return { createRecords, deleteRecords, updateRecords };
88+
};

0 commit comments

Comments
 (0)