tbest-fetch-client
An opinionated REST API client
Last updated 10 days ago by timbest .
MIT · Repository · Bugs · Original npm · Tarball · package.json
$ cnpm install tbest-fetch-client 
SYNC missed versions from official npm registry.

fetch-client

CircleCI

Example

Configure API

ClientBase.ts

import { FetchClient, getDocumentCsrfToken} from "fetch-client";

class ClientBase extends FetchClient {
  constructor() {
    this.defaultHeaders["X-CSRF-Token"] = getDocumentCsrfToken()
    this.credentials = "omit"
  }
}

export default ClientBase

Define an Endpoint

FooAPIClient.d.ts

Foo {
  bar: string;
}

FooCreateResponse {
  id: string;
}

FoosAPIClient.ts

import ClientBase from "./ClientBase";

class FoosAPIClient extends ClientBase {
  public getUrl(fooId?: string): URL {
    const fooUrl = this.getBaseUrl();

    if (fooId !== undefined) {
      fooId.pathname += `foos/${fooId}`;
    } else {
      fooId.pathname += "foos";
    }

    return fooUrl;
  }

  public async create(foo: Foo) {
    return await this.post(this.getUrl(), foo) as ApiResponse<FooCreateResponse, JsonObject>;
  }

  public async updateBar(fooId: string, bar: string) {
    const url = this.getUrl(fooId);
    return await this.put(url, {
      bar: bar,
    });
  }

  public async destroy(fooId: string) {
    const url = this.getUrl(fooId);
    return await this.delete(url);
  }
}

export default FoosAPIClient

Register Endpoint

RestAPIClient.ts

import FoosAPIClient from "./FoosAPIClient"

class RestAPIClient {
    private static foosClient: FoosAPIClient;

  public static get foos() {
    if (!DashboardApi.foosClient) {
      DashboardApi.foosClient = new FoosAPIClient();
    }
    return DashboardApi.foosClient;
  }
}

export default RestAPIClient

Use API

script.ts

import RestAPIClient from "./RestAPIClient"

async function createFoo(foo: Foo) {
  const response = await RestAPIClient.foos.create(foo);
  if (response.succeeded) {
    alert(`Created foo with id: ${response.payload.id}`)
  } else {
   if (response.responseReceived) {
      const errorJson = await response.responseError.getJson();
      console.error(errorJson);
    } else {
      console.error("Unable to create Foo");
    }
  }
}

createFoo({bar: 1})

Contributing

Setup

yarn add -g rollup

Current Tags

  • 0.1.1                                ...           latest (10 days ago)

3 Versions

  • 0.1.1                                ...           10 days ago
  • 0.1.0                                ...           2 months ago
  • 0.0.2                                ...           2 months ago
Maintainers (1)
Downloads
Today 0
This Week 0
This Month 16
Last Day 0
Last Week 0
Last Month 2
Dependencies (4)
Dev Dependencies (9)
Dependents (0)
None

Copyright 2014 - 2016 © taobao.org |