convex
Version:
Client for the Convex Cloud
33 lines (30 loc) • 1.02 kB
text/typescript
import { GenericAPI, MutationNames } from "../browser/index.js";
import { StorageId } from "../server/storage.js";
import { useMutationGeneric } from "../react/index.js";
/**
* TODO(CX-2960) Use codegen to make non-generic version
*
* @internal
*/
export function useUploadGeneric<
API extends GenericAPI,
Name extends MutationNames<API>
>(name: Name): (file: File) => Promise<StorageId> {
const generateUploadUrl = useMutationGeneric(name);
return async (file: File): Promise<StorageId> => {
const postUrl = await generateUploadUrl();
const res = await fetch(postUrl, {
method: "POST",
headers: { "Content-Type": file.type },
body: file,
});
if (res.status === 200) {
const { storageId } = await res.json();
return storageId;
} else {
const { code, message } = await res.json();
console.error(`${res.status} ${res.statusText}: ${code}: ${message}`);
throw new Error(`${res.status} ${res.statusText}: ${code}: ${message}`);
}
};
}