createHttpClient(options)collectMetrics(options)registerClient(container, client)registerClients(container, clients, defaults)HttpClient(options)- Metric handlers
metricsHandleStartmetricsHandleDonemetricsHandleFailmetricsHandleRetrymetricsHandleSuccess
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
originis set, thenprefixUrlwill be set toorigin + path. - If
prefixUrlis set, thenoriginandpathare ignored. - Use the
extendoption 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 whenoriginis set. Default: none.prefixUrl(string): The GotprefixUrl. Overridesoriginandpath. Default: none.bearerToken(string): Token to send in theauthorizationheader. Default: none.cache(boolean): The Gotcacheoption. Default: none.hooks(boolean): The Gothooksoption. Default: none.extend(object): Passed togot.extendwhen creating the Got instance.got(object): Got instance to use. Default:gotimported 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 asbearerTokento 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 clientnameand 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
responseTypeisjson. - The default for
resolveBodyOnlyistrue. - An error
errthrown from a request will haveerr.statusCodeset (copied fromerr.response.statusCode). - All methods have a
metaoption to log additional properties to themetakey. - All methods have a
logPropsoption to log additional properties at the top-level. - All methods have a
resourceNameoption to group dynamic requests, e.g., ifurl=/api/users/123then setresourceName=/api/users. - All methods have these additional options, which may be set per-request
to override the default from the constructor (see below):
responseLogLevelwillLogOptionswillLogResponsePropswillLogResponseDatagetLogResponsePropsgetLogResponseData
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 differentprefixUrlfor the health check. Default: use the sameprefixUrlas the client.getHealth: Function called for thehealthmethod. Receives the client instance and thehealthPathas 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 ifresponseLogLevelis an active level. Default: true.willLogResponseData(boolean): If true, logdatareturned bygetLogResponseData. Only relevant ifresponseLogLevelis 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 ifresponseLogLevelis 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 ifresponseLogLevelis an active level andwillLogResponseDatais 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)methoddata(on success) orerr(on fail)- Must contain
statusCodeandtimingsproperties. - May contain
isFromCacheproperty.
- Must contain
metricsHandleStart: Call immediately before request is started.metricsHandleDone: Call when request completes or errors.metricsHandleFail: Call when request fails; passederrproperty.metricsHandleRetry: Call when request retries; passederrproperty.metricsHandleSuccess: Call when request succeeds; passeddataproperty.