TypeScript and JavaScript
import { IngestOptions, Metering, FlushMode, UsageClient, UsageApiPayload, AggregationType, AggregationInterval, TimeRange } from "amberflo-metering-typescript";
/**
* This sample illustrates how to ingest your metering data into Amberflo in auto flush mode.
* Auto is the default mode.
*/
export async function runIngest() {
//obtain your Amberflo API Key
const apiKey = 'my-api-key';
//optional ingest options
let ingestOptions = new IngestOptions();
//set flush mode to auto. This is also the default, so this step is optional.
ingestOptions.flushMode = FlushMode.auto;
//Number of messages posted to the API. Default is 100.
ingestOptions.batchSize = 20;
//Frequency at which queued data will be sent to API. Default is 1000 milliseconds.
ingestOptions.frequencyMillis = 3000;
//Set to true to log debug statements
const debug = false;
const metering = new Metering(apiKey, debug, ingestOptions);
//initialize and start the ingestion client
metering.start();
//define dimesions for your meters
const dimensions = new Map<string, string>();
dimensions.set("region", "Midwest");
dimensions.set("customerType", "Tech");
let j = 0;
for (j = 0; j < 50; j++) {
let delay = new Promise(resolve => setTimeout(resolve, 100));
await delay;
//Queue meter messages for ingestion.
//In auto flush mode, queue will be flushed when ingestOptions.batchSize is exceeded or periodically ingestOptions.frequencyMillis
//Params: meterApiName: string, meterValue: number, meterTimeInMillis: number, customerId: string, dimensions: Map<string, string>
metering.meter("TypeScript-ApiCalls", j + 1, Date.now(), "123", dimensions);
metering.meter("TypeScript-Bandwidth", j + 1, Date.now(), "123", dimensions);
metering.meter("TypeScript-Transactions", j + 1, Date.now(), "123", dimensions);
metering.meter("TypeScript-CPU", j + 1, Date.now(), "123", dimensions);
}
//wait for messages and requests to API to complete
await metering.flush();
//perform graceful shutdown, flush, stop the timer
await metering.shutdown();
}
runIngest();
/**
* This sample illustrates how to setup customer details.
*/
export async function runCustomerDetails() {
//obtain your Amberflo API Key
const apiKey = 'my-api-key';
const traits = new Map<string, string>();
traits.set("stripeId", "cus_AJ6bY3VqcaLAEs");
traits.set("customerType", "Tech");
const metering = new Metering(apiKey, false);
await metering.addOrUpdateCustomerDetails('123', 'Dell', traits);
console.log('customer setup completed!');
}
runCustomerDetails();
export async function runUsage() {
//obtain your Amberflo API Key
const apiKey = 'my-api-key';
//initialize the usage client
const client = new UsageClient(apiKey);
// start date time represented as seconds since the Unix Epoch (1970-01-01T00:00:00Z) and using UTC.
// following is Start time for last 24 hours
const startTimeInSeconds = Math.ceil(((new Date().getTime()) - (24 * 60 * 60 * 1000)) / 1000);
let timeRange = new TimeRange();
timeRange.startTimeInSeconds = startTimeInSeconds;
// Example 1: group by customers for a specific meter and all customers
// setup usage query params
// visit following link for description of payload:
// https://amberflo.readme.io/docs/getting-started-sample-data#query-the-usage-data
let payload = new UsageApiPayload();
payload.meterApiName = 'TypeScript-ApiCalls';
payload.aggregation = AggregationType.sum;
payload.timeGroupingInterval = AggregationInterval.day;
//optional: group the result by customer
payload.groupBy = ["customerId"];
payload.timeRange = timeRange;
//Call the usage API
let jsonResult = await client.getUsage(payload);
// To understand the API response, visit following link:
// https://amberflo.readme.io/docs/getting-started-sample-data#query-the-usage-data
console.log(JSON.stringify(jsonResult, null, 4));
//Example 2: filter for a meter for specific customer
//setup usage query params
let payloadForFilteredCustomer = new UsageApiPayload();
payloadForFilteredCustomer.meterApiName = 'TypeScript-ApiCalls';
payloadForFilteredCustomer.aggregation = AggregationType.sum;
payloadForFilteredCustomer.timeGroupingInterval = AggregationInterval.day;
//optional: group the result by customer
payloadForFilteredCustomer.groupBy = ["customerId"];
//Filter result for a specific customer by ID
payloadForFilteredCustomer.filter = {customerId: ["123"]};
payloadForFilteredCustomer.timeRange = timeRange;
//Call the usage API
let jsonResultForFilteredCustomer = await client.getUsage(payloadForFilteredCustomer);
console.log(JSON.stringify(jsonResultForFilteredCustomer, null, 4));
}
runUsage();import { IngestOptions, Metering, FlushMode, UsageClient, UsageApiPayload, AggregationType, AggregationInterval, TimeRange } from "amberflo-metering-typescript";
/**
* This sample illustrates how to ingest your metering data into Amberflo in auto flush mode.
* Auto is the default mode.
*/
export async function runIngest() {
//obtain your Amberflo API Key
const apiKey = 'my-api-key';
//optional ingest options
let ingestOptions = new IngestOptions();
//set flush mode to auto. This is also the default, so this step is optional.
ingestOptions.flushMode = FlushMode.auto;
//Number of messages posted to the API. Default is 100.
ingestOptions.batchSize = 20;
//Frequency at which queued data will be sent to API. Default is 1000 milliseconds.
ingestOptions.frequencyMillis = 3000;
//Set to true to log debug statements
const debug = false;
const metering = new Metering(apiKey, debug, ingestOptions);
//initialize and start the ingestion client
metering.start();
//define dimesions for your meters
const dimensions = new Map<string, string>();
dimensions.set("region", "Midwest");
dimensions.set("customerType", "Tech");
let j = 0;
for (j = 0; j < 50; j++) {
let delay = new Promise(resolve => setTimeout(resolve, 100));
await delay;
//Queue meter messages for ingestion.
//In auto flush mode, queue will be flushed when ingestOptions.batchSize is exceeded or periodically ingestOptions.frequencyMillis
//Params: meterApiName: string, meterValue: number, meterTimeInMillis: number, customerId: string, dimensions: Map<string, string>
metering.meter("TypeScript-ApiCalls", j + 1, Date.now(), "123", dimensions);
metering.meter("TypeScript-Bandwidth", j + 1, Date.now(), "123", dimensions);
metering.meter("TypeScript-Transactions", j + 1, Date.now(), "123", dimensions);
metering.meter("TypeScript-CPU", j + 1, Date.now(), "123", dimensions);
}
//wait for messages and requests to API to complete
await metering.flush();
//perform graceful shutdown, flush, stop the timer
await metering.shutdown();
}
runIngest();
/**
* This sample illustrates how to setup customer details.
*/
export async function runCustomerDetails() {
//obtain your Amberflo API Key
const apiKey = 'my-api-key';
const traits = new Map<string, string>();
traits.set("stripeId", "cus_AJ6bY3VqcaLAEs");
traits.set("customerType", "Tech");
const metering = new Metering(apiKey, false);
await metering.addOrUpdateCustomerDetails('123', 'Dell', traits);
console.log('customer setup completed!');
}
runCustomerDetails();
export async function runUsage() {
//obtain your Amberflo API Key
const apiKey = 'my-api-key';
//initialize the usage client
const client = new UsageClient(apiKey);
// start date time represented as seconds since the Unix Epoch (1970-01-01T00:00:00Z) and using UTC.
// following is Start time for last 24 hours
const startTimeInSeconds = Math.ceil(((new Date().getTime()) - (24 * 60 * 60 * 1000)) / 1000);
let timeRange = new TimeRange();
timeRange.startTimeInSeconds = startTimeInSeconds;
// Example 1: group by customers for a specific meter and all customers
// setup usage query params
// visit following link for description of payload:
// https://amberflo.readme.io/docs/getting-started-sample-data#query-the-usage-data
let payload = new UsageApiPayload();
payload.meterApiName = 'TypeScript-ApiCalls';
payload.aggregation = AggregationType.sum;
payload.timeGroupingInterval = AggregationInterval.day;
//optional: group the result by customer
payload.groupBy = ["customerId"];
payload.timeRange = timeRange;
//Call the usage API
let jsonResult = await client.getUsage(payload);
// To understand the API response, visit following link:
// https://amberflo.readme.io/docs/getting-started-sample-data#query-the-usage-data
console.log(JSON.stringify(jsonResult, null, 4));
//Example 2: filter for a meter for specific customer
//setup usage query params
let payloadForFilteredCustomer = new UsageApiPayload();
payloadForFilteredCustomer.meterApiName = 'TypeScript-ApiCalls';
payloadForFilteredCustomer.aggregation = AggregationType.sum;
payloadForFilteredCustomer.timeGroupingInterval = AggregationInterval.day;
//optional: group the result by customer
payloadForFilteredCustomer.groupBy = ["customerId"];
//Filter result for a specific customer by ID
payloadForFilteredCustomer.filter = {customerId: ["123"]};
payloadForFilteredCustomer.timeRange = timeRange;
//Call the usage API
let jsonResultForFilteredCustomer = await client.getUsage(payloadForFilteredCustomer);
console.log(JSON.stringify(jsonResultForFilteredCustomer, null, 4));
}
runUsage();import { IngestOptions, Metering, FlushMode, UsageClient, UsageApiPayload, AggregationType, AggregationInterval, TimeRange } from "amberflo-metering-typescript";
/**
* This sample illustrates how to ingest your metering data into Amberflo in auto flush mode.
* Auto is the default mode.
*/
export async function runIngest() {
//obtain your Amberflo API Key
const apiKey = 'my-api-key';
//optional ingest options
let ingestOptions = new IngestOptions();
//set flush mode to auto. This is also the default, so this step is optional.
ingestOptions.flushMode = FlushMode.auto;
//Number of messages posted to the API. Default is 100.
ingestOptions.batchSize = 20;
//Frequency at which queued data will be sent to API. Default is 1000 milliseconds.
ingestOptions.frequencyMillis = 3000;
//Set to true to log debug statements
const debug = false;
const metering = new Metering(apiKey, debug, ingestOptions);
//initialize and start the ingestion client
metering.start();
//define dimesions for your meters
const dimensions = new Map<string, string>();
dimensions.set("region", "Midwest");
dimensions.set("customerType", "Tech");
let j = 0;
for (j = 0; j < 50; j++) {
let delay = new Promise(resolve => setTimeout(resolve, 100));
await delay;
//Queue meter messages for ingestion.
//In auto flush mode, queue will be flushed when ingestOptions.batchSize is exceeded or periodically ingestOptions.frequencyMillis
//Params: meterApiName: string, meterValue: number, meterTimeInMillis: number, customerId: string, dimensions: Map<string, string>
metering.meter("TypeScript-ApiCalls", j + 1, Date.now(), "123", dimensions);
metering.meter("TypeScript-Bandwidth", j + 1, Date.now(), "123", dimensions);
metering.meter("TypeScript-Transactions", j + 1, Date.now(), "123", dimensions);
metering.meter("TypeScript-CPU", j + 1, Date.now(), "123", dimensions);
}
//wait for messages and requests to API to complete
await metering.flush();
//perform graceful shutdown, flush, stop the timer
await metering.shutdown();
}
runIngest();
/**
* This sample illustrates how to setup customer details.
*/
export async function runCustomerDetails() {
//obtain your Amberflo API Key
const apiKey = 'my-api-key';
const traits = new Map<string, string>();
traits.set("stripeId", "cus_AJ6bY3VqcaLAEs");
traits.set("customerType", "Tech");
const metering = new Metering(apiKey, false);
await metering.addOrUpdateCustomerDetails('123', 'Dell', traits);
console.log('customer setup completed!');
}
runCustomerDetails();
export async function runUsage() {
//obtain your Amberflo API Key
const apiKey = 'my-api-key';
//initialize the usage client
const client = new UsageClient(apiKey);
// start date time represented as seconds since the Unix Epoch (1970-01-01T00:00:00Z) and using UTC.
// following is Start time for last 24 hours
const startTimeInSeconds = Math.ceil(((new Date().getTime()) - (24 * 60 * 60 * 1000)) / 1000);
let timeRange = new TimeRange();
timeRange.startTimeInSeconds = startTimeInSeconds;
// Example 1: group by customers for a specific meter and all customers
// setup usage query params
// visit following link for description of payload:
// https://amberflo.readme.io/docs/getting-started-sample-data#query-the-usage-data
let payload = new UsageApiPayload();
payload.meterApiName = 'TypeScript-ApiCalls';
payload.aggregation = AggregationType.sum;
payload.timeGroupingInterval = AggregationInterval.day;
//optional: group the result by customer
payload.groupBy = ["customerId"];
payload.timeRange = timeRange;
//Call the usage API
let jsonResult = await client.getUsage(payload);
// To understand the API response, visit following link:
// https://amberflo.readme.io/docs/getting-started-sample-data#query-the-usage-data
console.log(JSON.stringify(jsonResult, null, 4));
//Example 2: filter for a meter for specific customer
//setup usage query params
let payloadForFilteredCustomer = new UsageApiPayload();
payloadForFilteredCustomer.meterApiName = 'TypeScript-ApiCalls';
payloadForFilteredCustomer.aggregation = AggregationType.sum;
payloadForFilteredCustomer.timeGroupingInterval = AggregationInterval.day;
//optional: group the result by customer
payloadForFilteredCustomer.groupBy = ["customerId"];
//Filter result for a specific customer by ID
payloadForFilteredCustomer.filter = {customerId: ["123"]};
payloadForFilteredCustomer.timeRange = timeRange;
//Call the usage API
let jsonResultForFilteredCustomer = await client.getUsage(payloadForFilteredCustomer);
console.log(JSON.stringify(jsonResultForFilteredCustomer, null, 4));
}
runUsage();import { IngestOptions, Metering, FlushMode, UsageClient, UsageApiPayload, AggregationType, AggregationInterval, TimeRange } from "amberflo-metering-typescript";
/**
* This sample illustrates how to ingest your metering data into Amberflo in auto flush mode.
* Auto is the default mode.
*/
export async function runIngest() {
//obtain your Amberflo API Key
const apiKey = 'my-api-key';
//optional ingest options
let ingestOptions = new IngestOptions();
//set flush mode to auto. This is also the default, so this step is optional.
ingestOptions.flushMode = FlushMode.auto;
//Number of messages posted to the API. Default is 100.
ingestOptions.batchSize = 20;
//Frequency at which queued data will be sent to API. Default is 1000 milliseconds.
ingestOptions.frequencyMillis = 3000;
//Set to true to log debug statements
const debug = false;
const metering = new Metering(apiKey, debug, ingestOptions);
//initialize and start the ingestion client
metering.start();
//define dimesions for your meters
const dimensions = new Map<string, string>();
dimensions.set("region", "Midwest");
dimensions.set("customerType", "Tech");
let j = 0;
for (j = 0; j < 50; j++) {
let delay = new Promise(resolve => setTimeout(resolve, 100));
await delay;
//Queue meter messages for ingestion.
//In auto flush mode, queue will be flushed when ingestOptions.batchSize is exceeded or periodically ingestOptions.frequencyMillis
//Params: meterApiName: string, meterValue: number, meterTimeInMillis: number, customerId: string, dimensions: Map<string, string>
metering.meter("TypeScript-ApiCalls", j + 1, Date.now(), "123", dimensions);
metering.meter("TypeScript-Bandwidth", j + 1, Date.now(), "123", dimensions);
metering.meter("TypeScript-Transactions", j + 1, Date.now(), "123", dimensions);
metering.meter("TypeScript-CPU", j + 1, Date.now(), "123", dimensions);
}
//wait for messages and requests to API to complete
await metering.flush();
//perform graceful shutdown, flush, stop the timer
await metering.shutdown();
}
runIngest();
/**
* This sample illustrates how to setup customer details.
*/
export async function runCustomerDetails() {
//obtain your Amberflo API Key
const apiKey = 'my-api-key';
const traits = new Map<string, string>();
traits.set("stripeId", "cus_AJ6bY3VqcaLAEs");
traits.set("customerType", "Tech");
const metering = new Metering(apiKey, false);
await metering.addOrUpdateCustomerDetails('123', 'Dell', traits);
console.log('customer setup completed!');
}
runCustomerDetails();
export async function runUsage() {
//obtain your Amberflo API Key
const apiKey = 'my-api-key';
//initialize the usage client
const client = new UsageClient(apiKey);
// start date time represented as seconds since the Unix Epoch (1970-01-01T00:00:00Z) and using UTC.
// following is Start time for last 24 hours
const startTimeInSeconds = Math.ceil(((new Date().getTime()) - (24 * 60 * 60 * 1000)) / 1000);
let timeRange = new TimeRange();
timeRange.startTimeInSeconds = startTimeInSeconds;
// Example 1: group by customers for a specific meter and all customers
// setup usage query params
// visit following link for description of payload:
// https://amberflo.readme.io/docs/getting-started-sample-data#query-the-usage-data
let payload = new UsageApiPayload();
payload.meterApiName = 'TypeScript-ApiCalls';
payload.aggregation = AggregationType.sum;
payload.timeGroupingInterval = AggregationInterval.day;
//optional: group the result by customer
payload.groupBy = ["customerId"];
payload.timeRange = timeRange;
//Call the usage API
let jsonResult = await client.getUsage(payload);
// To understand the API response, visit following link:
// https://amberflo.readme.io/docs/getting-started-sample-data#query-the-usage-data
console.log(JSON.stringify(jsonResult, null, 4));
//Example 2: filter for a meter for specific customer
//setup usage query params
let payloadForFilteredCustomer = new UsageApiPayload();
payloadForFilteredCustomer.meterApiName = 'TypeScript-ApiCalls';
payloadForFilteredCustomer.aggregation = AggregationType.sum;
payloadForFilteredCustomer.timeGroupingInterval = AggregationInterval.day;
//optional: group the result by customer
payloadForFilteredCustomer.groupBy = ["customerId"];
//Filter result for a specific customer by ID
payloadForFilteredCustomer.filter = {customerId: ["123"]};
payloadForFilteredCustomer.timeRange = timeRange;
//Call the usage API
let jsonResultForFilteredCustomer = await client.getUsage(payloadForFilteredCustomer);
console.log(JSON.stringify(jsonResultForFilteredCustomer, null, 4));
}
runUsage();import { IngestOptions, Metering, FlushMode, UsageClient, UsageApiPayload, AggregationType, AggregationInterval, TimeRange } from "amberflo-metering-typescript";
/**
* This sample illustrates how to ingest your metering data into Amberflo in auto flush mode.
* Auto is the default mode.
*/
export async function runIngest() {
//obtain your Amberflo API Key
const apiKey = 'my-api-key';
//optional ingest options
let ingestOptions = new IngestOptions();
//set flush mode to auto. This is also the default, so this step is optional.
ingestOptions.flushMode = FlushMode.auto;
//Number of messages posted to the API. Default is 100.
ingestOptions.batchSize = 20;
//Frequency at which queued data will be sent to API. Default is 1000 milliseconds.
ingestOptions.frequencyMillis = 3000;
//Set to true to log debug statements
const debug = false;
const metering = new Metering(apiKey, debug, ingestOptions);
//initialize and start the ingestion client
metering.start();
//define dimesions for your meters
const dimensions = new Map<string, string>();
dimensions.set("region", "Midwest");
dimensions.set("customerType", "Tech");
let j = 0;
for (j = 0; j < 50; j++) {
let delay = new Promise(resolve => setTimeout(resolve, 100));
await delay;
//Queue meter messages for ingestion.
//In auto flush mode, queue will be flushed when ingestOptions.batchSize is exceeded or periodically ingestOptions.frequencyMillis
//Params: meterApiName: string, meterValue: number, meterTimeInMillis: number, customerId: string, dimensions: Map<string, string>
metering.meter("TypeScript-ApiCalls", j + 1, Date.now(), "123", dimensions);
metering.meter("TypeScript-Bandwidth", j + 1, Date.now(), "123", dimensions);
metering.meter("TypeScript-Transactions", j + 1, Date.now(), "123", dimensions);
metering.meter("TypeScript-CPU", j + 1, Date.now(), "123", dimensions);
}
//wait for messages and requests to API to complete
await metering.flush();
//perform graceful shutdown, flush, stop the timer
await metering.shutdown();
}
runIngest();
/**
* This sample illustrates how to setup customer details.
*/
export async function runCustomerDetails() {
//obtain your Amberflo API Key
const apiKey = 'my-api-key';
const traits = new Map<string, string>();
traits.set("stripeId", "cus_AJ6bY3VqcaLAEs");
traits.set("customerType", "Tech");
const metering = new Metering(apiKey, false);
await metering.addOrUpdateCustomerDetails('123', 'Dell', traits);
console.log('customer setup completed!');
}
runCustomerDetails();
export async function runUsage() {
//obtain your Amberflo API Key
const apiKey = 'my-api-key';
//initialize the usage client
const client = new UsageClient(apiKey);
// start date time represented as seconds since the Unix Epoch (1970-01-01T00:00:00Z) and using UTC.
// following is Start time for last 24 hours
const startTimeInSeconds = Math.ceil(((new Date().getTime()) - (24 * 60 * 60 * 1000)) / 1000);
let timeRange = new TimeRange();
timeRange.startTimeInSeconds = startTimeInSeconds;
// Example 1: group by customers for a specific meter and all customers
// setup usage query params
// visit following link for description of payload:
// https://amberflo.readme.io/docs/getting-started-sample-data#query-the-usage-data
let payload = new UsageApiPayload();
payload.meterApiName = 'TypeScript-ApiCalls';
payload.aggregation = AggregationType.sum;
payload.timeGroupingInterval = AggregationInterval.day;
//optional: group the result by customer
payload.groupBy = ["customerId"];
payload.timeRange = timeRange;
//Call the usage API
let jsonResult = await client.getUsage(payload);
// To understand the API response, visit following link:
// https://amberflo.readme.io/docs/getting-started-sample-data#query-the-usage-data
console.log(JSON.stringify(jsonResult, null, 4));
//Example 2: filter for a meter for specific customer
//setup usage query params
let payloadForFilteredCustomer = new UsageApiPayload();
payloadForFilteredCustomer.meterApiName = 'TypeScript-ApiCalls';
payloadForFilteredCustomer.aggregation = AggregationType.sum;
payloadForFilteredCustomer.timeGroupingInterval = AggregationInterval.day;
//optional: group the result by customer
payloadForFilteredCustomer.groupBy = ["customerId"];
//Filter result for a specific customer by ID
payloadForFilteredCustomer.filter = {customerId: ["123"]};
payloadForFilteredCustomer.timeRange = timeRange;
//Call the usage API
let jsonResultForFilteredCustomer = await client.getUsage(payloadForFilteredCustomer);
console.log(JSON.stringify(jsonResultForFilteredCustomer, null, 4));
}
runUsage();import { IngestOptions, Metering, FlushMode, UsageClient, UsageApiPayload, AggregationType, AggregationInterval, TimeRange } from "amberflo-metering-typescript";
/**
* This sample illustrates how to ingest your metering data into Amberflo in auto flush mode.
* Auto is the default mode.
*/
export async function runIngest() {
//obtain your Amberflo API Key
const apiKey = 'my-api-key';
//optional ingest options
let ingestOptions = new IngestOptions();
//set flush mode to auto. This is also the default, so this step is optional.
ingestOptions.flushMode = FlushMode.auto;
//Number of messages posted to the API. Default is 100.
ingestOptions.batchSize = 20;
//Frequency at which queued data will be sent to API. Default is 1000 milliseconds.
ingestOptions.frequencyMillis = 3000;
//Set to true to log debug statements
const debug = false;
const metering = new Metering(apiKey, debug, ingestOptions);
//initialize and start the ingestion client
metering.start();
//define dimesions for your meters
const dimensions = new Map<string, string>();
dimensions.set("region", "Midwest");
dimensions.set("customerType", "Tech");
let j = 0;
for (j = 0; j < 50; j++) {
let delay = new Promise(resolve => setTimeout(resolve, 100));
await delay;
//Queue meter messages for ingestion.
//In auto flush mode, queue will be flushed when ingestOptions.batchSize is exceeded or periodically ingestOptions.frequencyMillis
//Params: meterApiName: string, meterValue: number, meterTimeInMillis: number, customerId: string, dimensions: Map<string, string>
metering.meter("TypeScript-ApiCalls", j + 1, Date.now(), "123", dimensions);
metering.meter("TypeScript-Bandwidth", j + 1, Date.now(), "123", dimensions);
metering.meter("TypeScript-Transactions", j + 1, Date.now(), "123", dimensions);
metering.meter("TypeScript-CPU", j + 1, Date.now(), "123", dimensions);
}
//wait for messages and requests to API to complete
await metering.flush();
//perform graceful shutdown, flush, stop the timer
await metering.shutdown();
}
runIngest();
/**
* This sample illustrates how to setup customer details.
*/
export async function runCustomerDetails() {
//obtain your Amberflo API Key
const apiKey = 'my-api-key';
const traits = new Map<string, string>();
traits.set("stripeId", "cus_AJ6bY3VqcaLAEs");
traits.set("customerType", "Tech");
const metering = new Metering(apiKey, false);
await metering.addOrUpdateCustomerDetails('123', 'Dell', traits);
console.log('customer setup completed!');
}
runCustomerDetails();
export async function runUsage() {
//obtain your Amberflo API Key
const apiKey = 'my-api-key';
//initialize the usage client
const client = new UsageClient(apiKey);
// start date time represented as seconds since the Unix Epoch (1970-01-01T00:00:00Z) and using UTC.
// following is Start time for last 24 hours
const startTimeInSeconds = Math.ceil(((new Date().getTime()) - (24 * 60 * 60 * 1000)) / 1000);
let timeRange = new TimeRange();
timeRange.startTimeInSeconds = startTimeInSeconds;
// Example 1: group by customers for a specific meter and all customers
// setup usage query params
// visit following link for description of payload:
// https://amberflo.readme.io/docs/getting-started-sample-data#query-the-usage-data
let payload = new UsageApiPayload();
payload.meterApiName = 'TypeScript-ApiCalls';
payload.aggregation = AggregationType.sum;
payload.timeGroupingInterval = AggregationInterval.day;
//optional: group the result by customer
payload.groupBy = ["customerId"];
payload.timeRange = timeRange;
//Call the usage API
let jsonResult = await client.getUsage(payload);
// To understand the API response, visit following link:
// https://amberflo.readme.io/docs/getting-started-sample-data#query-the-usage-data
console.log(JSON.stringify(jsonResult, null, 4));
//Example 2: filter for a meter for specific customer
//setup usage query params
let payloadForFilteredCustomer = new UsageApiPayload();
payloadForFilteredCustomer.meterApiName = 'TypeScript-ApiCalls';
payloadForFilteredCustomer.aggregation = AggregationType.sum;
payloadForFilteredCustomer.timeGroupingInterval = AggregationInterval.day;
//optional: group the result by customer
payloadForFilteredCustomer.groupBy = ["customerId"];
//Filter result for a specific customer by ID
payloadForFilteredCustomer.filter = {customerId: ["123"]};
payloadForFilteredCustomer.timeRange = timeRange;
//Call the usage API
let jsonResultForFilteredCustomer = await client.getUsage(payloadForFilteredCustomer);
console.log(JSON.stringify(jsonResultForFilteredCustomer, null, 4));
}
runUsage();
Amberflo TypeScript SDK
Amberflo provides a simple and reliable way to integrate metering into your application.
This is the official TypeScript (and JavaScript) client for interacting with the Amberflo REST API.
Features
- Add and update customers
- Assign and update product plans for customers
- List customer invoices
- Generate customer portal sessions
- Add and retrieve prepaid orders
- Send meter events in asynchronous batches for high-throughput use cases, with optional manual flush
- Query usage data
Quick Start
- Install the SDK
3. Create a customer
import { CustomerDetailsClient, CustomerDetailsApiPayload } from "amberflo-metering-typescript";
// 1. Define some properties for this customer
const customerId = '123';
const customerName = 'Dell';
const traits = new Map<string, string>();
traits.set("customerType", "Tech");
// 2. Initialize metering client
const client = new CustomerDetailsClient(apiKey, debug);
// 3. Create or update the customer
const payload = new CustomerDetailsApiPayload(customerId, customerName, traits);
const createInStripe = true;
const customer = await client.add(payload, createInStripe);4. Ingest meter events
import { IngestOptions, Metering, FlushMode } from "amberflo-metering-typescript";
// 1. Instantiate metering client
const ingestOptions = new IngestOptions();
ingestOptions.flushMode = FlushMode.auto;
ingestOptions.batchSize = 20;
ingestOptions.frequencyMillis = 3000;
const metering = new Metering('my-api-key', false, ingestOptions);
// 2. Initialize and start the ingestion client
metering.start();
// Optional: Define dimesions for your meters
const dimensions = new Map<string, string>();
dimensions.set("region", "Midwest");
dimensions.set("customerType", "Tech");
// 3. Queue meter messages for ingestion.
metering.meter("TypeScript-ApiCalls", j + 1, Date.now(), "123", dimensions);
// 4. Perform graceful shutdown, flush, stop the timer
await metering.shutdown();5. Query usage
import {
AggregationInterval, AggregationType, TimeRange, UsageApiPayload, UsageClient,
} from "amberflo-metering-typescript";
// 1. Initialize the usage client
const client = new UsageClient(apiKey, debug);
// 2. Define a time range
const startTimeInSeconds = Math.ceil((new Date().getTime() - 24 * 60 * 60 * 1000) / 1000); // two days ago
const timeRange = new TimeRange(startTimeInSeconds);
// 3. Get overall usage report of a meter
const payload = new UsageApiPayload(
'TypeScript-ApiCalls',
AggregationType.sum,
AggregationInterval.day,
timeRange,
);
const result = await client.getUsage(payload);Using with JavaScript
This library can be used directly in JavaScript as well.
For instance, suppose you have the index.js bellow. You can run it with node index.js.
'use strict';
const apiKey = 'my-amberflo-api-key';
const { CustomerDetailsClient } = require('amberflo-metering-typescript');
async function main() {
const client = new CustomerDetailsClient(apiKey);
const customers = await client.list();
console.log(customers);
}
main();High throughput ingestion
Amberflo libraries are designed for high throughput environments. You can safely send hundreds of meter records per second, making it well-suited for web servers handling high volumes of requests.
Each call to record an event is queued in memory rather than sent immediately. These events are grouped into batches and flushed in the background, which significantly improves performance. Both the batch size and the flush interval can be customized.
Automatic flush: When operating with auto flush mode, which is the default, the messages will accumulate in the queue until either the batch size is reached or some period of time elapses. When either happens, the batch is sent.
Flush on demand: For example, at the end of your program, you'll want to flush to make sure there's nothing left in the queue. Calling this method will block the calling thread until there are no messages left in the queue. So, you'll want to use it as part of your cleanup scripts and avoid using it as part of the request lifecycle.
Documentation
General documentation on how to use Amberflo is available at Product Walktrough.
The full REST API documentation is available at API Reference .
Samples
Code samples covering different scenarios are available in the samples folder.
Reference
API Clients
import { IngestOptions, Metering, FlushMode } from "amberflo-metering-typescript";Customer
import { CustomerDetailsClient, CustomerDetailsApiPayload } from "amberflo-metering-typescript";import {
AggregationInterval,
AggregationType,
AllUsageApiPayload,
AllUsageGroupBy,
TimeRange,
UsageApiPayload,
UsageClient,
} from "amberflo-metering-typescript";import {
CustomerPortalSessionClient,
CustomerPortalSessionApiPayload
} from "amberflo-metering-typescript"import {
CustomerPrepaidOrderClient,
CustomerPrepaidOrderApiPayload,
BillingPeriod,
BillingPeriodInterval,
} from "amberflo-metering-typescript";import {
AllInvoicesQuery,
LatestInvoiceQuery,
InvoiceQuery,
CustomerProductInvoiceClient,
} from "amberflo-metering-typescript";import {
CustomerProductPlanClient,
CustomerProductPlanApiPayload,
} from "amberflo-metering-typescript";