mirror of
https://github.com/hex248/sprint.git
synced 2026-02-08 02:33:01 +00:00
refactored frontend api helpers to promise interface
This commit is contained in:
@@ -1,10 +1,8 @@
|
||||
import type { OrganisationRecord, OrgCreateRequest } from "@sprint/shared";
|
||||
import { toast } from "sonner";
|
||||
import { getCsrfToken, getServerURL } from "@/lib/utils";
|
||||
import type { ServerQueryInput } from "..";
|
||||
import { getErrorMessage } from "..";
|
||||
|
||||
export async function create(request: OrgCreateRequest & ServerQueryInput<OrganisationRecord>) {
|
||||
const { onSuccess, onError, ...body } = request;
|
||||
export async function create(request: OrgCreateRequest): Promise<OrganisationRecord> {
|
||||
const csrfToken = getCsrfToken();
|
||||
|
||||
const res = await fetch(`${getServerURL()}/organisation/create`, {
|
||||
@@ -13,25 +11,18 @@ export async function create(request: OrgCreateRequest & ServerQueryInput<Organi
|
||||
"Content-Type": "application/json",
|
||||
...(csrfToken ? { "X-CSRF-Token": csrfToken } : {}),
|
||||
},
|
||||
body: JSON.stringify(body),
|
||||
body: JSON.stringify(request),
|
||||
credentials: "include",
|
||||
});
|
||||
|
||||
if (!res.ok) {
|
||||
const error = await res.json().catch(() => res.text());
|
||||
const message =
|
||||
typeof error === "string"
|
||||
? error
|
||||
: error.error || `failed to create organisation (${res.status})`;
|
||||
toast.error(message);
|
||||
onError?.(error);
|
||||
} else {
|
||||
const data = await res.json();
|
||||
if (!data.id) {
|
||||
toast.error(`failed to create organisation (${res.status})`);
|
||||
onError?.(`failed to create organisation (${res.status})`);
|
||||
return;
|
||||
}
|
||||
onSuccess?.(data, res);
|
||||
const message = await getErrorMessage(res, `failed to create organisation (${res.status})`);
|
||||
throw new Error(message);
|
||||
}
|
||||
|
||||
const data = (await res.json()) as OrganisationRecord;
|
||||
if (!data.id) {
|
||||
throw new Error(`failed to create organisation (${res.status})`);
|
||||
}
|
||||
return data;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user