From 672fd79307f273bbc9829c2c09b68710af9eeef4 Mon Sep 17 00:00:00 2001 From: Dmytro Kulchytskyi Date: Tue, 22 Feb 2022 19:02:33 +0200 Subject: [PATCH] feat(service-com): Added ServiceCommunicator (#46) * feat(service-com): Added ServiceCommunicator * feat(service-com): Added ServiceCommunicator * feat(service-com): Added ServiceCommunicator * feat(service-com): Added ServiceCommunicator --- package.json | 3 +- src/interfaces/ServiceCommunicator.js | 57 +++++++++++++++++++++++++++ src/interfaces/index.js | 2 + 3 files changed, 61 insertions(+), 1 deletion(-) create mode 100644 src/interfaces/ServiceCommunicator.js diff --git a/package.json b/package.json index b6d58ef..1309e15 100644 --- a/package.json +++ b/package.json @@ -45,13 +45,14 @@ "standard": "^14.3.3" }, "dependencies": { + "axios": "^0.26.0", "bluebird": "^3.7.2", "dot-get": "^1.0.1", "ein-validator": "^1.0.0", "esm": "^3.2.25", "express": "^4.17.1", "express-validator": "^6.6.1", - "http-status": "^1.4.2", + "http-status": "^1.5.0", "https": "^1.0.0", "lodash": "^4.17.20", "node-device-detector": "^1.3.11", diff --git a/src/interfaces/ServiceCommunicator.js b/src/interfaces/ServiceCommunicator.js new file mode 100644 index 0000000..fde8b98 --- /dev/null +++ b/src/interfaces/ServiceCommunicator.js @@ -0,0 +1,57 @@ +import axios from 'axios' +import Status from 'http-status' + +export class ServiceCommunicator { + constructor ({ + standardError, + config + }) { + this.standardError = standardError + this.logmsg = config.logmsg + } + + init (serviceUrl) { + this.serviceUrl = serviceUrl + } + + async http (options) { + try { + const response = await axios({ + baseURL: this.serviceUrl, + ...options + }) + return response.data + } catch (error) { + const { response } = error + if (response && response.data && response.data.error) { + throw this._getStandardError(response.data.error) + } + throw error + } + } + + _getStandardError (error) { + const type = this._getErrorType(error.type) + const { message, errors = [] } = error + return this.standardError({ + type, + message, + errors: errors.map(({ location, ...rest }) => ({ + param: Object.keys(rest)[0], + msg: Object.values(rest)[0], + location + })) + }) + } + + _getErrorType (type) { + switch (type) { + case Status['400_NAME']: + return this.logmsg.errors.validationError + case Status['404_NAME']: + return this.logmsg.errors.notFoundError + default: + return type + } + } +} diff --git a/src/interfaces/index.js b/src/interfaces/index.js index f477c66..a7f7127 100644 --- a/src/interfaces/index.js +++ b/src/interfaces/index.js @@ -7,6 +7,8 @@ import { validationResult } from 'express-validator' import { makeInvoker } from 'awilix-express' import DeviceDetector from 'node-device-detector' +export { ServiceCommunicator } from './ServiceCommunicator' + /** * A module for common interfaces * @module interface