Skip to content
This repository has been archived by the owner on Dec 21, 2023. It is now read-only.

Commit

Permalink
feat(service-com): Added ServiceCommunicator (#46)
Browse files Browse the repository at this point in the history
* feat(service-com): Added ServiceCommunicator

* feat(service-com): Added ServiceCommunicator

* feat(service-com): Added ServiceCommunicator

* feat(service-com): Added ServiceCommunicator
  • Loading branch information
dmytro-kulchytskyi authored Feb 22, 2022
1 parent f538de3 commit 672fd79
Show file tree
Hide file tree
Showing 3 changed files with 61 additions and 1 deletion.
3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
57 changes: 57 additions & 0 deletions src/interfaces/ServiceCommunicator.js
Original file line number Diff line number Diff line change
@@ -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
}
}
}
2 changes: 2 additions & 0 deletions src/interfaces/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down

0 comments on commit 672fd79

Please sign in to comment.