Code Monkey home page Code Monkey logo

react-native-rest-client's Introduction

React Native REST Client

npm version js-semistandard-style

Simplify the RESTful calls of your React Native app.

Instalation

npm install --save react-native-rest-client

Simple usage

Create your own api client by extending the RestClient class

import RestClient from 'react-native-rest-client';

export default class YourRestApi extends RestClient {
  constructor () {
    // Initialize with your base URL
    super('https://api.myawesomeservice.com');
  }
  // Now you can write your own methods easily
  login (username, password) {
    // Returns a Promise with the response.
    return this.POST('/auth', { username, password });
  }
  getCurrentUser () {
    // If the request is successful, you can return the expected object
    // instead of the whole response.
    return this.GET('/auth')
      .then(response => response.user);
  }
};

Then you can use your custom client like this

const api = new YourRestApi();
api.login('johndoe', 'p4$$w0rd')
  .then(response => response.token)   // Successfully logged in
  .then(token => saveToken(token))    // Remember your credentials
  .catch(err => alert(err.message));  // Catch any error

Advanced usage

import RestClient from 'react-native-rest-client';

export default class YourRestApi extends RestClient {
  constructor (authToken) {
    super('https://api.myawesomeservice.com', {
      headers: {
        // Include as many custom headers as you need
        Authorization: `JWT ${authToken}`
        // Content-Type: application/json
        // and
        // Accept: application/json
        // are added by default
      },
      // Simulate a slow connection on development by adding
      // a 2 second delay before each request.
      devMode: __DEV_,
      simulatedDelay: 2000
    });
  }
  getWeather (date) {
    // Send the url query as an object
    return this.GET('/weather', { date })
      .then(response => response.data);
  }
  checkIn (lat, lon) {
    return this.POST('/checkin', { lat, lon });
  }
};

Reference

super(baseUrl [, options])

You must call the parent constructor as shown in the example above.

Parameter Type Required Default
baseUrl String Yes undefined
options Object No {}

options object

Supports the following values

Key Type Required Default Comments
headers String No {} Headers to be appended to the request. RestApi will always include Content-Type: application/json and Accept: application/json.
devMode Boolean No false When true, it enables the simulatedDelay.
simulatedDelay Number No 0 Useful for simulating a slow connection. Number of milliseconds to wait before making the request. NOTE: It will only take effect if devMode is true.

this.GET(route [, query])

this.POST(route [, body])

this.PUT(route [, body])

this.DELETE(route [, query])

Each one of these methods returns a Promise with the response as the parameter.

Parameter Type Required Default Comments
route String Yes '' Partial route to be appended to the baseUrl
query Object No {} Object to be encoded and appended as the query part to the URL
body Object No {} Data to be sent as the JSON body of the message

Limitations

  • This library only supports JSON request and response bodies. If the response is not a JSON object, it will throw a JSON parse error.
  • It is labeled as React Native, even when it has no RN dependencies and could (in theory) be used in any JavaScript project. The reason behind this is that the stack used (ES6 and fetch) comes out of the box with React Native, and adding support for more platforms would require to add pre-compilers, polyfills and other tricks, which are completely out of the scope of this library. If you know what you're doing though, feel free to tweak your stack and use this library.

License

MIT

react-native-rest-client's People

Contributors

javorosas avatar

Watchers

James Cloos avatar  avatar

Forkers

gentisoft

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.