Logger

https://github.com/hg-pyun/axios-logger

Example convinetence method

const {
    fakeBookCertificate: cert,
    fakeBookKey: key,
    customURLs,
} = sails.config;

const FakeBookService = axios.create({
    baseURL: customURLs.fakeBookBaseUrl,
    headers: {
        'Content-Type': 'application/json; charset=utf-8',
        'api-version': '4',
    },
    httpsAgent: new https.Agent({
        cert,
        key,
        keepAlive: true,
    }),
    paramsSerializer: queryParamObjToStr,
    transformRequest: [addHmacToQueryParam],

		// for doing things if 200!!!
		validateStatus: function (status) {
	    return status >= 200 && status < 300; // default
	  },
});

function addHmacToQueryParam(data, _headers) {
    data = {
        hmac: hmacKey
    };
    return JSON.stringify(data);
}

FakeBookService.interceptors.request.use(addHashToHeader);

function addHashToHeader(config) {
    const queryStr = queryParamObjToStr(config.params);
    const hash = crypto
        .update(Buffer.from(queryStr, 'utf-8'))
        .digest('hex')
        .toUpperCase();

    config.headers.hash = hash;
    return config;
}

Usage

export async function getActiveBooking(eventId: string, user: any): Promise<any> {
	return await http.get(`/event/${eventId}/booking/${user.id}/active`, {
		headers: {
			Authorization: `Bearer ${user.accessToken}`,
		},
		validateStatus: status => {
			return status === 200 || status === 404
		},
	})
}

Custom query param transformation function using URLSearchParams

function queryParamObjToStr(queryParamsObj) {
    const params = new URLSearchParams();

    Object.entries(queryParamsObj).forEach(([key, value]) => {
        if (Array.isArray(value)) {
            for (const val of value) {
                params.append(key, val);
            }
        } else {
            params.append(key, value.toString());
        }
    });

    return params.toString();
}

Stream file

import * as stream from 'stream';
import { promisify } from 'util';

const finished = promisify(stream.finished);

export async function downloadFile(fileUrl: string, outputLocationPath: string): Promise<unknown> {
  const writer = createWriteStream(outputLocationPath);
  return Axios({
    method: 'get',
    url: fileUrl,
    responseType: 'stream',
  }).then(async response => {
    response.data.pipe(writer);
    return finished(writer); // prevent server from crashing if there's an error
  });
}