@thzero/library_server_service_rest_axios
v0.19.1
Published
  [ |
| getById / deleteById | (correlationId, key, url, id, options) |
| post | (correlationId, key, url, body, options) |
| postById | (correlationId, key, url, id, body, options) |
key selects the backend from config. options is merged over the axios config, so anything axios accepts can be set per call.
Each call builds an axios instance that:
- sets
baseURLfrom the resolved resource, with a trailing slash guaranteed; - sends
Content-Type: application/json; - sends a correlationId header, generating one when the caller has none and writing it back onto
options.correlationIdso the caller can log the same value; - sends an api key header when the resource or
optionssupplies one, withoptions.apiKeywinning; - sends an
Authorizationbearer header whenoptions.tokenis set, in the form the framework's own authentication middleware parses back; - applies
options.timeout, or the backend's configuredtimeout; - treats any status from 200 to 503 as a resolved response rather than a throw, so failures arrive as responses.
_validate returns the payload on 200. On 401 it clears the user token through SERVICE_AUTH, when one is registered.
Configuration
Per-backend, read through _config.getBackend(correlationId, key):
{
"app": {
"backend": {
"<key>": {
"baseUrl": "https://service-host/",
"apiKey": "<api key>",
"timeout": 30000,
"discoverable": {
"name": "<discovery service name>",
"enabled": true
}
}
}
}
}baseUrl— used directly when discovery is off or unavailable.apiKey— sent as the api key header.options.apiKeyoverrides it per call.timeout— milliseconds.options.timeoutoverrides it per call.discoverable— omit it to skip discovery entirely. With it present, discovery is used only when aSERVICE_DISCOVERY_RESOURCESservice is registered anddiscoverable.enabledis notfalse.discoverable.name— the name looked up in discovery. Required once discovery is active. Discovered resources are cached per key.
A discovered resource's url is assembled as http(s)://<address>[:<port>], where the address is the resource's address, or a DNS name built from label, namespace and local.
Wiring it up
Register it as the REST communication service from your BootMain derived class or a boot plugin:
import communicationRestService from '@thzero/library_server_service_rest_axios';
this._injectService(LibraryServerConstants.InjectorKeys.SERVICE_COMMUNICATION_REST, new communicationRestService());Then call it from a service:
const response = await this._serviceCommunicationRest.get(correlationId, 'inventory', 'items', {
token: request.token
});The service resolves SERVICE_AUTH and SERVICE_DISCOVERY_RESOURCES during init; both may legitimately be absent.
Development
npm run lint # eslint .
npm run lint:fix # eslint . --fix
npm test # node --test "test/*.test.js"
