createHttpClient(options)
collectMetrics(options)
registerClient(container, client)
registerClients(container, clients, defaults)
HttpClient(options)
- Metric handlers
metricsHandleStart
metricsHandleDone
metricsHandleFail
metricsHandleRetry
metricsHandleSuccess
Every function described above is a top-level export. You can import any of them like this:
import { createHttpClient } from '@meltwater/mlabs-http'
metricNames
: Un-prefixed metric names.
Create an HttpClient with an API compatible with Got.
- A new Got instance will be created for the HttpClient.
- If
origin
is set, thenprefixUrl
will be set toorigin + path
. - If
prefixUrl
is set, thenorigin
andpath
are ignored. - Use the
extend
option to pass default options to Got These options are merged withgot.extend
. - Additional options are passed to HttpClient.
options
(object): Any additional options are passed directly to the HttpClient.origin
(string): The HTTP server URL origin. Default: none.path
(string): The path to prefix all requests with. Only used whenorigin
is set. Default: none.prefixUrl
(string): The GotprefixUrl
. Overridesorigin
andpath
. Default: none.bearerToken
(string): Token to send in theauthorization
header. Default: none.cache
(boolean): The Gotcache
option. Default: none.hooks
(boolean): The Gothooks
option. Default: none.extend
(object): Passed togot.extend
when creating the Got instance.got
(object): Got instance to use. Default:got
imported from got.
(HttpClient)
import { createHttpClient } from '@meltwater/mlabs-http'
const http = createHttpClient({origin: 'https://httpbin.org'})
const body = await http.get('get')
await http.post('post', { json: { foo: 'bar' } })
import { createHttpClient } from '@meltwater/mlabs-http'
const http = createHttpClient({
resolveBodyOnly: false,
origin: 'https://httpbin.org'
})
const { body, statusCode } = await http.get('get')
// or per request
const { body, statusCode } = await http.get('get', {
resolveBodyOnly: false
})
import { createHttpClient } from '@meltwater/mlabs-http'
const http = createHttpClient({
extend: {headers: {foo: 'bar'}},
origin: 'https://httpbin.org'
})
const body = await http.get('get')
import { createHttpClient } from '@meltwater/mlabs-http'
const http = createHttpClient({
origin: 'https://httpbin.org',
responseLogLevel: 'info',
getLogResponseProps: ({ body }) => ({ myIp: body.origin })
})
const body = await http.get('get', {
meta: { user: { name: 'foo' } },
logProps: { userId: 123 }
})
// all logs have { userId: 123, meta: { user: { name: 'foo' } } }
// success log also has { myIp: '127.0.0.1' }
Register an HttpClient and its dependencies in the Awilix container.
The container must provide the dependencies registry
, log
and reqId
.
The reqId
will be sent in the x-request-id
header.
The registry
is passed as metricRegistry
to the HttpClient.
For example, registering a client named http
will register the following dependencies:
httpCache
: A quick-lru cache.httpHooks
: No default hooks.httpClient
: The HttpClient (scoped).
Any of these dependencies may be overridden manually by registering a compatible dependency under the corresponding name.
container
(object required): The [Awilix] container.client
(object):name
(string): The (unique) client name. The client will be registered as${name}Client
. Default:http
.origin
(string): Passed directly to HttpClient.path
(string): Passed directly to HttpClient.prefixUrl
(string): Passed directly to HttpClient.token
(string): Passed asbearerToken
to HttpClient.createHooks
(function): Function that returns hooks (registered as dependency).cacheOptions
(object): Options passed directly to quick-lru.clientOptions
(object): Options passed directly to HttpClient.
(undefined)
registerClient(container, {
name: 'foo',
origin: 'https://example.com'
})
const client = container.resolve('fooClient')
Register each HttpClient and its dependencies in the Awilix container
using registerClient
.
container
(object required): The [Awilix] container.clients
(object): The clients to register. Each key will be used as the clientname
and the value will be passed as the second argument toregisterClient
.defaults
(object): Options to apply to each client by default.
(undefined)
registerClients(container, {
foo: { origin: 'https://example.com' },
{ token: 'auth-token' }
})
const client = container.resolve('fooClient')
Collect metrics with Prometheus client.
Call this function once with a Prometheus Registry instance and pass the same Registry instance to each HttpClient that should send metrics to this Registry.
The list of (un-prefixed) metric names is exported as metricNames
.
options
(object):register
(object required): Prometheus registry to use for metrics.prefix
(string): Prefix to prepend to all metric names. Default:http_client_
.metricOptions
(object): Override options for each metric. Default: no overrides.
(undefined)
const register = new Registry()
collectMetrics({
register,
prefix: 'my_prefix_',
options: {
'request_duration_milliseconds': {
buckets: [0, 200, 300, 800]
}
}
})
const http = createHttpClient({ metricRegistry: register })
await http.get('/get')
register.metrics()
Wraps all Got methods (except stream
) with an identical API:
get
, post
, put
, patch
, head
, and delete
.
Provides an additional method health
which takes no arguments
and resolves true
or rejects.
Configure with the healthPath
, healthPrefixUrl
and getHealth
options.
- The default
responseType
isjson
. - The default for
resolveBodyOnly
istrue
. - An error
err
thrown from a request will haveerr.statusCode
set (copied fromerr.response.statusCode
). - All methods have a
meta
option to log additional properties to themeta
key. - All methods have a
logProps
option to log additional properties at the top-level. - All methods have a
resourceName
option to group dynamic requests, e.g., ifurl=/api/users/123
then setresourceName=/api/users
. - All methods have these additional options, which may be set per-request
to override the default from the constructor (see below):
responseLogLevel
willLogOptions
willLogResponseProps
willLogResponseData
getLogResponseProps
getLogResponseData
options
(object):got
(object required): The Got instance to use for requests.name
(string): The client name (for logging). Default: http.metricRegistry
(object): Prometheus Registry to collect metrics. Default:null
(metrics disabled).metricPrefix
(object): Prefix prepend to all metric names. Default: SeecollectMetrics
.healthPath
(string): Path to use for the health check. Default:''
.healthPrefixUrl
(string): Use a differentprefixUrl
for the health check. Default: use the sameprefixUrl
as the client.getHealth
: Function called for thehealth
method. Receives the client instance and thehealthPath
as arguments. Default: a GET request tohealthPath
.reqId
(string): A request id to bind to the instance. Default: one will be generated.reqIdHeader
(string): Name of the header to use for the request id. Default:x-request-id
.reqNameHeader
(string): Name of the header to use for the request name. Default:x-request-name
.responseLogLevel
(string): Log level to log successful responses. If this level is active, then successful responses will be logged according to the other log response options. Default: debug.willLogOptions
(boolean): If true, log all options undermeta
. Default: true.willLogResponseProps
(boolean): If true, log props returned bygetLogResponseProps
. Only relevant ifresponseLogLevel
is an active level. Default: true.willLogResponseData
(boolean): If true, logdata
returned bygetLogResponseData
. Only relevant ifresponseLogLevel
is an active level. Default: false.getLogResponseProps
(function): Receives the full response from Got and returns an object whose properties will be logged at the top level. Only relevant ifresponseLogLevel
is an active level. Default: no additional props are logged.getLogResponseData
(function): Receives the full response from Got and returns an object whose properties will be logged underdata
. Only relevant ifresponseLogLevel
is an active level andwillLogResponseData
is set. Default: logs a relevant subset of the full Got response.log
(object): A Logger. Default: a new logger.
Handlers for updating metrics. Provided for libraries that want to register and track similar metrics.
Each handler is passed the following options in the first argument:
prefix
(seecollectMetrics
)name
(seeHttpClient
)resourceName
(seeHttpClient
)method
data
(on success) orerr
(on fail)- Must contain
statusCode
andtimings
properties. - May contain
isFromCache
property.
- Must contain
metricsHandleStart
: Call immediately before request is started.metricsHandleDone
: Call when request completes or errors.metricsHandleFail
: Call when request fails; passederr
property.metricsHandleRetry
: Call when request retries; passederr
property.metricsHandleSuccess
: Call when request succeeds; passeddata
property.