api.ts 638 B

123456789101112131415161718192021222324252627282930313233343536373839
  1. export enum ApiMethods {
  2. GET = "GET",
  3. POST = "POST",
  4. }
  5. export enum ApiPaths {
  6. Login = "login",
  7. }
  8. type FetchApiProps<T> = {
  9. method: ApiMethods;
  10. path: ApiPaths;
  11. body: T;
  12. };
  13. type FetchApiResult = { error?: string; message?: string };
  14. const fetchApi = async <T>({
  15. method,
  16. path,
  17. body,
  18. }: FetchApiProps<T>): Promise<FetchApiResult> => {
  19. const response = await fetch(`/api/${path}`, {
  20. method: method,
  21. body: JSON.stringify(body),
  22. });
  23. const { message } = await response.json();
  24. if (response.ok) {
  25. return { message };
  26. } else {
  27. return {
  28. error: message,
  29. };
  30. }
  31. };
  32. export default fetchApi;