REST 客户端

ReactXP 提供了基本的网络 API 用于确定网络连接状态,但它没有提供连接后访问网络的方法。

此扩展提供了一个跨平台的机制,用于封装简单的 REST API。它支持可选的重试逻辑(包括指数退避)。

有关更多详细信息,请参阅 SimpleRestClients GitHub 站点。

安装方式:npm install simplerestclientsyarn add simplerestclients

示例用法

import { GenericRestClient, ApiCallOptions }  from 'simplerestclients';
import SyncTasks = require('synctasks');

export interface User {
    id: string;
    firstName: string;
    lastName: string;
}

export default class MyRestClient extends GenericRestClient {
    constructor(private _appId: string) {
        super('https://myhost.com/api/v1/');
    }

    // Override _getHeaders to append a custom header with the app ID.
    protected _getHeaders(options: ApiCallOptions): { [key: string]: string } {
        let headers = super._getHeaders(options);
        headers['X-AppId'] = this._appId;
        return headers;
    }

    // Define public methods that expose the APIs provided through
    // the REST service.
    getAllUsers(): SyncTasks.Promise<User[]> {
        return this.performApiGet<User[]>('users');
    }

    getUserById(id: string): SyncTasks.Promise<User> {
        return this.performApiGet<User>('user/' + id);
    }

    setUser(user: User): SyncTasks.Promise<void> {
        return this.performApiPut<void>('user/' + user.id, user);
    }
}