npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

amberflo-metering-typescript

v2.6.0

Published

Amberflo metering client for TypeScript

Downloads

3,186

Readme

amberflo-metering-typescript

Amberflo is the simplest way to integrate metering into your application.

This is the official TypeScript (and JavaScript) client that wraps the Amberflo REST API.

:heavy_check_mark: Features

  • Add and update customers
  • Assign and update product plans to customers
  • List invoices of a customer
  • Get a new customer portal session for a customer
  • Add and list prepaid orders to customers
  • Send meter events in asynchronous batches for high throughput (with optional flush on demand)
  • Query usage

:rocket: Quick Start

  1. Sign up for free and get an API key.

  2. Install the SDK

npm install --save amberflo-metering-typescript
  1. 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);
  1. 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();
  1. 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);

With JavaScript

This library can also be used directly with JavaScript. For instance:

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();

Then you can run it with: node index.js.

:zap: High throughput ingestion

Amberflo.io libraries are built to support high throughput environments. That means you can safely send hundreds of meter records per second. For example, you can chose to deploy it on a web server that is serving hundreds of requests per second.

However, every call does not result in a HTTP request, but is queued in memory instead. Messages are batched and flushed in the background, allowing for much faster operation. The size of batch and rate of flush 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.

:book: Documentation

General documentation on how to use Amberflo is available at Product Walkthrough.

The full REST API documentation is available at API Reference.

:scroll: Samples

Code samples covering different scenarios are available in the samples folder.

:bookmark_tabs: Reference

API Clients

Ingest

import { IngestOptions, Metering, FlushMode } from "amberflo-metering-typescript";

Customer

import { CustomerDetailsClient, CustomerDetailsApiPayload } from "amberflo-metering-typescript";

Usage

import {
    AggregationInterval,
    AggregationType,
    AllUsageApiPayload,
    AllUsageGroupBy,
    TimeRange,
    UsageApiPayload,
    UsageClient,
} from "amberflo-metering-typescript";

Customer Portal Session

import {
    CustomerPortalSessionClient,
    CustomerPortalSessionApiPayload
} from "amberflo-metering-typescript"

Customer Prepaid Order

import {
    CustomerPrepaidOrderClient,
    CustomerPrepaidOrderApiPayload,
    BillingPeriod,
    BillingPeriodInterval,
} from "amberflo-metering-typescript";

Customer Product Invoice

import {
    AllInvoicesQuery,
    LatestInvoiceQuery,
    InvoiceQuery,
    CustomerProductInvoiceClient,
} from "amberflo-metering-typescript";

Customer Product Plan

import {
    CustomerProductPlanClient,
    CustomerProductPlanApiPayload,
} from "amberflo-metering-typescript";

Request Retry

All clients accept a retry parameter to enable retrying idempotent requests on 5xx or network failures. This uses the default configuration of axios-retry.

Further customization of retry logic is possible by manually patching the client.axiosInstance attribute of a client, as described in the axios-retry documentation.