1.1.3 • Published 13 days ago

@etsoo/restclient v1.1.3

Weekly downloads
-
License
MIT
Repository
github
Last release
13 days ago

@etsoo/restclient

TypeScript promise based HTTP/REST API client. Unified axios and fetch usage.

ESLint + AirbnbBase + Prettier, Jest(ts-jest) applied, supports CommonJs and ESM. About how to build a NPM package and CI/CD with Github action: https://dev.to/garryxiao/build-a-react-components-npm-package-and-ci-cd-with-github-action-1jm6

Includes FetchLikeApi for extension quickly:

/**
 * Fetch API
 */
export class FetchApi extends FetchLikeApi<Response> {
    constructor() {
        super(fetch);
    }
}

// Under Node
// install node-fetch (https://github.com/node-fetch/node-fetch) first, and @types/node-fetch with TypeScript
const { FetchLikeApi } = require("@etsoo/restclient");
const fetch, { Response } = require("node-fetch");
class FetchApi extends FetchLikeApi<Response> {
  constructor() {
    super(fetch);
  }
}

Installing

Using npm:

$ npm install @etsoo/restclient

Using yarn:

$ yarn add @etsoo/restclient

Example

Initialization

  • Depending on the envioronment, fetch first, then use axios.
  • Under node, supports node-fetch.
import { createClient } from '@etsoo/restclient';
const client = createClient();

// Or
import { createClientAsync } from '@etsoo/restclient';
const client = await createClientAsync();
  • Depending on your decision.
import { FetchApi } from '@etsoo/restclient';
const client = new FetchApi();

// Or
import { AxiosApi } from '@etsoo/restclient';
const client = new AxiosApi();

Calls

// Customer data structure
interface Customer {
    id: string,
    name: string
}

// API client
const client = createClient();

// Authorization, JWT
client.authorize(ApiAuthorizationScheme.Bearer, '*** JWT token ***');

// Read customer list with asyc/await ES6+ style
const customers = await client.get<Customer[]>('/api/customer');
// or with traditional callback way
client.get<Customer[]>('/api/customer').then(customers => {
});

// Read one customer
const customer = await client.get<Customer>('/api/customer/1');
if(customer == null) {
    // Error found
    return;
}
console.log(customer.name);

Error handling

// API client
const client = createClient();

// Global error handling
client.onError = (error) => {
    console.log(error);
}

// Read one customer
var payload: IApiPayload<Customer, any> = {
    // Current call's error handling
    onError = (error) => {
        console.log(error);
        // return false to prevent further error handling
        return false;
    },
    // Pass default value to distinguish return value with error or undefined
    defaultValue: {}
}

const customer = await client.get<Customer>('/api/customer/1', undefined, payload);
if(customer == null) {
    // Error found
    // client.lastError cache the last error
    // For accurate check, validate client.lastError.data.url
    return;
}

// Now call payload.response to access headers
// client.transformResponse(payload.response) to get a standard IApiResponse

Properties

NameDescription
baseUrlAPI base URL, add to the API root of all calls
charsetCharset for sending data, default is 'utf-8'
configSee axios/Request Config or fetch/RequestInit
defaultResponseTypeDefault type is JSON
jsonContentTypeJSON content type string, 'application/json'
lastErrorLast error for track
onErrorError occured callback
onRequestBefore request callback
onCompleteAfter request completed but before onResponse
onResponseAfter response callback

Methods

Provides delete, get, head, options, patch, post, put syntactic sugar for request method. Return with undefined means error found. If the API return nothing with success, a empty object {} will be returned to distingush the error case. Define a onError callback function at payload only for the call or client's property onError for global error handling.

    /**
     * Authorize the call
     * https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Authorization
     * @param scheme Scheme
     * @param token Token, empty/null/undefined to remove it
     * @param writeHeaders Headers to write authtication, default to all calls
     */
    authorize(
        scheme: ApiAuthorizationScheme | string,
        token: string | undefined,
        writeHeaders?: HeadersInit
    ): void;

    /**
     * Detect IP data
     * @returns IP data
     */
    detectIP(): Promise<IPData | undefined>;

    /**
     * Get HTTP content dispostion
     * @param responseOrValue Response or header value
     * @returns Result
     */
    getContentDisposition(response: R): ContentDisposition | undefined;
    getContentDisposition(header: string): ContentDisposition | undefined;

    /**
     * Get content length
     * @param headers Headers
     * @returns
     */
    getContentLength(headers: HeadersAll): number | undefined;

    /**
     * Get content type and charset
     * @param headers Headers
     */
    getContentTypeAndCharset(headers: HeadersInit): [string, string?];

    /**
     * Get content type
     * @param headers Headers
     */
    getHeaderValue(headers: HeadersInit, key: string): string | null;

    /**
     * Get Json data directly
     * @param url URL
     * @returns Json data
     */
    getJson<T = DataTypes.ReadonlyData>(url: string): Promise<T>;

    /**
     * Request to API
     * @param method Method
     * @param url API URL
     * @param data Passed data
     * @param payload Payload
     */
    request<T>(
        method: ApiMethod,
        url: string,
        data?: ApiRequestData,
        payload?: IApiPayload<T, R>
    ): Promise<T | undefined>;

    /**
     * Set content language
     * @param language Content language
     * @param headers Headers, default is global headers
     */
    setContentLanguage(
        language: string | null | undefined,
        headers?: HeadersInit
    ): void;

    /**
     * Set header value
     * @param key Header name
     * @param value Header value
     * @param headers Headers to lookup
     */
    setHeaderValue(
        key: string,
        value: string | null | undefined,
        headers: HeadersInit
    ): void;

    /**
     * Transform the original response to a unified object
     * @param response Original response
     */
    transformResponse(response: R): IApiResponse;

Call Payload

When you call any API, pass additional properties with the payload parameter.

NameDescription
contentTypeSpecify data type to send, like 'application/json'
onErrorCurrent API call error callback
configCurrent API config. See axios/Request Config or fetch/RequestInit
defaultValueDefault value, like [] for array return to distinguish undefined or error return
paramsURL parameters
parserCurrent API response data parser
responseRequest response object
responseTypeSpecify response data type
showLoadingWhether to show loading bar
localLocal URL and ignore baseUrl

License

MIT

1.1.3

13 days ago

1.1.1

2 months ago

1.1.2

2 months ago

1.1.0

2 months ago

1.0.99

2 months ago

1.0.98

3 months ago

1.0.97

3 months ago

1.0.96

3 months ago

1.0.89

10 months ago

1.0.91

7 months ago

1.0.90

8 months ago

1.0.95

6 months ago

1.0.94

6 months ago

1.0.93

7 months ago

1.0.92

7 months ago

1.0.88

1 year ago

1.0.87

1 year ago

1.0.86

1 year ago

1.0.85

1 year ago

1.0.80

1 year ago

1.0.84

1 year ago

1.0.83

1 year ago

1.0.82

1 year ago

1.0.81

1 year ago

1.0.73

2 years ago

1.0.72

2 years ago

1.0.77

2 years ago

1.0.76

2 years ago

1.0.75

2 years ago

1.0.74

2 years ago

1.0.79

1 year ago

1.0.78

2 years ago

1.0.71

2 years ago

1.0.70

2 years ago

1.0.69

2 years ago

1.0.68

2 years ago

1.0.66

2 years ago

1.0.67

2 years ago

1.0.65

2 years ago

1.0.64

2 years ago

1.0.63

2 years ago

1.0.62

3 years ago

1.0.61

3 years ago

1.0.60

3 years ago

1.0.59

3 years ago

1.0.58

3 years ago

1.0.57

3 years ago

1.0.55

3 years ago

1.0.54

3 years ago

1.0.53

3 years ago

1.0.52

3 years ago

1.0.56

3 years ago

1.0.51

3 years ago

1.0.48

3 years ago

1.0.47

3 years ago

1.0.46

3 years ago

1.0.49

3 years ago

1.0.50

3 years ago

1.0.45

3 years ago

1.0.44

3 years ago

1.0.43

3 years ago

1.0.42

3 years ago

1.0.41

3 years ago

1.0.40

3 years ago

1.0.39

3 years ago

1.0.38

3 years ago

1.0.37

3 years ago

1.0.36

3 years ago

1.0.35

3 years ago

1.0.34

3 years ago

1.0.33

3 years ago

1.0.32

3 years ago

1.0.31

3 years ago

1.0.29

3 years ago

1.0.28

3 years ago

1.0.30

3 years ago

1.0.27

3 years ago

1.0.26

3 years ago

1.0.25

4 years ago

1.0.24

4 years ago

1.0.23

4 years ago

1.0.22

4 years ago

1.0.21

4 years ago

1.0.20

4 years ago

1.0.19

4 years ago

1.0.18

4 years ago

1.0.17

4 years ago

1.0.16

4 years ago

1.0.15

4 years ago

1.0.14

4 years ago

1.0.13

4 years ago

1.0.11

4 years ago

1.0.10

4 years ago

1.0.12

4 years ago

1.0.9

4 years ago

1.0.2

4 years ago

1.0.8

4 years ago

1.0.7

4 years ago

1.0.6

4 years ago

1.0.3

4 years ago

1.0.1

4 years ago