-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlogout.ts
39 lines (36 loc) · 1.22 KB
/
logout.ts
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
import { browser } from "$app/environment";
import { error } from "@sveltejs/kit";
import getErrorMessageFromResponse from "$lib/util/getErrorMessageFromResponse";
import { goto } from "$app/navigation";
import type { Writable } from "svelte/store";
import type { User } from "$lib/context/currentUser";
let logout:
| (({
currentUser,
fetch,
}: {
currentUser: Writable<User | undefined>;
fetch: typeof globalThis.fetch;
}) => void)
| undefined;
if (browser) {
logout = async ({ currentUser, fetch }) => {
const logoutResponse = await fetch("/logout", {
method: "POST",
headers: {
"Content-Type": "application/x-www-form-urlencoded",
Accept: "application/json",
},
});
if (!logoutResponse.ok) {
const responseErrorMessage = getErrorMessageFromResponse(logoutResponse);
const message = `Failed to log out: ${logoutResponse.status} ${logoutResponse.statusText}: ${responseErrorMessage}`;
throw error(500, { message });
}
const refreshURL = new URL(location.toString());
refreshURL.searchParams.delete("preview");
currentUser?.set(undefined);
await goto(refreshURL.toString(), { invalidateAll: true });
};
}
export default logout;