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
|
import { useMutation } from "@tanstack/react-query";
import type { Settings } from "./settings";
import { api } from "./trpc";
import type { ZBookmark } from "@hoarder/trpc/types/bookmarks";
import { zUploadResponseSchema, zUploadErrorSchema } from "@hoarder/trpc/types/uploads";
export function useUploadAsset(
settings: Settings,
options: { onSuccess?: (bookmark: ZBookmark) => void; onError?: (e: string) => void },
) {
const invalidateAllBookmarks =
api.useUtils().bookmarks.getBookmarks.invalidate;
const {
mutate: createBookmark,
isPending: isCreatingBookmark,
} = api.bookmarks.createBookmark.useMutation({
onSuccess: (d) => {
invalidateAllBookmarks();
if (options.onSuccess) {
options.onSuccess(d);
}
},
onError: (e) => {
if (options.onError) {
options.onError(e.message);
}
},
});
const {
mutate: uploadAsset,
isPending: isUploading,
} = useMutation({
mutationFn: async (file: { type: string; name: string; uri: string }) => {
const formData = new FormData();
// @ts-expect-error This is a valid api in react native
formData.append("image", {
uri: file.uri,
name: file.name,
type: file.type,
});
const resp = await fetch(`${settings.address}/api/assets`, {
method: "POST",
body: formData,
headers: {
Authorization: `Bearer ${settings.apiKey}`,
},
});
if (!resp.ok) {
throw new Error(await resp.text());
}
return zUploadResponseSchema.parse(await resp.json());
},
onSuccess: (resp) => {
const assetId = resp.assetId;
createBookmark({ type: "asset", assetId, assetType: "image" });
},
onError: (e) => {
if (options.onError) {
const err = zUploadErrorSchema.parse(JSON.parse(e.message));
options.onError(err.error);
}
},
});
return {
uploadAsset,
isPending: isUploading || isCreatingBookmark,
};
}
|