This library provides some of the most common component development functionality in a simple, reusable way.
To install, type
npm install @elastic.io/component-commons-library
A number of REST Client classes are available to use and extend to create Clients for a given API.
Each of the REST Clients extends from the NoAuthRestClient
, overriding the relevant methods. Exception is PlatformApiRestClient and PlatformApiLogicClient.
NoAuthRestClient class to make rest requests no no auth APIs by provided options.
const Client = new NoAuthRestClient(emitter, cfg);
Makes requests: options expects the following sub-variables:
Class can be extended to have custom authentication
Example:
const { NoAuthRestClient } = require('@elastic.io/component-commons-library');
class MyClient extends NoAuthRestClient {
constructor(emitter, cfg) {
super(emitter, cfg);
// Other variables go here
}
// Some methods can be overridden
addAuthenticationToRequestOptions(requestOptions) {
requestOptions.specialField = true;
}
}
BasicAuthRestClient class extends NoAuthRestClient class. Makes requests to resource with basic auth.
const Client = new BasicAuthRestClient(emitter, cfg, user, pass);
ApiKeyRestClient class extends NoAuthRestClient class. Makes requests to resource with api key (custom header) auth.
const Client = new BasicAuthRestClient(emitter, cfg, user, pass);
CookieRestClient class extends NoAuthRestClient class.
TBD
OAuth2RestClient class extends NoAuthRestClient class. Makes requests to resource with oauth2 access token auth.
const Client = new OAuth2AuthorizationCodeRestClient(emitter, cfg);
This class can handle, refresh and emit oauth2 EIO configuration.
FacelessRestClient Makes requests to resource with oauth2 access token auth using ElasticIO Faceless Service.
secretId
parameter or oauth
object with oauth2 config and tokens.User-Agent
header when client retrieve secret from platformx-request-id
header when client retrieve secret from platform
const Client = new FacelessRestClient(emitter, cfg, userAgent, msgId);
NtlmRestClient class extends NoAuthRestClient class. Makes requests to resource with NTLM authentication. Falls back to basic authentication if NTLM authentication fails. Handles both V1 and V2 of the NTLM Protocol.
SOMEDOMAIN\SomeUser
)const Client = new NtlmRestClient(emitter, cfg);
A number of Platform API Client classes are available to use and extend them to create Clients for Platform API.
PlatformApiRestClient class extends BasicAuthRestClient class. The method inside this class checks for the status code 200, if not, then throws an error. And also checks that the response came with the correct data in the JSON format and the other expected response headers.
const Client = new PlatformApiRestClient(emitter, cfg);
PlatformApiLogicClient class extends PlatformApiRestClient class. Contains useful methods to manipulate flow's state to set it either to active running or to inactive stopped, searching flows, workspaces, credentials and more.
const Client = new PlatformApiLogicClient(emitter, cfg);
Contains tools for JSON metadata generation
convertJsonSchemaToEioSchema(keyToReturn, completeSchemaOriginal)
- converts general JSON schema to platform-friendly JSON metadatamakeSchemaInline(json, availableSchemas)
- replaces $ref recursively with full object description for provided json object using availableSchemas schemas map.Contains functions to transform platform data that contains JSONata expressions
jsonataTransform(msg, cfg)
- returns the msg.body
with the JSONata expressions evaluated to valuesThe attachment processor function can be used to store attachments on the platform. It exposes the following functions
uploadAttachment(getAttachment, retryOptions, contentType)
, which will upload an attachment to the platform Maester
storage and return the result object.
Where: getAttachment
- async function which returns stream retryOptions
- (optional): parameters for retrying of upload attachment, if request failed. Parameters are retriesCount
and requestTimeout
(ms)
contentType
- (optional): Content-Type
of attachment. By default Content-Type
will be calculated automatically. getAttachment(url, contentType)
, which will retrieve an attachment from steward
or maester
storage. To specify the storage - query parameter
storage_type
must be provided. To get items from maester
storage - ?storage_type=maester
should added to the url
argument. By default attachments are retrieved from steward
storage, so ?storage_type=steward
is not obligated to be added to the url
argument. contentType
-
one of [stream
, arraybuffer
]Example:
const { AttachmentProcessor } = require('@elastic.io/component-commons-library');
const getAttachAsStream = async () => (
await axios.get('http://sample.pdf', { responseType: 'stream' })
).data;
const result = await new AttachmentProcessor().uploadAttachment(getAttachAsStream, 'application/pdf');
const { objectId } = result.data;
const { AttachmentProcessor } = require('@elastic.io/component-commons-library');
const result = await new AttachmentProcessor().getAttachment('http://example.com', 'stream'); // steward storage
const result = await new AttachmentProcessor().getAttachment('http://example.com?storage_type=steward', 'arraybuffer'); // steward storage
const result = await new AttachmentProcessor().getAttachment('http://example.com?storage_type=maester', 'stream'); // maester storage
API_RETRIES_COUNT (defaults to 3): maximum amount of retries for 5xx errors. If server still responding 5xx, error will be thrown.
API_REQUEST_TIMEOUT (defaults to 15000, min: 500, max: 120000): specifies the number of milliseconds before the request times out. If the request takes longer than timeout, the request will be aborted.
axiosReqWithRetryOnServerError
(use with .call()
to pass context, implement it as a method of class with logger
and cfg
(value of configuration object for current action) values in a constructor) - function which makes axios request by specified request-config, making logging and error handling:
API_RETRIES_COUNT
times, each retry will be delayed with exponentialSleep
function. cfg
has doNotThrow404
set to true: 404 error won't be treated as error. getErrMsg
- forms error message from axios-response.
getRetryOptions
- return valid values for envs API_RETRIES_COUNT
and API_REQUEST_TIMEOUT
. If values are higher or lower the limit - they'll be overwritten by default values.
sleep
- return promise which resolves after N time.
exponentialDelay
- returns number of milliseconds depending to current retry. See exponential backoff to explanation.
exponentialSleep
- return promise which resolves after N time. Where N is number of milliseconds from exponentialDelay
execution.
Example for axiosReqWithRetryOnServerError
function:
class Client {
private logger: any;
private cfg: any;
constructor(emitter, cfg) {
this.logger = emitter.logger;
this.cfg = cfg;
}
public async apiRequest(options: AxiosRequestConfig): Promise<any> {
try {
const response = await axiosReq.axiosReqWithRetryOnServerError(this, requestOptions);
return response.data;
} catch (error) {
if (error.response?.status === 401) {
// update token
}
throw error;
}
}
public async getUserById(id) {
return this.apiRequest({
url: `/users/${id}`,
method: 'GET',
});
}
}
The built in logger uses Bunyan Logger as its base implementation. The available logger methods can be found here.
Example:
const { Logger } = require('@elastic.io/component-commons-library');
const logger = Logger.getLogger();
logger.info('Hello, world');
The getLogger()
method takes an optional parameter loggerName
that lets you declare multiple different loggers.
Apache-2.0 © elastic.io GmbH