Skip to content

bouchal/node-async-json-request

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

17 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Simple sending JSON requests via async/await or promises.

Async JSON Request

Coverage Status

Installation

npm i async-json-request --save

Usage

Basic request sending

import JsonRequest from 'async-json-request';

const apiRequest = new JsonRequest('https://jsonplaceholder.typicode.com');

const printData = async () => {
	const result = await apiRequest.get('/posts/1');
	
	console.log(result.body);
};

printData();

Methods

  • .get(URI, PARAMETERS)
  • .post(URI, PARAMETERS, BODY)
  • .put(URI, PARAMETERS, BODY)
  • ...and every other possible methods

Custom default request options

import JsonRequest from 'async-json-request';

const apiRequest = new JsonRequest('https://jsonplaceholder.typicode.com', {
	headers: {
		'x-token': 'TOKEN'
	}
});

Custom additional options for specific request

import JsonRequest from 'async-json-request';

const apiRequest = new JsonRequest('https://jsonplaceholder.typicode.com', {
	headers: {
		'x-token': 'TOKEN'
	}
});

const result = apiRequest
    .wrap({
        headers: {
            'authorization': 'Bearer XYZ'
        }
    })
    .get('/posts/1');

All options are deep merged together.

Typescript

If you know schema which return in body, you can use generic types for better suggestions.

import JsonRequest from 'async-json-request';

interface IPost {
    userId: number;
    id: number;
    title: string;
    body: string;
}

const apiRequest = new JsonRequest('https://jsonplaceholder.typicode.com');

const printFirstPostTitle = async (): Promise<void> => {
    const response = await apiRequest.get<IPost>('/posts/1');

    const responseBody = response.body; // Now body will be suggest you IPost interface.
    
    console.log(`Title of first post is: ${responseBody.title}`);
}

printFirstPostTitle();

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published