59 lines
1.7 KiB
TypeScript
59 lines
1.7 KiB
TypeScript
import { InjectionToken } from '@angular/core';
|
|
|
|
import {
|
|
createAngularApiClient,
|
|
type AngularApiClient,
|
|
type AngularHttpClientLike,
|
|
} from '../../../src/api/angular-client';
|
|
|
|
export const WPP_API_CLIENT = new InjectionToken<AngularApiClient>('WPP_API_CLIENT');
|
|
|
|
export interface FetchLike {
|
|
(input: string, init?: RequestInit): Promise<Response>;
|
|
}
|
|
|
|
export function createFetchHttpClient(fetchImpl: FetchLike): AngularHttpClientLike {
|
|
return {
|
|
async get<T>(url: string): Promise<T> {
|
|
const response = await fetchImpl(url, {
|
|
method: 'GET',
|
|
headers: { Accept: 'application/json' },
|
|
credentials: 'same-origin',
|
|
});
|
|
const payload = await response.json().catch(() => ({}));
|
|
if (!response.ok) {
|
|
throw {
|
|
status: response.status,
|
|
message: (payload as { error?: string }).error ?? `HTTP ${response.status}`,
|
|
error: payload,
|
|
};
|
|
}
|
|
return payload as T;
|
|
},
|
|
async post<T>(url: string, body: unknown): Promise<T> {
|
|
const response = await fetchImpl(url, {
|
|
method: 'POST',
|
|
headers: {
|
|
Accept: 'application/json',
|
|
'Content-Type': 'application/json',
|
|
},
|
|
body: JSON.stringify(body),
|
|
credentials: 'same-origin',
|
|
});
|
|
const payload = await response.json().catch(() => ({}));
|
|
if (!response.ok) {
|
|
throw {
|
|
status: response.status,
|
|
message: (payload as { error?: string }).error ?? `HTTP ${response.status}`,
|
|
error: payload,
|
|
};
|
|
}
|
|
return payload as T;
|
|
},
|
|
};
|
|
}
|
|
|
|
export function createWppApiClient(fetchImpl: FetchLike = fetch.bind(globalThis)): AngularApiClient {
|
|
return createAngularApiClient(createFetchHttpClient(fetchImpl));
|
|
}
|