aboutsummaryrefslogtreecommitdiffstats
path: root/apps/mobile/lib/upload.ts
blob: b31faa90c8aed67b85766938b9b1576fa996689c (plain) (blame)
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
import { useMutation } from "@tanstack/react-query";

import { BookmarkTypes, ZBookmark } from "@hoarder/shared/types/bookmarks";
import {
  zUploadErrorSchema,
  zUploadResponseSchema,
} from "@hoarder/shared/types/uploads";

import type { Settings } from "./settings";
import { api } from "./trpc";

export function useUploadAsset(
  settings: Settings,
  options: {
    onSuccess?: (bookmark: ZBookmark & { alreadyExists: boolean }) => 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("file", {
        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;
      const assetType =
        resp.contentType === "application/pdf" ? "pdf" : "image";
      createBookmark({ type: BookmarkTypes.ASSET, assetId, assetType });
    },
    onError: (e) => {
      if (options.onError) {
        const err = zUploadErrorSchema.parse(JSON.parse(e.message));
        options.onError(err.error);
      }
    },
  });

  return {
    uploadAsset,
    isPending: isUploading || isCreatingBookmark,
  };
}