api.ts 659 B

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