rest
This commit is contained in:
parent
7cacd41326
commit
5ecf7c5b65
116
src/rest-api/axios.ts
Normal file
116
src/rest-api/axios.ts
Normal file
@ -0,0 +1,116 @@
|
||||
import axios from 'npm:axios';
|
||||
import { ApiError, NetworkError } from './errors.ts';
|
||||
|
||||
interface Post {
|
||||
id: number;
|
||||
title: string;
|
||||
body: string;
|
||||
userId: number;
|
||||
}
|
||||
|
||||
interface User {
|
||||
id: number;
|
||||
username: string;
|
||||
email: string;
|
||||
}
|
||||
|
||||
const apiClient = axios.create({
|
||||
baseURL: 'https://dummyjson.com',
|
||||
timeout: 2000,
|
||||
});
|
||||
|
||||
apiClient.interceptors.response.use(
|
||||
(response) => {
|
||||
console.log('Interceptors response: ', response.data);
|
||||
|
||||
response.data['timestamp'] = new Date();
|
||||
delete response.data['title'];
|
||||
|
||||
return response;
|
||||
},
|
||||
(error) => {
|
||||
if (axios.isAxiosError(error)) {
|
||||
console.error(
|
||||
'Interceptors: Fehler ',
|
||||
error.response?.status,
|
||||
error.message
|
||||
);
|
||||
} else {
|
||||
console.error('Unbekannter Fehler', error);
|
||||
}
|
||||
|
||||
return Promise.reject(error);
|
||||
}
|
||||
);
|
||||
|
||||
async function fetchData<T>(endpoint: string): Promise<T> {
|
||||
try {
|
||||
const response = await apiClient.get<T>(endpoint);
|
||||
return response.data;
|
||||
} catch (error) {
|
||||
if (axios.isAxiosError(error)) {
|
||||
throw new ApiError(error.response?.status ?? 500, error.message);
|
||||
}
|
||||
|
||||
throw new NetworkError(
|
||||
'Netzwerkfehler: ' +
|
||||
(error instanceof Error ? error.message : 'Unbekannt')
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
async function fetchPost(): Promise<void> {
|
||||
try {
|
||||
const post = await fetchData<Post>('/posts/1');
|
||||
console.log('Empfangene Daten', post.title);
|
||||
} catch (error) {
|
||||
console.log('Fehler beim Abrufen der Daten: ', error);
|
||||
}
|
||||
}
|
||||
|
||||
fetchPost();
|
||||
|
||||
async function createPost(): Promise<void> {
|
||||
const payload: Omit<Post, 'id'> = {
|
||||
title: 'TypeScript mit Axios',
|
||||
body: 'Dies ist ein Testpost',
|
||||
userId: 1,
|
||||
};
|
||||
|
||||
try {
|
||||
const response = await apiClient.post('/posts/add', payload);
|
||||
console.log('Erstellter Post', response.data);
|
||||
} catch (error) {
|
||||
console.log('Fehler beim Erstellen des Posts: ', error);
|
||||
}
|
||||
}
|
||||
|
||||
createPost();
|
||||
|
||||
async function fetchWithRetry<T>(
|
||||
endpoint: string,
|
||||
retries = 3,
|
||||
delay = 1000
|
||||
): Promise<T | null> {
|
||||
for (let attempt = 1; attempt <= retries; attempt++) {
|
||||
try {
|
||||
return await fetchData<T>(endpoint);
|
||||
} catch (error) {
|
||||
if (attempt < retries) {
|
||||
await new Promise((resolve) => setTimeout(resolve, delay));
|
||||
delay *= 2;
|
||||
} else {
|
||||
console.error(
|
||||
'API endgültig fehlgeschlagen nach ',
|
||||
retries,
|
||||
'Versuchen: ',
|
||||
error
|
||||
);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
fetchWithRetry('/users/1?delay=5000');
|
||||
15
src/rest-api/errors.ts
Normal file
15
src/rest-api/errors.ts
Normal file
@ -0,0 +1,15 @@
|
||||
export class ApiError extends Error {
|
||||
constructor(public status: number, message: string) {
|
||||
super(message);
|
||||
this.name = 'ApiError';
|
||||
}
|
||||
}
|
||||
|
||||
export class NetworkError extends Error {
|
||||
public status = 510;
|
||||
|
||||
constructor(message: string) {
|
||||
super(message);
|
||||
this.name = 'NetworkError';
|
||||
}
|
||||
}
|
||||
87
src/rest-api/senden-empfangen.ts
Normal file
87
src/rest-api/senden-empfangen.ts
Normal file
@ -0,0 +1,87 @@
|
||||
async function fetchData() {
|
||||
try {
|
||||
const response = await fetch('https://dummyjson.com/posts/1aaa');
|
||||
if (!response.ok) {
|
||||
throw new Error('Http-Fehler! Status: ' + response.status);
|
||||
}
|
||||
console.log(await response.json());
|
||||
} catch (error) {
|
||||
console.log('Fehler beim Aufrufen der Daten: ', error);
|
||||
}
|
||||
}
|
||||
|
||||
fetchData();
|
||||
|
||||
async function sendData() {
|
||||
const payload = {
|
||||
title: 'TypeScript REST',
|
||||
userId: 1,
|
||||
body: 'Dies ist ein Beispiel Post',
|
||||
};
|
||||
|
||||
try {
|
||||
const response = await fetch('https://dummyjson.com/posts/add', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify(payload),
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error('Http-Fehler! Status: ' + response.status);
|
||||
}
|
||||
|
||||
const data = await response.json();
|
||||
console.log('Antwort der API: ', data);
|
||||
} catch (error) {
|
||||
console.error('Fehler beim Senden der Daten: ', error);
|
||||
}
|
||||
}
|
||||
|
||||
sendData();
|
||||
|
||||
async function fetchWithParams(username: string) {
|
||||
try {
|
||||
const response = await fetch(
|
||||
`https://dummyjson.com/users/search?q=${username}`
|
||||
);
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error('Http-Fehler! Status: ' + response.status);
|
||||
}
|
||||
console.log(await response.json());
|
||||
} catch (error) {
|
||||
console.log('Fehler beim Aufrufen der Daten: ', error);
|
||||
}
|
||||
}
|
||||
|
||||
fetchWithParams('John');
|
||||
|
||||
async function fetchDataWithTimeout() {
|
||||
const controller = new AbortController();
|
||||
const timeoutId = setTimeout(() => controller.abort(), 3000);
|
||||
|
||||
try {
|
||||
const response = await fetch('https://dummyjson.com/users/1?delay=5000', {
|
||||
signal: controller.signal,
|
||||
});
|
||||
|
||||
clearTimeout(timeoutId);
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error('Http-Fehler! Status: ' + response.status);
|
||||
}
|
||||
|
||||
console.log(await response.json());
|
||||
} catch (error: unknown) {
|
||||
console.log(error);
|
||||
if ((error as Error)?.name === 'AbortError') {
|
||||
console.log('Anfrage abgebrochen wegen Timeout');
|
||||
} else {
|
||||
console.log('Fehler beim Aufrufen der Daten: ', error);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fetchDataWithTimeout();
|
||||
Loading…
x
Reference in New Issue
Block a user