2.3.2 • Published 3 years ago

@ecolytiq-team/ecolytiq-sdk v2.3.2

Weekly downloads
-
License
Apache-2.0
Repository
github
Last release
3 years ago

ecolytiq-sdk-npm

Node.js Package

Usage

npm install @ecolytiq-team/ecolytiq-sdk

Get an Access Token from the ecolytiq Auth Server, either via agreed method of token retrival like OAuth2 or the apiAuth helper.

Setup an API Configuration f.e. with getApiConfiguration and use the API either using one of the helper functions api* or the OpenAPI generated client code.

Helper Functions

This package contains several helper functions which are mainly meant to abstract away some of the default complexity and settings of the generated API client. The api* helper also wrap errors into either:

  • APIUnavailable if the server is not reachable,
  • APIUnexpectedResponse for a response status outside 200-299
  • APIInvalidResponse if the result did return successfull but could not be interpreted by the helper

apiAuth Helper

Currently the Auth Helper apiAuth can handle 2 cases. The request of an accessToken for given client credentials for a typical Serverside M2M Authentication Flow.

import { apiAuth } from "@ecolytiq-team/ecolytiq-sdk";

const token = await apiAuth({
    authUrl: apiEndpoint,
    scope: "all",
    grantType: "token",
    clientCredentials: {
        clientId: "id",
        clientSecret: "secret",
    },
});

The second method is to use a username and password combination for a typical frontend login approach (f.e. for a SPA).

import { apiAuth } from "@ecolytiq-team/ecolytiq-sdk";

const token = await apiAuth({
    authUrl: apiEndpoint,
    scope: "all",
    grantType: "password",
    passwordCredentials: {
        username: "user",
        password: "pass",
    },
});

When run in non Browser context like NodeJS or Apache Cordova, the usage might lead to an "Invalid Reference Error" because the generated client will try to access window.fetch. As a workaround one can set the fetchApi explicitly (and polyfill if needed) like this:

import { apiAuth } from "@ecolytiq-team/ecolytiq-sdk";
import fetchApi from "isomorphic-fetch";

const token = await apiAuth({
    authUrl: apiEndpoint,
    scope: "all",
    grantType: "password",
    passwordCredentials: {
        username: "user",
        password: "pass",
    },
    // override typescript-fetch specific settings
    // for f.e. NodeJS (or Node/Browser use) something like "isomorphic-fetch" can be used
    // for f.e. NextJS getStaticProps: extendedConfig: { fetchApi: fetch } is enough
    // for f.e. Cordova you need to install a fetch replacement like whatwg-fetch
    extendedConfig: { fetchApi: fetchApi },
});

Note: The auth helper currently only allows selected methods and does not return any token expiration time or other information. For production, this should be replaced with an OAuth2 client connecting to the Ecolytiq Auth Server.

getApiConfiguration

This helper can be used to setup a Configuration Object for the API with given token and specified (prod/staging/sandbox/..) api endpoint.

const apiConfig = getApiConfiguration({
    // token returned by either OAuth2 client or apiAuth helper
    authToken: token,
    apiUrl: apiEndpoint,
});

// for the generated client code
const enrichmentService = new EnrichmentServiceApi(apiConfig);
const greenTXItems = await enrichmentService.txpTransactionRangePost({ ... })

// for the helper
const greenTXItems = await apiRequestRangeEnrichment(apiConfig, txItems, "DE");

When run in non Browser context like NodeJS or Apache Cordova, the usage might lead to an "Invalid Reference Error" because the generated client will try to access window.fetch. As a workaround one can set the fetchApi explicitly:

import { getApiConfiguration } from "@ecolytiq-team/ecolytiq-sdk";
import fetchApi from "isomorphic-fetch";

const apiConfig = getApiConfiguration({
    // token returned by either OAuth2 client or apiAuth helper
    authToken: token,
    apiUrl: apiEndpoint,
    // override typescript-fetch specific settings
    // for f.e. NodeJS (or Node/Browser use) something like "isomorphic-fetch" can be used
    // for f.e. NextJS getStaticProps: extendedConfig: { fetchApi: fetch } is enough
    // for f.e. Cordova you need to install a fetch replacement like whatwg-fetch
    fetchApi: fetchApi,
});

apiRequestEnrichment for batch TXItem Enrichment

This helper can be used for enrichment of a single TXItem. It is based on the /txp/transaction specification.

const greenTXItem = await apiRequestEnrichment(apiConfig, txitem, "DE");

apiRequestRangeEnrichment for batch TXItem Enrichment

This helper can be used for enrichment of multiple TXItems. It is based on the /txp/transaction/range specification.

const greenTXItems = await apiRequestRangeEnrichment(apiConfig, txitems, "DE");

pinging the server with apiGetHealth

This helper can be used to check the Servers health info. It is based on the /txp/ping specification.

try {
    const pingResponse = await apiGetHealth(apiConfig);
    // just checking if a specific name is in the response, otherwise
    // it could also return {}
    if (`PONG_date` in pingResponse) {
        console.log("Server pinged, up and running");
    }
} catch (e) {
    if (e instanceof APIUnavailable) {
        // Server down or broken route
        console.warning("Server did not respond at all.");
    } else {
        // Server responded but without PONG, might be a problem
        // or
        console.warning("Server did not respond as expected.");
    }
}

Using the OpenAPI Generated Client (typescript-fetch)

This package contains the complete generated code for the Ecolytiq Transaction API as specified, generated with OpenAPI Generator and typescript-fetch template. It will expose the the tags and operations as follows:

  • tags create an API Class for example: enrichment-service will be EnrichmentServiceApi
  • either a name operationId or path + http method will be mangled into a method name like: /txp/transaction/range into txpTransactionRangePost which will only return a result if possible and txpTransactionRangePostRaw which will return more information for custom error handling.

This makes it moderately easy to find the respective method used for a specified api method. Any modern IDE should provide that much information. With this the generated code can be used directly without additional handling and error wrappers if needed:

Example for JavaScript:

import { EnrichmentServiceApi, getApiConfiguration } from "@ecolytiq-team/ecolytiq-sdk";

async function getEnrichedItems(apiEndpoint, token, txitems) {
    const apiConfig = getApiConfiguration({
        authToken: token,
        apiUrl: apiEndpoint,
    });
    const enrichmentService = new EnrichmentServiceApi(apiConfig);
    return await enrichmentService.txpTransactionRangePost({
        modelRegionCode: "DE",
        body: {
            txItems: txitems,
        },
    });
}

Example for TypeScript:

import { EnrichmentServiceApi, getApiConfiguration, GreenTXItem, TXItem } from "@ecolytiq-team/ecolytiq-sdk";

async function getEnrichedItems(apiEndpoint: string, token: string, txitems: TXItem[]): Promise<GreenTXItem[]> {
    const apiConfig = getApiConfiguration({
        authToken: token,
        apiUrl: apiEndpoint,
    });
    const enrichmentService = new EnrichmentServiceApi(apiConfig);
    return await enrichmentService.txpTransactionRangePost({
        modelRegionCode: "DE",
        body: {
            txItems: txitems,
        },
    });
}
2.3.2

3 years ago

2.3.1

3 years ago

2.3.0

3 years ago

0.0.2-beta.5

3 years ago