httpService.ts 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244
  1. import type { TPaginacion, DefaultResponse } from "../types/responses";
  2. export interface IRequestParams {
  3. expand?: string;
  4. ordenar?: string | "id-desc" | "id-asc";
  5. limite?: number;
  6. pagina?: number;
  7. buscar?: string;
  8. [key: string]: any;
  9. }
  10. export interface IRequest {
  11. req: string;
  12. endpoint: string;
  13. params: any;
  14. body: any;
  15. }
  16. const API_URL = "https://pos.api.turquessacoffee.com/";
  17. export interface IHttpService {
  18. get: <T>(
  19. endpoint: string,
  20. params?: any,
  21. updateQueryParams?: boolean
  22. ) => Promise<DefaultResponse<T>>;
  23. getBlob: (endpoint: string, data: any) => Promise<Blob>;
  24. downloadBlob: (
  25. endpoint: string,
  26. data: any,
  27. fileName: string
  28. ) => Promise<void>;
  29. post: <T>(endpoint: string, body: any) => Promise<DefaultResponse<T>>;
  30. postFormData: (endpoint: string, data: any) => Promise<DefaultResponse<any>>;
  31. delete: <T>(endpoint: string, body: T) => Promise<DefaultResponse<any>>;
  32. put: (endpoint: string, body: any) => Promise<any>;
  33. }
  34. export class HttpService implements IHttpService {
  35. API_URL: string;
  36. constructor(API_URL: string) {
  37. this.API_URL = API_URL;
  38. }
  39. static DEFAULT_HEADERS = () => {
  40. return {
  41. "Content-Type": "application/json",
  42. // Authorization: `Bearer ${localStorage.getItem("token")}`,
  43. };
  44. };
  45. static FILE_HEADERS = () => {
  46. return {
  47. "Content-Type": "multipart/form-data",
  48. // Authorization: `Bearer ${localStorage.getItem("token")}`,
  49. };
  50. };
  51. static DEFAULT_REQUEST_PARAMS = {
  52. limite: 10,
  53. pagina: 1,
  54. ordenar: "id-desc",
  55. };
  56. static DEFAULT_PAGINACION: TPaginacion = {
  57. total: 0,
  58. pagina: 1,
  59. limite: 10,
  60. };
  61. static paramsToQuery = (params: any) => {
  62. return Object.keys(params)
  63. .map(
  64. (key) => encodeURIComponent(key) + "=" + encodeURIComponent(params[key])
  65. )
  66. .join("&");
  67. };
  68. static EMPTY_REQUEST = (): IRequest => ({
  69. req: "",
  70. endpoint: "",
  71. params: null,
  72. body: null,
  73. });
  74. static GET_REQUEST = (endpoint: string, params: any = {}): IRequest => ({
  75. req: "GET",
  76. endpoint,
  77. params,
  78. body: null,
  79. });
  80. static POST_REQUEST = <T = any>(
  81. endpoint: string,
  82. body: T,
  83. params: any = {}
  84. ): IRequest => ({
  85. req: "POST",
  86. endpoint,
  87. params,
  88. body,
  89. });
  90. static DELETE_REQUEST = (endpoint: string, params: any = {}) =>
  91. ({
  92. req: "DELETE",
  93. endpoint: `${endpoint}/eliminar`,
  94. body: {
  95. ...params,
  96. },
  97. } as IRequest);
  98. get = async <T>(
  99. endpoint: string,
  100. params: any = HttpService.DEFAULT_REQUEST_PARAMS,
  101. updateQueryParams: boolean = false
  102. ) => {
  103. const stringParams = params ? HttpService.paramsToQuery(params) : "";
  104. const queryParams = `?${new URLSearchParams(stringParams).toString()}`;
  105. let url = `${this.API_URL}${endpoint}`;
  106. if (queryParams) {
  107. url = `${this.API_URL}${endpoint}${queryParams}`;
  108. if (updateQueryParams && window.location.search !== queryParams) {
  109. //Actualizar los queryparams de la url actual
  110. window.history.pushState(
  111. {},
  112. "",
  113. window.location.pathname + `${queryParams}`
  114. );
  115. }
  116. }
  117. const _response = await fetch(url, {
  118. method: "GET",
  119. headers: HttpService.DEFAULT_HEADERS(),
  120. });
  121. console.log("response", _response);
  122. const response = (await _response.json()) as DefaultResponse<T>;
  123. return {
  124. ...response,
  125. isError: response?.status !== 200 ? true : false,
  126. status: response?.status,
  127. resultado: response?.resultado || response,
  128. } as DefaultResponse<T>;
  129. };
  130. getBlob = async (endpoint: string, data: any) => {
  131. const _response = await fetch(`${this.API_URL}${endpoint}`, {
  132. method: "GET",
  133. headers: HttpService.DEFAULT_HEADERS(),
  134. body: JSON.stringify(data),
  135. });
  136. const response = await _response.blob();
  137. return response;
  138. };
  139. downloadBlob = async (
  140. endpoint: string,
  141. data: any,
  142. fileName: string = "fileName"
  143. ) => {
  144. const _response = await fetch(`${this.API_URL}${endpoint}`, {
  145. method: "GET",
  146. headers: HttpService.DEFAULT_HEADERS(),
  147. body: JSON.stringify(data),
  148. });
  149. const blob = await _response.blob();
  150. const urlBlob = URL.createObjectURL(blob);
  151. const link = document.createElement("a");
  152. link.href = urlBlob;
  153. link.setAttribute("download", fileName);
  154. document.body.appendChild(link);
  155. link.click();
  156. URL.revokeObjectURL(urlBlob);
  157. link.remove();
  158. };
  159. post = async <T>(endpoint: string, body: any) => {
  160. const _response = await fetch(`${this.API_URL}${endpoint}`, {
  161. method: "POST",
  162. headers: HttpService.DEFAULT_HEADERS(),
  163. body: JSON.stringify(body),
  164. });
  165. const status = _response.status;
  166. const response = (await _response.json()) as DefaultResponse<T>;
  167. return {
  168. ...response,
  169. isError: status !== 200 ? true : false,
  170. status: status,
  171. } as DefaultResponse<T>;
  172. };
  173. postFormData = async (endpoint: string, data: any) => {
  174. const _response = await fetch(`${this.API_URL}${endpoint}`, {
  175. method: "POST",
  176. headers: HttpService.FILE_HEADERS(),
  177. body: data,
  178. });
  179. const response = await _response.json;
  180. return {
  181. ...response,
  182. isError: _response?.status !== 200 ? true : false,
  183. status: _response?.status,
  184. } as DefaultResponse<any>;
  185. };
  186. delete = async <T = any>(endpoint: string, body: T) => {
  187. const response = await fetch(`${this.API_URL}${endpoint}`, {
  188. body: JSON.stringify(body),
  189. method: "DELETE",
  190. headers: HttpService.DEFAULT_HEADERS(),
  191. });
  192. const status = response.status;
  193. const responseJson = await response.json();
  194. return {
  195. ...responseJson,
  196. isError: status !== 200 ? true : false,
  197. status: status,
  198. } as DefaultResponse<any>;
  199. };
  200. put = async (endpoint: string, body: any) => {
  201. const response = await fetch(`${this.API_URL}${endpoint}`, {
  202. method: "PUT",
  203. headers: HttpService.DEFAULT_HEADERS(),
  204. body: JSON.stringify(body),
  205. });
  206. return response.json();
  207. };
  208. }
  209. export const http = new HttpService(API_URL);