Skip to content

Wasyto/api-worker

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

31 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation


Browser Support

Chrome Firefox Safari Opera Edge IE
Latest ✔ Latest ✔ Latest ✔ Latest ✔ Latest ✔ 11 ✔

Installing

Package manager

Using npm:

$ npm install api-worker

Using bower:

$ bower install api-worker

Using yarn:

$ yarn add api-worker

Using pnpm:

$ pnpm add api-worker

Once the package is installed, you can import the library using import or require approach:

import { apiWorker } from 'api-worker';

Types

api-worker props:

export enum ApiWorkerMethod {
  GET = 'GET',
  POST = 'POST',
  DELETE = 'DELETE',
  PUT = 'PUT',
  PATCH = 'PATCH',
  PURGE = 'PURGE',
}

export enum ApiWorkerResponse {
  BLOB = 'BLOB',
  JSON = 'JSON',
  ARRAY_BUFFER = 'ARRAY_BUFFER',
  TEXT = 'TEXT',
}

export type ApiWorkerProps = {
  url: string;
  method?: ApiWorkerMethod;
  body?: any;
  headers?: object;
  abortController?: AbortController;
  timeout?: number;
  responseType?: ApiWorkerResponse;
  urlParams?: string;
  onSuccess?: (data: any) => void;
  onError?: (data: any) => void;
};

Example

First declare, yours endpoint in a file. -services.ts

import { apiWorker } from 'api-worker';

// First you need configurate, your endpoint
// services/endpoints.ts

export function getExample({
  onSuccess = (data: any) => {},
  onError = (data: any) => {},
}: {
  onSuccess: (data: any) => void,
  onError: (data: any) => void,
}) {
  apiWorker({
    // Is comming a new feature, for you declare only, your endpoint
    url: 'https://api.github.com/orgs/Wasyto/',
    method: 'GET',
    onSuccess,
    onError,
  });
}
export function setExample({
  body,
  onSuccess = (data: any) => {},
  onError = (data: any) => {},
}: {
  body = {}
  onSuccess: (data: any) => void,
  onError: (data: any) => void,
}) {
  apiWorker({
    // Is comming a new feature, for you declare only, your endpoint
    url: 'https://api.github.com/orgs/Wasyto/',
    method: 'POST',
    body = body,
    onSuccess,
    onError,
  });
}

Second and last step, is you call your function.

import { setExample, getExample } from "./services.ts"
import useEffect from "react"
   
function App(){
 UseEffect(() => {
   setExample({
     body:  {example: 'Wasyto'},
     onSucces: (data) => console.log(data),
     onError: (error) => console.log(error),
   });
   getExample({
     onSucces: (data) => console.log(data),
     onError: (error) => console.log(error),
   });
}, [])  
   return (
      <div className="app"></div>
   )
}