feat: rewrite auth (#364)

* feat: wip rewrite auth

* feat: restructure folders and fix stories and tests

* feat: remove auth provider and fix tests
This commit is contained in:
Jérémy M
2023-06-23 17:49:50 +02:00
committed by GitHub
parent 1c7980b270
commit c6708b2c1f
54 changed files with 1268 additions and 584 deletions

View File

@ -0,0 +1,3 @@
export function assertNotNull<T>(item: T): item is NonNullable<T> {
return item !== null && item !== undefined;
}

View File

@ -0,0 +1,62 @@
import Cookies, { CookieAttributes } from 'js-cookie';
type Listener = (
newValue: string | undefined,
oldValue: string | undefined,
) => void;
class CookieStorage {
private listeners: Record<string, Listener[]> = {};
private keys: Set<string> = new Set();
getItem(key: string): string | undefined {
return Cookies.get(key);
}
setItem(key: string, value: string, attributes?: CookieAttributes): void {
const oldValue = this.getItem(key);
this.keys.add(key);
Cookies.set(key, value, attributes);
this.dispatch(key, value, oldValue);
}
removeItem(key: string): void {
const oldValue = this.getItem(key);
this.keys.delete(key);
Cookies.remove(key);
this.dispatch(key, undefined, oldValue);
}
clear(): void {
this.keys.forEach((key) => this.removeItem(key));
}
private dispatch(
key: string,
newValue: string | undefined,
oldValue: string | undefined,
): void {
if (this.listeners[key]) {
this.listeners[key].forEach((callback) => callback(newValue, oldValue));
}
}
addEventListener(key: string, callback: Listener): void {
if (!this.listeners[key]) {
this.listeners[key] = [];
}
this.listeners[key].push(callback);
}
removeEventListener(key: string, callback: Listener): void {
if (this.listeners[key]) {
this.listeners[key] = this.listeners[key].filter(
(listener) => listener !== callback,
);
}
}
}
export const cookieStorage = new CookieStorage();

View File

@ -0,0 +1,16 @@
import { Observable } from '@apollo/client';
export const promiseToObservable = <T>(promise: Promise<T>) =>
new Observable<T>((subscriber) => {
promise.then(
(value) => {
if (subscriber.closed) {
return;
}
subscriber.next(value);
subscriber.complete();
},
(err) => subscriber.error(err),
);
});