Advertisement
magrega

service function

May 28th, 2023 (edited)
956
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import { TStories, TStory } from '../App.types';
  2.  
  3. const _api = 'https://lobster-app-qoium.ondigitalocean.app/story/';
  4. let initialRequest = '?offset=0&limit=15';
  5.  
  6. export const fetchData = async (url: string, method: string = 'GET', body?: string): Promise<any> => {
  7.   try {
  8.     const options: RequestInit = { method, headers: { 'Content-Type': 'application/json' } };
  9.  
  10.     if (body) options.body = body;
  11.  
  12.     const response = await fetch(url, options);
  13.  
  14.     if (!response.ok) throw new Error(`HTTP error! status: ${response.status}`);
  15.  
  16.     return response.json();
  17.   } catch (e) {
  18.     throw new Error(`Error fetching data: ${(e as Error).message}`);
  19.   }
  20. };
  21.  
  22. export const getPosts = async (req: string = initialRequest): Promise<TStories> => {
  23.   try {
  24.     const responseBody = await fetchData(`${_api}${req}`);
  25.     initialRequest = responseBody.next_url.replace('/story/', '');
  26.     return responseBody;
  27.   } catch (e) {
  28.     throw new Error(`Error fetching posts: ${(e as Error).message}`);
  29.   }
  30. };
  31.  
  32. export const getPost = async (id: string): Promise<TStory> => {
  33.   try {
  34.     return fetchData(`${_api}${id}`);
  35.   } catch (e) {
  36.     throw new Error(`Error getting post: ${(e as Error).message}`);
  37.   }
  38. };
  39.  
  40. export const sendPost = async (body: string): Promise<TStory> => {
  41.   try {
  42.     return await fetchData(_api, 'POST', JSON.stringify({ content: body }));
  43.   } catch (e) {
  44.     throw new Error(`Error making a post: ${(e as Error).message}`);
  45.   }
  46. };
  47.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement