[FIX] Fix Client Functions and Add Base Path Option (#63)

Fixes #54.
This commit is contained in:
Dan6erbond 2022-01-12 20:28:20 +01:00 committed by GitHub
parent 099dfd294f
commit ac77764b3d
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
4 changed files with 33 additions and 6 deletions

19
src/client/helpers.ts Normal file
View File

@ -0,0 +1,19 @@
function mergePath(basePaths: (string | null)[], path: string) {
if (path.startsWith("/")) {
path = path.slice(1);
}
let retPath;
for (let basePath of basePaths) {
if (basePath !== null) {
if (!basePath.startsWith("/")) {
basePath = "/" + basePath;
}
if (!basePath.endsWith("/")) {
basePath = basePath + "/";
}
retPath = basePath + path;
}
}
return retPath;
}

View File

@ -1,14 +1,15 @@
/* import { goto } from "@sveltejs/kit/assets/runtime/app/navigation";
import { page } from "@sveltejs/kit/assets/runtime/app/stores"; */
import type { LoadInput } from "@sveltejs/kit";
import type { ClientRequestConfig } from "./types";
interface SignInConfig {
interface SignInConfig extends ClientRequestConfig {
redirectUrl?: string;
}
export async function signIn(provider: string, data?: any, config?: SignInConfig) {
if (data) {
const path = `/api/auth/callback/${provider}`;
const path = mergePath(["/api/auth", config?.basePath ?? null], `/callback/${provider}`);
const res = await fetch(path, {
method: "POST",
headers: {
@ -34,7 +35,7 @@ export async function signIn(provider: string, data?: any, config?: SignInConfig
redirect: redirectUrl ?? "/",
};
const query = new URLSearchParams(queryData);
const path = `/api/auth/login/${provider}?${query}`;
const path = mergePath(["/api/auth", config?.basePath ?? null], `/signin/${provider}?${query}`);
return path; // await goto(path);
}

View File

@ -1,14 +1,18 @@
/* import { session as session$ } from "$app/stores"; */
export async function signOut() {
let res = await fetch("/api/auth/signout", { method: "POST" });
import type { ClientRequestConfig } from "./types";
export async function signOut(config?: ClientRequestConfig) {
let res = await fetch(mergePath(["/api/auth", config?.basePath ?? null], "signout"), {
method: "POST",
});
const { signout } = await res.json();
if (!signout) {
throw new Error("Sign out not successful!");
}
res = await fetch("/api/auth/session");
res = await fetch(mergePath(["/api/auth", config?.basePath ?? null], "session"));
const session = await res.json();
return session;

3
src/client/types.ts Normal file
View File

@ -0,0 +1,3 @@
export interface ClientRequestConfig {
basePath?: string;
}