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

@janiscommerce/webhook-trigger

v2.1.2

Published

A wrapper for webhooks integration

Downloads

714

Readme

Webhook Trigger

Build Status Coverage Status npm version

A wrapper for webhooks integration

:inbox_tray: Installation

npm install @janiscommerce/webhook-trigger

:hammer: Usage

IMPORTANT The JANIS_SERVICE_NAME environment variable is required to be set as the current service code. The JANIS_WEBHOOKS_QUEUE_URL environment variable is required to be set as the SQS Queue URL of the Webhooks service.

Permissions

You need to add permissions to send messages to the Webhooks SQS Queue to your execution role. If you run your service in AWS Lambda with Serverless Helper, you can import and use the serverlessHelperHooks function to add proper permissions.

The following is an example of implementation:

const { helper } = require('sls-helper');
const { serverlessHelperHooks } = require('@janiscommerce/webhook-trigger');

module.exports = helper({
	hooks: [
		...serverlessHelperHooks()
	]
});

If not, be sure to give your execution role the permission to perform sqs:SendMessage on the SQS Queue.

Service registration

Service registration is the process where a service publishes its triggers so the user can create a Webhook subscription for them.

First of all, you need to create a triggers YAML definition file. The recommended path is ./webhooks/triggers.yml.

This file must have the following structure:

- entity: entity-name
  eventName: some-event
- entity: other-entity-name
  eventName: other-event

Every event that your service triggers must be declared here so users can subscribe to it.

To implement the subscription for your service, simply create the registration lambda with the following content:

// In src/lambda/WebhookTriggersRegistration/index.js
'use strict';

const path = require('path');
const { RegistrationLambda } = require('@janiscommerce/webhook-trigger');

module.exports.handler = RegistrationLambda(path.join(__dirname, '../../../webhooks/triggers.yml'));

IMPORTANT: Validate that the path to your triggers definition file is correct!

Then, add your lambda function serverless config file. If you are using serverless-helper here is the function definition:

["function", {
	"functionName": "WebhookTriggersRegistration",
	"handler": "src/lambda/WebhookTriggersRegistration/index.handler",
	"description": "Webhook Triggers Registration",
	"layers": []
}]

Then you can test your registration by executing the following:

npx sls invoke local -f WebhookTriggersRegistration

Once you have everything validated, you should include this invocation in you CI/CD pipeline:

aws lambda invoke --function-name <ServiceName>-<stage>-WebhookTriggersRegistration output --log-type Tail --query 'LogResult' --output text | base64 -d

If you want to register your triggers in a different way, the Registration class is also exported by this package.

Event triggering

Every time an event happens, you have to trigger it. For that you need to provide the clientCode, entity and eventName associated to the event. Additionally, you must provide the content of the event hook. This content must be a string of approximately less than 240Kb. In case you provide an object instead if a string, it will be JSON encoded for you. This content will be the request body that will be sent to the subscribers.

The WebhookTrigger.send signature is the following (typings are included in the package for intellisense):

type SendMessageSuccess = {
    success: true;
    messageId: string;
};
type SendMessageError = {
    success: false;
    message: object;
    errorMessage: string;
};

WebhookTrigger.send(clientCode: string, entity: string, eventName: string, content: string | object): Promise<SendMessageSuccess | SendMessageError>

This method only rejects when required env vars are missing, to make easier to detect this issues on early testing. Errors ocurring at network or queue levels will be reported as SendMessageError in the return value.

:new: Batch event triggering

Starting in v2, it's possible to trigger multiple events at once. To do so, use the WebhookTrigger.sendBatch method, passing an array of events.

The WebhookTrigger.sendBatch signature is the following (typings are included in the package for intellisense):

type WebhookEvent = {
    clientCode: string;
    entity: string;
    eventName: string;
    content: string | {
        [x: string]: any;
    };
};

type SendMessageBatchResult = {
    successCount: number;
    failedCount: number;
    outputs: (SendMessageSuccess | SendMessageError)[];
};

WebhookTrigger.sendBatch(events: WebhookEvent[]): Promise<SendMessageBatchResult>

This method only rejects when required env vars are missing or the events sent are not an array, to make easier to detect this issues on early testing. Errors ocurring at network, queue or individual event validation levels will be reported as a failedCount and the detail will be present as a SendMessageError in the outputs property.

:computer: Examples

Send an event when an order is created

const WebhookTrigger = require('@janiscommerce/webhook-trigger');

await WebhookTrigger.send('currentClientCode', 'order', 'created', {
	id: 'd555345345345aa67a342a55',
	dateCreated: new Date(),
	amount: 10.40
});

Send multiple events when multiple orders are dispatched (you could even send events for more than one clientCode and/or each with a different eventName)

const WebhookTrigger = require('@janiscommerce/webhook-trigger');

await WebhookTrigger.send([
	{
		clientCode: 'currentClientCode',
		entity: 'order',
		eventName: 'dispatched',
		content: {
			id: 'd555345345345aa67a342a55',
			dateCreated: new Date(),
			amount: 10.40
		}
	},
	{
		clientCode: 'currentClientCode',
		entity: 'order',
		eventName: 'dispatched',
		content: {
			id: 'e55a3a53e5645aa67a34254a',
			dateCreated: new Date(),
			amount: 32.5
		}
	}
]);