94 lines
2.5 KiB
TypeScript
94 lines
2.5 KiB
TypeScript
export interface User {
|
|
email: string;
|
|
name: string;
|
|
subscription: boolean;
|
|
}
|
|
|
|
const API_BASE = import.meta.env.PUBLIC_API_URL;
|
|
export const AUTH_TOKEN_KEY = 'authToken'
|
|
|
|
class BlauwasserAPI {
|
|
private async fetchAPI<T>(
|
|
endpoint: string,
|
|
options: RequestInit = {}
|
|
): Promise<T> {
|
|
const url = new URL(endpoint, API_BASE);
|
|
const defaultHeaders: HeadersInit = {
|
|
'Content-Type': 'application/json',
|
|
};
|
|
|
|
if (typeof window !== 'undefined') {
|
|
const jwt = localStorage.getItem(AUTH_TOKEN_KEY);
|
|
if (jwt) {
|
|
defaultHeaders['Authorization'] = `Bearer ${jwt}`;
|
|
}
|
|
}
|
|
|
|
const response = await fetch(url, {
|
|
...options,
|
|
headers: { ...defaultHeaders, ...options.headers },
|
|
});
|
|
|
|
if (!response.ok) {
|
|
throw new Error(`API Error ${response.status}: ${response.statusText}`);
|
|
}
|
|
|
|
return response.json();
|
|
}
|
|
|
|
async getUserInfo(): Promise<User> {
|
|
return this.fetchAPI(`/users/me`);
|
|
}
|
|
|
|
async register(user: User): Promise<void> {
|
|
return this.fetchAPI(`/users`, {
|
|
method: 'POST',
|
|
body: JSON.stringify(user)
|
|
})
|
|
}
|
|
|
|
async login(userCode: string): Promise<string> {
|
|
const formData = new URLSearchParams();
|
|
formData.append('user_code', userCode);
|
|
|
|
return await this.fetchAPI('/users/login', {
|
|
method: 'POST',
|
|
headers: {
|
|
'Content-Type': 'application/x-www-form-urlencoded',
|
|
},
|
|
body: formData,
|
|
});
|
|
}
|
|
|
|
async toggleSubscription(subscription: boolean): Promise<void> {
|
|
const formData = new URLSearchParams();
|
|
formData.append('subscription', JSON.stringify(subscription));
|
|
|
|
return await this.fetchAPI('/users/me/subscription', {
|
|
method: 'PUT',
|
|
headers: {
|
|
'Content-Type': 'application/x-www-form-urlencoded',
|
|
},
|
|
body: formData,
|
|
});
|
|
}
|
|
|
|
async deleteUser(): Promise<void> {
|
|
return await this.fetchAPI('/users/me', {
|
|
method: "DELETE"
|
|
})
|
|
}
|
|
|
|
async approveNewsletter(secret: string): Promise<void> {
|
|
const formData = new URLSearchParams();
|
|
formData.append('secret', JSON.stringify(secret));
|
|
|
|
return await this.fetchAPI('/newsletter/approve', {
|
|
method: 'POST',
|
|
body: formData
|
|
})
|
|
}
|
|
}
|
|
|
|
|
|
export const api = new BlauwasserAPI();
|