chore: restructure to have small backend sdk as well

This commit is contained in:
janishutz committed 2026-09-10 14:53:41 +02:00
1 parent 6d13fbb75b
commit 4d7b326df5
15 files changed
+3206 -1

No files matched your search

+8
View File
@@ -0,0 +1,8 @@
export const login = () => {
sessionStorage.setItem( 'redirect', location.pathname );
location.href = '/login';
};
export const check = () => {};
export const logout = () => {};
+21
View File
@@ -0,0 +1,21 @@
import {
Config
} from './dtype.js';
let configuration: Config = {
'backendURL': new URL( '' ),
'defaultAuthErrorResolution': 'error'
};
const get = () => {
return configuration;
};
const configure = ( config: Config ) => {
configuration = config;
};
export default {
configure,
get
};
+16
View File
@@ -0,0 +1,16 @@
export type AuthErrorResolution = 'resolve' | 'error';
export interface Config {
'backendURL': URL;
'defaultAuthErrorResolution': AuthErrorResolution;
'authErrorEvent'?: string;
'authCheckEndpoint'?: string;
'loginEndpoing'?: string;
'logoutEndpoint'?: string;
}
declare global {
interface GlobalEventHandlersEventMap {
'autherror': CustomEvent<void>
}
}
+8
View File
@@ -0,0 +1,8 @@
import config from './config.js';
export const configure = config.configure;
/**
* Wrapper on top of fetch, with redirects from the backend handled according to your rules
*/
export * as request from './request.js';
+52
View File
@@ -0,0 +1,52 @@
import config from './config.js';
import {
login
} from './auth.js';
export class AuthError extends Error {}
export class UnownedError extends Error {}
const get = async ( url: string ): Promise<Response> => {
return await wrapper( url, {
'credentials': 'include'
} );
};
const post = async ( url: string, payload: string, mime: string = 'application/json' ): Promise<Response> => {
return await wrapper( url, {
'credentials': 'include',
'body': payload,
'method': 'post',
'headers': {
'Content-Type': mime ?? 'application/json'
}
} );
};
const wrapper = async ( url: string, opts: RequestInit ): Promise<Response> => {
const res = await fetch( config.get().backendURL + url, {
'redirect': 'manual',
...opts
} );
if ( res.type === 'opaqueredirect' ) {
if ( config.get().authErrorEvent ) {
document.dispatchEvent( new CustomEvent( 'autherror' ) );
}
if ( config.get().defaultAuthErrorResolution === 'resolve' ) {
login();
} else {
throw new AuthError( 'ERR_USER_UNAUTHORIZED' );
}
} else {
return res;
}
};
export default {
get,
post
};