api.ts 770 B

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