Skip to content

Commit 9059aef

Browse files
ClemsazertSimonClo
authored andcommitted
✨ create doc & table hook
1 parent c46d36c commit 9059aef

File tree

1 file changed

+64
-0
lines changed

1 file changed

+64
-0
lines changed
Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
import { APIError, errorCauses, gristFetchApi } from '@/api';
2+
3+
import { TableDescription } from './useListGristTables';
4+
5+
export const useGristCreateDocAndTable = () => {
6+
const createTable = async (
7+
name: string,
8+
): Promise<{
9+
documentId: string;
10+
tableId: string;
11+
}> => {
12+
const DEFAULT_WORKSPACE_ID = 2;
13+
const docUrl = `workspaces/${DEFAULT_WORKSPACE_ID}/docs`;
14+
try {
15+
const docResponse = await gristFetchApi(docUrl, {
16+
method: 'POST',
17+
headers: {
18+
'Content-Type': 'application/json',
19+
},
20+
body: JSON.stringify({ name }),
21+
});
22+
23+
if (!docResponse.ok) {
24+
throw new APIError(
25+
'Failed to fetch Grist tables',
26+
await errorCauses(docResponse),
27+
);
28+
}
29+
30+
const documentId = (await docResponse.json()) as string;
31+
32+
const tableUrl = `docs/${documentId}/tables`;
33+
const tableResponse = await gristFetchApi(tableUrl);
34+
if (!tableResponse.ok) {
35+
throw new APIError(
36+
'Failed to fetch Grist tables',
37+
await errorCauses(tableResponse),
38+
);
39+
}
40+
41+
const tableDescription = (await tableResponse.json()) as TableDescription;
42+
43+
if (tableDescription.tables.length === 0) {
44+
throw new Error('No tables found in the created document');
45+
}
46+
47+
if (tableDescription.tables.length > 1) {
48+
throw new Error(
49+
'More than one table has been found in the created document, this should not happen.',
50+
);
51+
}
52+
53+
return {
54+
documentId,
55+
tableId: tableDescription.tables[0].id,
56+
};
57+
} catch (error) {
58+
console.error('Error creating Grist table:', error);
59+
throw error;
60+
}
61+
};
62+
63+
return { createTable };
64+
};

0 commit comments

Comments
 (0)