HTTP Requests in Hapi using Wreck plugin


hapi nodejs Tutorials wreck

Hello! If you are from Ukraine, Belarus, Poland or India and looking for a job in Software Development, please reach me out by email.

Introduction

Wreck is Javascript library from Hapi-ecosystem to use HTTP requests. Basically it’s uses for Hapi.js projects. You can use it to write async/await code, because it’s promise-based library.

Installation

Wreck can be installed using NPM:

npm i wreck

or YARN:

yarn add wreck

Сreating a simple HTTP request

const Wreck = require('wreck');

const example = async function () {
    const res = await Wreck.request('get', 'https://jsonplaceholder.typicode.com/todos/1');
    const body = await Wreck.read(res, {
        json: true
    });
    console.log(body);
};

try {
    example();
} catch (e) {
    console.error(e);
}

The first argument of Wreck.request() it’s the HTTP-method. It supports all popular: GET, POST, PUT, DELETE, default is GET. The second argument - the URI of the requested resource. The third - options object. Also, we can use the next methods to make specified requests:

  • Wreck.get()
  • Wreck.post()
  • Wreck.put()
  • Wreck.delete()
  • Wreck.patch()

Getting JSON

To get JSON using Wreck we can use the json property of options object in .get method. We need to set it to true value:

const { res, payload } = await Wreck.get('https://jsonplaceholder.typicode.com/todos/1', {
        json:true
    })
console.log(payload);

The console will display:

{ userId: 1,
  id: 1,
  title: 'delectus aut autem',
  completed: false }

To make request with query params, you can use the .payload property:

const { res, payload } = await Wreck.get('https://jsonplaceholder.typicode.com/todos/1', {
        payload:'a=1&b=2'
    })
console.log(payload);

The querystring can be generated using the qs module.

Making POST request with payload

We can make POST request with JSON payload in two ways:

const data = JSON.stringify({ a: 1, b: 2 });
const { res, payload } = await Wreck.post('https://jsonplaceholder.typicode.com/todos/1', {
    payload: data
})

or using the request function:

const data = JSON.stringify({ a: 1, b: 2 });
const { res, payload } = await Wreck.request('post', 'https://jsonplaceholder.typicode.com/todos/1', {
    payload: data
})

If your app keeps the Promises-style of code, you can easily use the following:

Wreck.get('https://jsonplaceholder.typicode.com/todos/1', {json: true})
.then(res => console.log(res.payload))
.catch(err => console.log(err));

Setting custom header

The request headers object can be set in options parameter:

const headers = {
    'Content-Type': 'application/json'
};
const { res, payload } = await Wreck.request('get', 'https://jsonplaceholder.typicode.com/todos/1', {
    headers
});

Setting defaults

To make default headers, agents and other request/read objects, we can create a new instance of Wreck using the Wreck.defaults() method.

const wreck = Wreck.defaults({
    agents: {
        http: new Http.Agent({
            maxSockets: 10
        })
    },
    headers: {
        'Content-Type': 'application/json'
    }
});
const { res, payload } = await Wreck.get('https://jsonplaceholder.typicode.com/todos/1');

It’s useful if you need to create multiple HTTP clients with different default data.

Learning Hapi.js? Buy my Hapi.js Handbook🔥

comments powered by Disqus