简化RN应用的RESTful调用 - react-native-rest-client

2016-11-29      46      JavaScript
项目简介

React Native REST Client

简化React Native应用的RESTful调用。

安装

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

简单使用方法

通过扩展RestClient类创建你自己的api客户端。

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);
  }
};

然后你可以使用你的自定义客户端:

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

高级使用方式

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 });
  }
};