Code Monkey home page Code Monkey logo

typeorm-webhook-extensions's Introduction

TypeORM Webhook Extensions

Simply add webhooks to your TypeORM entities. Send events to a webhook-configured endpoint(s) after a TypeORM entity is loaded, removed, updated, or inserted.

Usage

Installation

npm install --save typeorm-webhook-extensions

or

yarn add typeorm-webhook-extensions

Decorate TypeORM Models with @Webhook

import { Entity } from 'typeorm';
import webhookExtension, { Webhook } from 'typeorm-webhook-extensions';

@Entity('users')
@Webhook({
  sendOnInsert: true,
  sendOnLoad: true,
  sendOnRemove: true,
  sendOnUpdate: true,
  onError: (error) => { console.log(error); },
  onSuccess: (endpoint, status, payload) => { console.log(endpoint, status, payload )},
})
class User {
  @PrimaryGeneratedColumn()
  public id: number = 0;

  @Column()
  public username: string = '';

  @Column()
  public password: string = '';
}

The @Webhook decorator takes arguments that match the WebhookOptions interface:

interface WebhookOptions {
  sendOnLoad?: boolean | WebhookFormatter;
  sendOnUpdate?: boolean | WebhookFormatter;
  sendOnRemove?: boolean | WebhookFormatter;
  sendOnInsert?: boolean | WebhookFormatter;
  webhookEndpoint?: string | string | WebhookEndpointBuilder;
  okStatuses?: number[];
  onError?: WebhookErrorHandler;
  onSuccess?: WebhookActionLogger;
};

WebhookEndpointBuilder is an asynchronous function that returns Promise<string | string[]>. If you need to send events to different webhook URLs based on information in the entity, this is approximately how you can do so:

const getWebhookEndpoints = async (entity: any) => {
  const companyEndpoints = await getConnection().query(`SELECT webhook_endpoint FROM companies WHERE owner_id=${entity.id};`);
  return companyEndpoints.map(company => company.webhook_endpoint);
}

If true is passed to sendOnLoad, sendOnUpdate, sendOnRemove, or sendOnInsert, a payload containing the non-function properties from your entity along with webhookType will be sent to your specified webhook. Optionally, you may pass a WebhookFormatter function in for any of these options. The WebhookFormatter receives the instance of the entity as its sole argument. For example, this would exclude the (hopefully hashed) password from being sent to the webhook endpoint:

...
@Webhook({
  sendOnLoad: (entity => ({
    event_type: 'load',
    resource: 'user',
    username: entity.username,
  })),
})

Change Global Options

Some options can be configured globally for all decorated TypeORM entities. Here is an example of how you can change these options:

// Import as above
webhookExtension.setOptions(<TypeORMWebhookExtensionsOptions> {
  okStatuses: [200, 201], // HTTP status codes that signify the webhook server successfully received the event
  webhookEndpoint: 'https://localhost/api/webhook', // The URL to send webhook events to
  onError: (error) => { console.log(error); }, // A callback to run in the event that the webhook event does not successfully send
  onSuccess: (endpoint, status, payload) => { console.log(endpoint, status, payload )}, // A callback to run in the event that the webhook event successfully sends
});

TypeScript Configuration

{
  "target": "es2015", // at least
  "experimentalDecorators": true
}

Note

Be sure to set up a webhookEndpoint, either on the default export singleton or in the webhook decorator's options.

Contribution

Feel free to contribute by forking this repository, making, testing, and building your changes, then opening a pull request. Please try to maintain a uniform code style.

typeorm-webhook-extensions's People

Contributors

dependabot-preview[bot] avatar joshuaslate avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar

Watchers

 avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.