1.0.5-beta • Published 9 months ago

round12-http-client v1.0.5-beta

Weekly downloads
-
License
ISC
Repository
github
Last release
9 months ago

Introduction

Minimal API around the fetch native function, allowing you to quickly make outgoing HTTP requests to communicate with your API. It is focused on its most common use cases and a wonderful developer experience.

Examples

Setting up your a custom http client

import httpClient from 'round12-http-client';

const http = (path, id) => httpClient({
  baseUrl: 'https://my-api.com',
  headers: {
    'Content-type': 'application/json'
  },
}).resource(path, id);e

// Simple GET request passing query parameters
http('users').query({ limit: 10, page: 1 }).get();

Request examples

Simple GET request with query parameters

// Simple GET request passing query parameters
http('users').query({ limit: 10, page: 1 }).get()
  .then((response) => {
    // ...someting magic happens
  })
  .catch((error) => {
    // ...error handling
  });

Make a cancellable request

requesting?.cancel() // Cancel the previous running request, if it exists.
const requesting = http('users').cancellable()
const response = await requesting.get();

Setting The Resource's Path

The very first input that the wrapper needs is the path. Under the hood, this will be appended to the base URL in order to conform the entire URL to the resource that you want to aim to:

http('users');

Let's supose your path is not so simply. We know that that is te most common scenario, Hence, since the Zamba SDK's wrapper aims to make the developer experience delightfull, there are several ways you can set the path URL:

const userId = '641357cadc42b45fe7051fd4';
const roleId = '640a42ef609403f6fc0c2e5b';

http(`users/${userId}/roles/${roleId}`);

But if you don't like the interpolation:

const userId = '641357cadc42b45fe7051fd4';
const roleId = '640a42ef609403f6fc0c2e5b';

http('users.roles', [userId, roleId]);

The wrapper is smart enough to figure out how to compose the URL with the given parameters.

Query Parameters

The wrapper follows the builder pattern, which ables developers to set the request configuration throw their methods. For the case that you want to add Query Parameters, you may use the query method:

http('users').query({
  limit: 10,
  page: 1,
  orderBy: 'name',
  direction: 'desc',
  // ...
});

You may also pass nested perameters (up to just one level). This is useful when you need to conform a url with different types of values for the same query parameter; i.e: ?page[number]=1&page[size]=10

http('users').query({
  page: { number: 1, size: 10 },
  orderBy: 'name',
  direction: 'desc',
  // ...
});

If you prefer, you may set the query parameters using the URLSearchParams object of Javascript:

const params = new URLSearchParams();
params.append('limit', 10);
params.append('page', 1);

http('users').query(params);

Modelize Responses

Sometimes our API doesn't return the JSON response as we expect. For that cases is very common to "transform" the data using a model. The model method of the wrapper helps devolpers to make it elegant:

class User {
  constructor(props = {}) {
    this.id = props._id;
    this.lastName = props.last_name;
    this.email = props.user_email;
  }
}

http('users').model(User);

Making Cancellable Requests

An awesome feature of the wrapper is their cancellable method. Sometimes we need to abort a request to perform another action gaining performance and a rapid response of the UI and making better the User Experience. The cancellable method returns a cancel function that may be called from wherever you want in the code to cancel the request.

const req = http('users').cancellable();

req.cancel();

CRUD Methods

The HTTP wrapper has several methods to make requests data through actions that implements the GET, POST, PUT, PATCH and DELETE HTTP verbs making your sentences cleaner and simple to read.

Getting Collections

The get method make a HTTP request using through the GET and returns an Axios Response.

const response = await http('users').get();

Getting A Specific Key Of The Response

const response = await http('users').get('data');

Getting The First Item of Data Collection

const response = await http('users').get('data.0');

// Or you may prefer the cool way:
const response = await http('users').first('data');

Getting The Last Item of Data Collection

const response = await http('users').last('data');

Post Request

Send a request using the POST method with body object representing the data of the new resource:

const body = {
  name: 'Bruce',
  lastname: 'Wayne',
  superpower: 'Multimillionaire',
};

http('users').post(body);

Put Request

Send a request using the PUT method with a body object:

const userId = '641357cadc42b45fe7051fd4';

http('users', userId).put(body);

Patching An Item

Send a request using the PATCH method with a body object:

const userId = '641357cadc42b45fe7051fd4';

http('users', userId).patch(body);

Deleting An Item

Send a request using the DELETE method:

const userId = '641357cadc42b45fe7051fd4';

http('users', userId).delete();

Something About The HTTP Methods

You might wonder what's the difference between update and patch methods. It's releated to the methods that they implement under the hood. While the update method use PUT, the patch method use PATCH.

PUT and PATCH are both HTTP methods used to update resources on the web. However, they differ in the way they update the resources.

PUT method

The PUT method is used to update an entire resource on the web. When you use the PUT method, you replace the entire resource with the new representation of the resource.

Example: If you have a resource with the URI "/users/123" and you use the PUT method to update it, you would send a request with the new representation of the resource to the server. The server would then replace the existing resource with the new representation.

PATCH method

The PATCH method is used to update a part of a resource on the web. When you use the PATCH method, you only send the changes that need to be made to the resource, rather than sending the entire new representation of the resource. If the resource doesn't exist, the PATCH method should return an error.

Example: If you have a resource with the URI "/users/123" and you use the PATCH method to update it, you would send a request with only the changes that need to be made to the server. The server would then apply the changes to the existing resource.

In summary, the main difference between PUT and PATCH is that PUT replaces the entire resource, while PATCH only updates a part of it.

1.0.5-beta

9 months ago

1.0.4-beta

9 months ago

1.0.3-beta

10 months ago

1.0.2-beta

10 months ago

1.0.1

10 months ago

1.0.0

10 months ago