Giter VIP home page Giter VIP logo

axios-endpoints's Introduction

Axios endpoints

Build Status npm

Axios endpoints helps you to create a more concise endpoint mapping with a simple but flexible api. It is as wrapper over axios.

Getting started

Before anything, install axios-endpoints

npm install --save axios #axios is a peer dependency
npm install --save axios-endpoints

Usage with Factory (recommended)

For a more complete usage of axios settings, you may use the Factory.

import axios from "axios";
import EndpointFactory from "axios-endpoints";

const axiosInstance = axios.create({
    baseURL: "https://localhost:8080/api"
});

const Endpoint = EndpointFactory(axiosInstance);

const cityEndpoint = new Endpoint("/city"); // GET https://localhost:8080/api/city
const postEndpoint = new Endpoint(({id = ""}) => "/post/" + id);

// Header changing example
function setAuthorization(MYTOKEN){
  axiosInstance.defaults.headers.common["Authorization"] = MYTOKEN;
}



function getCityList(callback) {
   cityEndpoint.get().then(response=>{
      callback(response.data);
   }).catch(e=>{
      console.log("That didnt go well");
   });
}

// do you like async stuff? so take this async example
async function getCityList(){
   try{
      const { data } = await cityEndpoint.get();
      return data;
   } catch (e) {
      console.log("That didnt go well");
   }
}

Usage without factory

The fastest way to use axios-endpoints. ideal when you dont want to set any axios configs:

// endpoints.js
import { Endpoint } from "axios-endpoints";

export const userEndpoint = new Endpoint("https://localhost:8080/api/user");


// anotherfile.js
import { userEndpoint } from "./endpoints";

async function getUserList(){
   try{
      const { data } = await userEndpoint.get();
      return data;
   } catch (e) {
      console.log("That didnt go well");
   }
}

HTTP methods

You can user either .get .post .put and .delete as well:

const cityEndpoint = new Endpoint("/city");

const { data } = await cityEndpoint.get(); // GET https://localhost:8080/api/city
const { data } = await cityEndpoint.get({
    params: {country:"brazil"}
}); // GET https://localhost:8080/api/city?country=brazil


const { data } = await cityEndpoint.post({
   name: "Hortolandia", 
   country: "Brazil", 
   hazardLevel: 10000
}, {
  params: { someParam: "icecream" }
}); 
/*
curl --request POST \  
  --url https://localhost:8080/api/city?someParam=icecream \
  --header 'Content-Type: application/json' \
  --data '{
   "name": "Hortolandia", 
   "country": "Brazil", 
   "hazardLevel": 10000
  }'
*/

uriParams

Not always your endpoint will be represented by a fixed string. For that, uri params exists.

const postEndpoint = new Endpoint(({postId = ""}) => "/post/" + postId)

const { data } = await postEndpoint.get({
   uriParams: {
      postId: 1
   }
}); // GET https://localhost:8080/api/post/1

For more information about parameters and returned values, check the API section.

API

EndpointFactory

import axios from "axios";
import EndpointFactory from "axios-endpoints"

const axiosInstance = axios.create(config);
const Enpoint = EndpointFactory(axiosInstance);

Type: function

Parameters
axiosInstance Axios instance

axiosInstance is generated via axios.create function. For more information, check axios documentation.

Return: Endpoint

Endpoint

import axios from "axios";
import EndpointFactory from "axios-endpoints"

const axiosInstance = axios.create(config);
const Enpoint = EndpointFactory(axiosInstance);

Type: class

Constructor
Constructor Parameters Type
endpointIdentifier String or Function any => String
Instance methods
endpoint#get(options)
endpoint#post(payload, options)
endpoint#put(payload, options)
endpoint#patch(payload, options)
endpoint#delete(options)
Parameters Type
options The same object as the Request Config with the extra property uriParams.
You may use params and uriParams more often.
payload The object that will be carried as json payload of the request

Contributing

If you got so far reading this README, you are maybe thinking about contributing. Pull requests are welcome.

axios-endpoints's People

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Forkers

shannonrdunn

axios-endpoints's Issues

Scope error

Cannot use in projects using web pack 4.x:

Error:

index.js:1452 TypeError: Cannot read property 'uri' of undefined
    at get (index.js:123)
    at _callee$ (loginActions.js:9)
    at tryCatch (runtime.js:62)
    at Generator.invoke [as _invoke] (runtime.js:288)
    at Generator.prototype.(:3000/anonymous function) [as next] (http://localhost:3000/static/js/0.chunk.js:578:21)
    at asyncGeneratorStep (asyncToGenerator.js:3)
    at _next (asyncToGenerator.js:25)
    at asyncToGenerator.js:32
    at new Promise (<anonymous>)
    at asyncToGenerator.js:21
    at _ValidatePhone (loginActions.js:9)
    at ValidatePhone (loginActions.js:9)
    at _callee$ (LoginContext.js:29)
    at tryCatch (runtime.js:62)
    at Generator.invoke [as _invoke] (runtime.js:288)
    at Generator.prototype.(:3000/anonymous function) [as next] (http://localhost:3000/static/js/0.chunk.js:578:21)
    at asyncGeneratorStep (asyncToGenerator.js:3)
    at _next (asyncToGenerator.js:25)
    at asyncToGenerator.js:32
    at new Promise (<anonymous>)
    at asyncToGenerator.js:21
    at LoginContext.js:21
    at _callee$ (InsertPhone.js:30)
    at tryCatch (runtime.js:62)
    at Generator.invoke [as _invoke] (runtime.js:288)
    at Generator.prototype.(:3000/anonymous function) [as next] (http://localhost:3000/static/js/0.chunk.js:578:21)
    at asyncGeneratorStep (asyncToGenerator.js:3)
    at _next (asyncToGenerator.js:25)
    at asyncToGenerator.js:32
    at new Promise (<anonymous>)
    at asyncToGenerator.js:21
    at InsertPhone.js:31
    at HTMLUnknownElement.callCallback (react-dom.development.js:144)
    at Object.invokeGuardedCallbackDev (react-dom.development.js:193)
    at invokeGuardedCallback (react-dom.development.js:243)
    at invokeGuardedCallbackAndCatchFirstError (react-dom.development.js:258)
    at executeDispatch (react-dom.development.js:615)
    at executeDispatchesInOrder (react-dom.development.js:640)
    at executeDispatchesAndRelease (react-dom.development.js:740)
    at executeDispatchesAndReleaseTopLevel (react-dom.development.js:753)
    at forEachAccumulated (react-dom.development.js:720)
    at runEventsInBatch (react-dom.development.js:896)
    at runExtractedEventsInBatch (react-dom.development.js:906)
    at handleTopLevel (react-dom.development.js:5074)
    at batchedUpdates$1 (react-dom.development.js:18374)
    at batchedUpdates (react-dom.development.js:2299)
    at dispatchEvent (react-dom.development.js:5154)
    at interactiveUpdates$1 (react-dom.development.js:18436)
    at interactiveUpdates (react-dom.development.js:2320)
    at dispatchInteractiveEvent (react-dom.development.js:5130)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.