Skip to content

frain-dev/convoy.js

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

62 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Convoy SDK for JS

This is the Convoy JS SDK. This SDK contains methods for easily interacting with Convoy's API. Below are examples to get you started. You can view the full API Reference here

Installation

Install convoy.js

npm install convoy.js

Setup Client

Next, require the convoy module and set it up with your instance URL, API key, and project ID. Both the API key and project ID are available from your Project Settings page.

Your instance URL depends on where your project lives:

  • Convoy Cloud (US): https://us.getconvoy.cloud/api/v1
  • Convoy Cloud (EU): https://eu.getconvoy.cloud/api/v1
  • Self-hosted: https://your-instance/api/v1
// HTTP Client
const { Convoy } = require('convoy.js');
const convoy = new Convoy({ uri: 'https://us.getconvoy.cloud/api/v1', api_key: 'your_api_key', project_id: 'your_project_id' })

// Amazon SQS Client
const { Convoy } = require('convoy.js');
const convoy = new Convoy({ uri: 'https://us.getconvoy.cloud/api/v1', api_key: 'your_api_key', project_id: 'your_project_id', sqs_options: {} })


// Apache Kafka Client
const { Convoy } = require('convoy.js');
const convoy = new Convoy({ uri: 'https://us.getconvoy.cloud/api/v1', api_key: 'your_api_key', project_id: 'your_project_id', kafka_options: {} })

Create an Endpoint

An endpoint represents a target URL to receive events.

const endpointData = {
  name: 'Default Endpoint',
  url: "https://webhook.site/63baf442-bbf7-4d51-97e8-428ade404459",
  description: "Default Endpoint",
  secret: "endpoint-secret",
  events: ["*"]
};

const response = await convoy.endpoints.create(endpointData);

Store the Endpoint ID, so you can use it in subsequent requests for creating subscriptions or sending events.

Creating Subscriptions

const subscription = await convoy.subscriptions.create({
  endpoint_id: '01HD6PJBQ0WE842PZ3J8SHDC46',
  name: 'Test Subscription',
  type: 'api'
});

Sending an Event

You can send events to Convoy via HTTP or via any supported message broker. See here to see the list of supported brokers.

// Send an event to a single endpoint.
const eventData = {
  endpoint_id: endpointId, 
  event_type: "payment.success",
  data: { 
    event: "payment.success",
    data: {
      status: "Completed",
      description: "Transaction Successful",
      userID: "test_user_id808",
    }
  }
};

const response = await convoy.events.create(eventData);

// Fanout an event to multiple endpoints.
const fanoutData = {
  owner_id: "some_unique_key",
  event_type: "payment.success",
  data: {
    event: "payment.success",
    data: {
      status: "Completed",
      description: "Transaction Successful",
      userID: "test_user_id808",
    }
  }
};

const fanoutResponse = await convoy.events.createFanOutEvent(fanoutData);

// Broadcast an event to every endpoint in the project.
const broadcastData = {
  event_type: "payment.success",
  data: {
    status: "Completed",
    description: "Transaction Successful",
  }
};

const broadcastResponse = await convoy.events.createBroadcastEvent(broadcastData);

Note: The body struct used above is the same used for the message brokers below.

SQS

This library depends on aws-sdk-js-v3 to configure the SQS client.

// Send event to a single endpoint.
const data = await convoy.sqs.writeEvent({
    endpoint_id: '01HCF8X23MWXCEWR3K3HB7KAY8',
    event_type: '*',
    data: {
        event: "payment.success",
        data: {
            status: "Completed",
            description: "Transaction Successful",
            userID: "test_user_id808",
        }
    }
});

// Fanout an event to multiple endpoints.
const data = await convoy.sqs.writeEvent({
    owner_id: 'some_unique_key',
    event_type: '*',
    data: {
        event: "payment.success",
        data: {
            status: "Completed",
            description: "Transaction Successful",
            userID: "test_user_id808",
        }
    }
});

Kafka

This library depends on kafkajs to configure the Kafka client.

// Send event to a single endpoint.
const data = await convoy.kafka.writeEvent({
  endpoint_id: '01HCF8X23MWXCEWR3K3HB7KAY8',
  event_type: '*',
  data: { 
    event: "payment.success",
    data: {
      status: "Completed", 
      description: "Transaction Successful",
      userID: "test_user_id808",
    }
  }
});

// Fanout an event to multiple endpoints.
const data = await convoy.kafka.writeEvent({
  owner_id: 'some_unique_key',
  event_type: '*',
  data: { 
    event: "payment.success",
    data: {
      status: "Completed",
      description: "Transaction Successful",
      userID: "test_user_id808",
    }
  }
});

Verifying Webhooks

This client supports verifying simple and advanced webhook signatures.

// verfiy a simple signature
const webhook = new Webhook({
    header: '666060cbe1348bbc7ec98f4e93dda8eaaf11bbf283d6a2dd56e841b2ef12fcd465c846903f709942473e1442604798186746f04848702c44a773f80672de7b21',
    payload: { email: 'test@gmail.com', first_name: 'test', last_name: 'test' },
    secret: '8IX9njirDG',
    hash: 'sha512',
    encoding: 'hex',
});

webhook.verify()

// verfiy an advanced signature
const webhook = new Webhook({
    header: 't=2048976161,v1=afdb90313acfa15a3fc425755ae651a204947710315bb2a90bccaa87fce88998,v1=fLBDCBUiX5iIs0L5zfNq45h23EkX1HAMpFF+2lHrnes=',
    payload: { email: 'test@gmail.com' },
    secret: '8IX9njirDG',
    hash: 'sha256',
    encoding: 'base64',
});

expect(webhook.verify()).toBeTruthy();

Testing

npm run test

Contributing

Please see CONTRIBUTING for details.

Credits

License

The MIT License (MIT). Please see License File for more information.

Speakeasy-generated API client

The HTTP API client is generated from Convoy OpenAPI via Speakeasy. Webhook signature verification remains hand-written (src/webhook.ts) and is covered by shared tests/signature-vectors.json. See MIGRATION.md.

Summary

Convoy API Reference: Convoy is a fast and secure webhooks proxy. This document contains datastore's API specification.

Table of Contents

SDK Installation

Tip

To finish publishing your SDK to npm and others you must run your first generation action.

The SDK can be installed with either npm, pnpm, bun or yarn package managers.

NPM

npm add https://github.com/frain-dev/convoy.js

PNPM

pnpm add https://github.com/frain-dev/convoy.js

Bun

bun add https://github.com/frain-dev/convoy.js

Yarn

yarn add https://github.com/frain-dev/convoy.js

Note

This package is published with CommonJS and ES Modules (ESM) support.

Requirements

For supported JavaScript runtimes, please consult RUNTIMES.md.

SDK Example Usage

Example

import { Convoy } from "convoy.js";

const convoy = new Convoy({
  apiKeyAuth: "<YOUR_BEARER_TOKEN_HERE>",
});

async function run() {
  const result = await convoy.projects.getProjects("<id>");

  console.log(result);
}

run();

Authentication

Per-Client Security Schemes

This SDK supports the following security scheme globally:

Name Type Scheme
apiKeyAuth http HTTP Bearer

To authenticate with the API the apiKeyAuth parameter must be set when initializing the SDK client instance. For example:

import { Convoy } from "convoy.js";

const convoy = new Convoy({
  apiKeyAuth: "<YOUR_BEARER_TOKEN_HERE>",
});

async function run() {
  const result = await convoy.projects.getProjects("<id>");

  console.log(result);
}

run();

Available Resources and Operations

Available methods
  • bulkOnboard - Bulk onboard endpoints with subscriptions

Standalone functions

All the methods listed above are available as standalone functions. These functions are ideal for use in applications running in the browser, serverless runtimes or other environments where application bundle size is a primary concern. When using a bundler to build your application, all unused functionality will be either excluded from the final bundle or tree-shaken away.

To read more about standalone functions, check FUNCTIONS.md.

Available standalone functions

Retries

Some of the endpoints in this SDK support retries. If you use the SDK without any configuration, it will fall back to the default retry strategy provided by the API. However, the default retry strategy can be overridden on a per-operation basis, or across the entire SDK.

To change the default retry strategy for a single API call, simply provide a retryConfig object to the call:

import { Convoy } from "convoy.js";

const convoy = new Convoy({
  apiKeyAuth: "<YOUR_BEARER_TOKEN_HERE>",
});

async function run() {
  const result = await convoy.projects.getProjects("<id>", {
    retries: {
      strategy: "backoff",
      backoff: {
        initialInterval: 1,
        maxInterval: 50,
        exponent: 1.1,
        maxElapsedTime: 100,
      },
      retryConnectionErrors: false,
    },
  });

  console.log(result);
}

run();

If you'd like to override the default retry strategy for all operations that support retries, you can provide a retryConfig at SDK initialization:

import { Convoy } from "convoy.js";

const convoy = new Convoy({
  retryConfig: {
    strategy: "backoff",
    backoff: {
      initialInterval: 1,
      maxInterval: 50,
      exponent: 1.1,
      maxElapsedTime: 100,
    },
    retryConnectionErrors: false,
  },
  apiKeyAuth: "<YOUR_BEARER_TOKEN_HERE>",
});

async function run() {
  const result = await convoy.projects.getProjects("<id>");

  console.log(result);
}

run();

Error Handling

ConvoyError is the base class for all HTTP error responses. It has the following properties:

Property Type Description
error.message string Error message
error.statusCode number HTTP response status code eg 404
error.headers Headers HTTP response headers
error.body string HTTP body. Can be empty string if no body is returned.
error.rawResponse Response Raw HTTP response
error.data$ Optional. Some errors may contain structured data. See Error Classes.

Example

import { Convoy } from "convoy.js";
import * as errors from "convoy.js/models/errors";

const convoy = new Convoy({
  apiKeyAuth: "<YOUR_BEARER_TOKEN_HERE>",
});

async function run() {
  try {
    const result = await convoy.projects.getProjects("<id>");

    console.log(result);
  } catch (error) {
    // The base class for HTTP error responses
    if (error instanceof errors.ConvoyError) {
      console.log(error.message);
      console.log(error.statusCode);
      console.log(error.body);
      console.log(error.headers);

      // Depending on the method different errors may be thrown
      if (error instanceof errors.GetProjectsBadRequestError) {
        console.log(error.data$.message); // string
        console.log(error.data$.status); // boolean
        console.log(error.data$.data); // { [k: string]: any }
      }
    }
  }
}

run();

Error Classes

Primary error:

  • ConvoyError: The base class for HTTP error responses.
Less common errors (211)

Network errors:

Inherit from ConvoyError:

* Check the method documentation to see if the error is applicable.

Server Selection

Select Server by Index

You can override the default server globally by passing a server index to the serverIdx: number optional parameter when initializing the SDK client instance. The selected server will then be used as the default on the operations that use it. This table lists the indexes associated with the available servers:

# Server Description
0 https://us.getconvoy.cloud/api US Region
1 https://eu.getconvoy.cloud/api EU Region

Example

import { Convoy } from "convoy.js";

const convoy = new Convoy({
  serverIdx: 0,
  apiKeyAuth: "<YOUR_BEARER_TOKEN_HERE>",
});

async function run() {
  const result = await convoy.projects.getProjects("<id>");

  console.log(result);
}

run();

Override Server URL Per-Client

The default server can also be overridden globally by passing a URL to the serverURL: string optional parameter when initializing the SDK client instance. For example:

import { Convoy } from "convoy.js";

const convoy = new Convoy({
  serverURL: "https://eu.getconvoy.cloud/api",
  apiKeyAuth: "<YOUR_BEARER_TOKEN_HERE>",
});

async function run() {
  const result = await convoy.projects.getProjects("<id>");

  console.log(result);
}

run();

Custom HTTP Client

The TypeScript SDK makes API calls using an HTTPClient that wraps the native Fetch API. This client is a thin wrapper around fetch and provides the ability to attach hooks around the request lifecycle that can be used to modify the request or handle errors and response.

The HTTPClient constructor takes an optional fetcher argument that can be used to integrate a third-party HTTP client or when writing tests to mock out the HTTP client and feed in fixtures.

The following example shows how to:

  • route requests through a proxy server using undici's ProxyAgent
  • use the "beforeRequest" hook to add a custom header and a timeout to requests
  • use the "requestError" hook to log errors
import { Convoy } from "convoy.js";
import { ProxyAgent } from "undici";
import { HTTPClient } from "convoy.js/lib/http";

const dispatcher = new ProxyAgent("http://proxy.example.com:8080");

const httpClient = new HTTPClient({
  // 'fetcher' takes a function that has the same signature as native 'fetch'.
  fetcher: (input, init) =>
    // 'dispatcher' is specific to undici and not part of the standard Fetch API.
    fetch(input, { ...init, dispatcher } as RequestInit),
});

httpClient.addHook("beforeRequest", (request) => {
  const nextRequest = new Request(request, {
    signal: request.signal || AbortSignal.timeout(5000)
  });

  nextRequest.headers.set("x-custom-header", "custom value");

  return nextRequest;
});

httpClient.addHook("requestError", (error, request) => {
  console.group("Request Error");
  console.log("Reason:", `${error}`);
  console.log("Endpoint:", `${request.method} ${request.url}`);
  console.groupEnd();
});

const sdk = new Convoy({ httpClient: httpClient });

Debugging

You can setup your SDK to emit debug logs for SDK requests and responses.

You can pass a logger that matches console's interface as an SDK option.

Warning

Beware that debug logging will reveal secrets, like API tokens in headers, in log messages printed to a console or files. It's recommended to use this feature only during local development and not in production.

import { Convoy } from "convoy.js";

const sdk = new Convoy({ debugLogger: console });

About

Convoy SDK for JS

Resources

License

Contributing

Stars

12 stars

Watchers

2 watching

Forks

Packages

 
 
 

Contributors