refactoring: server actions data fetching -> api routes
This commit is contained in:
1 parent
1111712d2c
commit
5cbf93b3b8
38 files changed
+326
-308
No files matched your search
@@ -0,0 +1,88 @@
|
||||
type Search = Record<string, string | number | boolean | null | undefined>;
|
||||
|
||||
class Http {
|
||||
constructor(
|
||||
private base: string,
|
||||
private authorization?: string
|
||||
) {}
|
||||
|
||||
private async request<T, B = unknown>({
|
||||
method,
|
||||
url,
|
||||
base = this.base,
|
||||
search,
|
||||
body,
|
||||
preventCache = true
|
||||
}: {
|
||||
method: 'GET' | 'POST';
|
||||
url: string;
|
||||
base?: string;
|
||||
search?: Search;
|
||||
body?: B;
|
||||
preventCache?: boolean;
|
||||
}): Promise<T> {
|
||||
const serializedParams = new URLSearchParams(
|
||||
Object.entries(search ?? {}).reduce((params, [key, value]) => {
|
||||
if (value != null && value !== '') {
|
||||
params.set(key, String(value));
|
||||
}
|
||||
return params;
|
||||
}, new URLSearchParams())
|
||||
);
|
||||
|
||||
try {
|
||||
const response = await fetch(`${base}${url}?${serializedParams}`, {
|
||||
method,
|
||||
headers: {
|
||||
Authorization: this.authorization || '',
|
||||
'Content-Type': 'application/json'
|
||||
},
|
||||
body: body ? JSON.stringify(body) : undefined,
|
||||
next: preventCache ? undefined : { revalidate: 3600 }
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
return Promise.reject({
|
||||
status: response.status,
|
||||
statusText: response.statusText
|
||||
});
|
||||
}
|
||||
|
||||
return response.json();
|
||||
} catch (error) {
|
||||
return Promise.reject({ message: 'Network or parsing error', error });
|
||||
}
|
||||
}
|
||||
|
||||
get<T>(
|
||||
url: string,
|
||||
{ params, preventCache }: { params?: Search; preventCache?: boolean } = {},
|
||||
base?: string
|
||||
): Promise<T> {
|
||||
return this.request<T>({
|
||||
url,
|
||||
method: 'GET',
|
||||
search: params,
|
||||
preventCache,
|
||||
base
|
||||
});
|
||||
}
|
||||
|
||||
post<T, B = unknown>(
|
||||
url: string,
|
||||
{ params, preventCache }: { params?: Search; preventCache?: boolean } = {},
|
||||
body?: B,
|
||||
base?: string
|
||||
): Promise<T> {
|
||||
return this.request<T>({
|
||||
url,
|
||||
method: 'POST',
|
||||
search: params,
|
||||
body,
|
||||
base,
|
||||
preventCache
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
export default Http;
|
||||
@@ -0,0 +1,5 @@
|
||||
import Http from './Http';
|
||||
|
||||
const movieAdvisor = new Http('http://localhost:3000/api/tmdb');
|
||||
|
||||
export default movieAdvisor;
|
||||
@@ -0,0 +1,5 @@
|
||||
import Http from './Http';
|
||||
|
||||
const theMovieDb = new Http('https://api.themoviedb.org/3', `Bearer ${process.env.MOVIE_DB_TOKEN}`);
|
||||
|
||||
export default theMovieDb;
|
||||
Reference in new issue
Block a user