apiMethods.js 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. const API_BASE = "http://localhost:5000";
  2. export const getStatus = async () => {
  3. try {
  4. const res = await fetch(API_BASE);
  5. if (!res.ok) {
  6. throw Error(res.statusText);
  7. }
  8. return await res.json();
  9. } catch (err) {
  10. return {status: err.message, version: null}
  11. }
  12. }
  13. export const createGame = async (timer) => {
  14. const res = await fetch(`${API_BASE}/game`, {
  15. method: "PUT",
  16. headers: {
  17. "Content-Type": "application/json",
  18. },
  19. body: JSON.stringify({ timer }),
  20. });
  21. if (!res.ok) {
  22. throw Error(res.statusText);
  23. }
  24. const { gameId } = await res.json();
  25. return gameId;
  26. }
  27. export const gameInfo = async (gameId) => {
  28. const res = await fetch(`${API_BASE}/game/${gameId}`);
  29. if (!res.ok) {
  30. throw Error(res.statusText);
  31. }
  32. return await res.json();
  33. }
  34. export const joinGame = async (gameId, playerName) => {
  35. const res = await fetch(`${API_BASE}/game/${gameId}/join`, {
  36. method: "POST",
  37. headers: {
  38. "Content-Type": "application/json",
  39. },
  40. body: JSON.stringify({ playerName }),
  41. });
  42. if (!res.ok) {
  43. throw Error(res.statusText);
  44. }
  45. return await res.json();
  46. }
  47. export const getCurrentRound = async (gameId, playerId) => {
  48. const res = await fetch(`${API_BASE}/game/${gameId}/current`, {
  49. headers: {
  50. "Authorization": `Player ${playerId}`
  51. },
  52. });
  53. if (!res.ok) {
  54. throw Error(res.statusText);
  55. }
  56. return await res.json();
  57. }
  58. export const sendGuess = async (gameId, playerId, round, point) => {
  59. const res = await fetch(`${API_BASE}/game/${gameId}/guesses/${round}`, {
  60. method: "POST",
  61. headers: {
  62. "Authorization": `Player ${playerId}`,
  63. "Content-Type": "application/json",
  64. },
  65. body: JSON.stringify(point),
  66. });
  67. if (!res.ok) {
  68. throw Error(res.statusText);
  69. }
  70. return await res.json();
  71. }