forked from openedx/frontend-app-authoring
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapiHooks.ts
More file actions
291 lines (273 loc) · 10.4 KB
/
apiHooks.ts
File metadata and controls
291 lines (273 loc) · 10.4 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
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
/**
* This is a file used especially in this `taxonomy` module.
*
* We are using a new approach, using `useQuery` to build and execute the queries to the APIs.
* This approach accelerates the development.
*
* In this file you will find two types of hooks:
* - Hooks that builds the query with `useQuery`. These hooks are not used outside of this file.
* Ex. useTaxonomyListData.
* - Hooks that calls the query hook, prepare and return the data.
* Ex. useTaxonomyListDataResponse & useIsTaxonomyListDataLoaded.
*/
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { camelCaseObject } from '@edx/frontend-platform';
import { getAuthenticatedHttpClient } from '@edx/frontend-platform/auth';
import { apiUrls, ALL_TAXONOMIES, getApiErrorMessage } from './api';
import * as api from './api';
import type { QueryOptions, TagListData } from './types';
// Query key patterns. Allows an easy way to clear all data related to a given taxonomy.
// https://github.com/openedx/frontend-app-admin-portal/blob/2ba315d/docs/decisions/0006-tanstack-react-query.rst
// Inspired by https://tkdodo.eu/blog/effective-react-query-keys#use-query-key-factories.
export const taxonomyQueryKeys = {
all: ['taxonomies'],
/**
* Key for the list of taxonomies, optionally filtered by org.
* @param org Which org we fetched the taxonomy list for (optional)
*/
taxonomyList: (org?: string) => [
...taxonomyQueryKeys.all,
'taxonomyList',
...(org && org !== ALL_TAXONOMIES ? [org] : []),
],
/**
* Base key for data specific to a single taxonomy. No data is stored directly in this key.
* @param taxonomyId ID of the taxonomy
*/
taxonomy: (taxonomyId: number) => [...taxonomyQueryKeys.all, 'taxonomy', taxonomyId],
/**
* @param taxonomyId ID of the taxonomy
*/
taxonomyMetadata: (taxonomyId: number) => [...taxonomyQueryKeys.taxonomy(taxonomyId), 'metadata'],
/**
* @param taxonomyId ID of the taxonomy
*/
taxonomyTagList: (taxonomyId: number) => [...taxonomyQueryKeys.taxonomy(taxonomyId), 'tags'],
/**
* @param taxonomyId ID of the taxonomy
* @param pageIndex Which page of tags to load (zero-based)
* @param pageSize
*/
taxonomyTagListPage: (taxonomyId: number, pageIndex: number, pageSize: number) => [
...taxonomyQueryKeys.taxonomyTagList(taxonomyId),
'page',
pageIndex,
pageSize,
],
/**
* Query for loading _all_ the subtags of a particular parent tag
* @param taxonomyId ID of the taxonomy
* @param parentTagValue
*/
taxonomyTagSubtagsList: (taxonomyId: number, parentTagValue: string) => [
...taxonomyQueryKeys.taxonomyTagList(taxonomyId),
'subtags',
parentTagValue,
],
/**
* @param taxonomyId ID of the taxonomy
* @param fileId Some string to uniquely identify the file we want to upload
*/
importPlan: (taxonomyId: number, fileId: string) => [...taxonomyQueryKeys.all, 'importPlan', taxonomyId, fileId],
} satisfies Record<string, (string | number)[] | ((...args: any[]) => (string | number)[])>;
/**
* Builds the query to get the taxonomy list
* @param {string} [org] Filter the list to only show taxonomies assigned to this org
*/
export const useTaxonomyList = (org) => (
useQuery({
queryKey: taxonomyQueryKeys.taxonomyList(org),
queryFn: () => api.getTaxonomyListData(org),
})
);
/**
* Builds the mutation to delete a taxonomy.
* @returns A function that can be used to delete the taxonomy.
*/
export const useDeleteTaxonomy = () => {
const queryClient = useQueryClient();
const { mutateAsync } = useMutation({
mutationFn: async ({ pk }: { pk: number; }) => api.deleteTaxonomy(pk),
onSettled: (_d, _e, args) => {
queryClient.invalidateQueries({ queryKey: taxonomyQueryKeys.taxonomyList() });
queryClient.removeQueries({ queryKey: taxonomyQueryKeys.taxonomy(args.pk) });
},
});
return mutateAsync;
};
/** Builds the query to get the taxonomy detail */
export const useTaxonomyDetails = (taxonomyId: number) =>
useQuery({
queryKey: taxonomyQueryKeys.taxonomyMetadata(taxonomyId),
queryFn: () => api.getTaxonomy(taxonomyId),
refetchOnMount: 'always',
});
/**
* Use this mutation to import a new taxonomy.
*/
export const useImportNewTaxonomy = () => {
const queryClient = useQueryClient();
return useMutation({
mutationFn: async ({
name,
description,
file,
}: { name: string; description: string; file: File; }) => {
const formData = new FormData();
formData.append('taxonomy_name', name);
formData.append('taxonomy_description', description);
formData.append('file', file);
const { data } = await getAuthenticatedHttpClient().post(apiUrls.createTaxonomyFromImport(), formData);
return camelCaseObject(data);
},
onSuccess: (data) => {
// There's a new taxonomy, so the list of taxonomies needs to be refreshed:
queryClient.invalidateQueries({
queryKey: taxonomyQueryKeys.taxonomyList(),
});
queryClient.setQueryData(taxonomyQueryKeys.taxonomyMetadata(data.id), data);
},
});
};
/**
* Build the mutation to import tags to an existing taxonomy
*/
export const useImportTags = () => {
const queryClient = useQueryClient();
return useMutation({
mutationFn: async ({ taxonomyId, file }: { taxonomyId: number; file: File; }) => {
const formData = new FormData();
formData.append('file', file);
try {
const { data } = await getAuthenticatedHttpClient().put(apiUrls.tagsImport(taxonomyId), formData);
return camelCaseObject(data);
} catch (err) {
throw new Error(getApiErrorMessage(err));
}
},
onSuccess: (data) => {
queryClient.invalidateQueries({
queryKey: taxonomyQueryKeys.taxonomyTagList(data.id),
});
// In the metadata, 'tagsCount' (and possibly other fields) will have changed:
queryClient.setQueryData(taxonomyQueryKeys.taxonomyMetadata(data.id), data);
},
});
};
/**
* Preview the results of importing the given file into an existing taxonomy.
* @param taxonomyId The ID of the taxonomy whose tags we're updating.
* @param file The file that we want to import
*/
export const useImportPlan = (taxonomyId: number, file: File | null) =>
useQuery({
queryKey: taxonomyQueryKeys.importPlan(taxonomyId, file ? `${file.name}${file.lastModified}${file.size}` : ''),
queryFn: async (): Promise<string | null> => {
if (!taxonomyId || file === null) {
return null;
}
const formData = new FormData();
formData.append('file', file);
try {
const { data } = await getAuthenticatedHttpClient().put(apiUrls.tagsPlanImport(taxonomyId), formData);
return data.plan as string;
} catch (err) {
throw new Error(getApiErrorMessage(err));
}
},
retry: false, // If there's an error, it's probably a real problem with the file. Don't try again several times!
});
/**
* Use the list of tags in a taxonomy.
*/
export const useTagListData = (taxonomyId: number, options: QueryOptions) => {
const { pageIndex, pageSize, enabled = true, disablePagination = false } = options; // eslint-disable-line
return useQuery({
// queryKey: taxonomyQueryKeys.taxonomyTagListPage(taxonomyId, pageIndex, pageSize),
queryKey: taxonomyQueryKeys.taxonomyTagList(taxonomyId), // For now, ignore pagination in the query key.
queryFn: async () => {
const { data } = await getAuthenticatedHttpClient().get(
apiUrls.tagList(taxonomyId, {
pageIndex,
pageSize,
fullDepth: true,
disablePagination,
}),
);
return camelCaseObject(data) as TagListData;
},
enabled,
refetchOnMount: 'always',
});
};
/**
* Temporary hook to load *all* the subtags of a given tag in a taxonomy.
* Doesn't handle pagination or anything. This is meant to be replaced by
* something more sophisticated later, as we improve the "taxonomy details" page.
*/
export const useSubTags = (taxonomyId: number, parentTagValue: string) =>
useQuery({
queryKey: taxonomyQueryKeys.taxonomyTagSubtagsList(taxonomyId, parentTagValue),
queryFn: async () => {
const response = await getAuthenticatedHttpClient().get(apiUrls.allSubtagsOf(taxonomyId, parentTagValue));
return camelCaseObject(response.data) as TagListData;
},
});
export const useCreateTag = (taxonomyId: number) => {
const queryClient = useQueryClient();
return useMutation({
mutationFn: async ({ value, parentTagValue }: { value: string; parentTagValue?: string; }) => {
await getAuthenticatedHttpClient().post(
apiUrls.createTag(taxonomyId),
{ tag: value, parent_tag_value: parentTagValue },
);
},
onSuccess: () => {
queryClient.invalidateQueries({
queryKey: taxonomyQueryKeys.taxonomyTagList(taxonomyId),
refetchType: 'none',
});
// In the metadata, 'tagsCount' (and possibly other fields) will have changed:
queryClient.invalidateQueries({
queryKey: taxonomyQueryKeys.taxonomyMetadata(taxonomyId),
refetchType: 'none',
});
},
});
};
export const useUpdateTag = (taxonomyId: number) => {
const queryClient = useQueryClient();
return useMutation({
mutationFn: async ({ value, originalValue }: { value: string; originalValue: string; }) => {
await getAuthenticatedHttpClient().patch(
apiUrls.updateTag(taxonomyId),
{ tag: originalValue, updated_tag_value: value },
);
},
onSuccess: () => {
queryClient.invalidateQueries({
queryKey: taxonomyQueryKeys.taxonomyTagList(taxonomyId),
});
// In the metadata, 'tagsCount' (and possibly other fields) will have changed:
queryClient.invalidateQueries({ queryKey: taxonomyQueryKeys.taxonomyMetadata(taxonomyId) });
},
});
};
export const useDeleteTag = (taxonomyId: number) => {
const queryClient = useQueryClient();
return useMutation({
mutationFn: async ({ value, withSubtags }: { value: string; withSubtags: boolean; }) => {
const body = { tags: [value], with_subtags: withSubtags };
await getAuthenticatedHttpClient().delete(apiUrls.deleteTag(taxonomyId), {
data: body,
});
},
onSuccess: () => {
queryClient.invalidateQueries({
queryKey: taxonomyQueryKeys.taxonomyTagList(taxonomyId),
});
// In the metadata, 'tagsCount' (and possibly other fields) will have changed:
queryClient.invalidateQueries({ queryKey: taxonomyQueryKeys.taxonomyMetadata(taxonomyId) });
},
});
};