Ecosyste.ms: Awesome

An open API service indexing awesome lists of open source software.

Awesome Lists | Featured Topics | Projects

https://github.com/Kikobeats/tom

tom ๐Ÿถ is a backoffice for your projects
https://github.com/Kikobeats/tom

Last synced: 5 days ago
JSON representation

tom ๐Ÿถ is a backoffice for your projects

Awesome Lists containing this project

README

        







![Last version](https://img.shields.io/github/tag/Kikobeats/tom-microservice.svg?style=flat-square)
[![Coverage Status](https://img.shields.io/coveralls/Kikobeats/tom-microservice.svg?style=flat-square)](https://coveralls.io/github/Kikobeats/tom-microservice)
[![NPM Status](https://img.shields.io/npm/dm/tom-microservice.svg?style=flat-square)](https://www.npmjs.org/package/tom-microservice)

> Stripe API version: [2024-09-30.acacia](https://docs.stripe.com/upgrades#2024-09-30.acacia).

**tom** ๐Ÿถ is a backoffice for your projects, oriented for doing things like:

- Handle [payments](#payment) workflow ( create customers, subscribe to plans) using Stripe.
- Send notifications ([email](notificationemail)/[Slack](notificationslack)/[Telegram](notificationtelegram)), even based on a template.
- Easy to extend & customize using [Event System](#event-system).
- Chainable actions, running them on [series](batchseries) or [parallel](batchparallel).
- Expose it over [HTTP](as-microservice) or as [CLI](from-cli).

## Install

```bash
$ npm install tom-microservice
```

## Usage

!> You can see a fully production ready example at [tom-example](https://github.com/Kikobeats/tom-example).

You can consume **tom** ๐Ÿถ from different ways.

### as microservice

Just execute `tom` and the server will start:

![](https://i.imgur.com/qrr67O7.png)

To see details of a command use `tom --help`

Also declare it as part of your npm scripts:

```json
{
"scripts": {
"start": "tom"
}
}
```

The microservice accepts command options in snake and camel case as body parameters.

### from CLI

You can execute `tom` as CLI to resolve the same functionality than the microservice endpoint:

```bash
$ tom --command=notification.email --templateId=welcome [email protected] --subject='hello world'
```

To view details for a command at any time use `tom --help`

### from Node.js

#### as process

You can interact with **tom** ๐Ÿถ from Node.js user code:

```js
// First of all you need to declare a configuration file.
const config = {/* See configuration section */}

// Pass configuration file to `tom-microservice` module.
const tom = require('tom-microservice')(config)

// Now you can access `tom` commands
const { payment, email } = tom
```

#### as HTTP router

Additionally, you can get the **tom** ๐Ÿถ HTTP router in standalone way:

```js
const { createRoutes } = require('tom-microservice')
const config = {/* See configuration section */}

const router = createRoutes(config, ({ tom, router, send }) => {
router
.get('/ping', (req, res) => send(res, 200, 'healthy'))
})
```

#### as HTTP server

You can also intialize **tom** ๐Ÿถ HTTP server from code:

```js
const { listen, createRoutes } = require('tom-microservice')

const config = {/* See configuration section */}

const router = createRoutes(config, ({ tom, router, send }) => {
router
.get('/ping', (req, res) => send(res, 200, 'healthy'))
})

listen(config, { routes })
```

## Configuration

!> Combine with [miconfig](https://www.npmjs.com/package/miconfig) for loading different settings based on environment.

All the **tom** ๐Ÿถ actions are based on a configuration file.

You can define the configuration file via:

- A `.tomrc` file, written in YAML or JSON, with optional extensions: .yaml/.yml/.json/.js.
- A `tom.config.js` file that exports an object.
- A `tom` key in your package.json file.

Just put your configuration in one of these places, **tom** ๐Ÿถ will automatically load it.

### Basic

!> Get a free email domain alias using [improvmx.com](https://improvmx.com) or [forwardemail.net](https://forwardemail.net/#/).

The minimal configuration necessary is related with your company.

```yaml
company:
name: microlink
site: microlink.io
link: https://microlink.io
logo: https://microlink.io/logo.png
email: [email protected]
copyright: Copyright ยฉ 2020 Microlink. All rights reserved.
```

For the rest, **tom** ๐Ÿถ will notify you on execution time if any specific configuration value is missing.

### Advanced

Additionally, you can setup some extra company fields to unlock certain **tom** workflows.

## Event System

!> Event System is only supported with `tom.config.js` configuration file.

Every time **tom** ๐Ÿถ execute a command successfully it will be emit an event:

```js
// Register stats for payment session
tom.on('payment:session', async data => {
const info = await sendAnalytics(data)
return info
})
```

The `data` received will be the last command execution output.

The events system are designed to allow you perform async actions.

If you return something, then it will be added into the final payload, that will be printed at the log level.

The events emitted are of 3 hierarchical types:

```js
// An event emitted for a command under a category
tom.on('payment:session', sendAnalytics)

// An event emitted under a category
tom.on('payment', sendAnalytics)

// Any event
tom.on('*', sendAnalytics)
```

## Commands

The commands define what things you can do with **tom** ๐Ÿถ.

Every command has his own field at [configuration](#configuration).

### payment

![](https://i.imgur.com/M4qyWPE.png)

It creates new customer and subcribe them to previous declared product plans, using Stripe.

Also, when is necessary, the subscription will be associated applying a tax rate based on the customer geolocation detected.

In addition, **tom** ๐Ÿถ will fill useful customer metadata inforomation whetever is possible (such ass IP Address, country, region, VAT rate, currency code, etc.)

#### payment:session

`POST`

It validates a Stripe [session](https://stripe.com/docs/api/checkout/sessions/object) previously created via [Stripe Checkout](https://stripe.com/docs/payments/checkout).

##### Data Parameters

###### sessionId

*Required*
type: `string`

The Stripe [session](https://stripe.com/docs/api/checkout/sessions/create) identifier.

#### payment:webhook

`POST`

![](https://i.imgur.com/NSc3h8R.png)

It exposes an endpoint to be triggered by [Stripe Webhook](https://stripe.com/docs/webhooks).

For using Stripe webhook you need to [setup webhook in your account](https://stripe.com/docs/webhooks/setup#configure-webhook-settings).

Click `+ Add Endpoint` and the URL should the URL where **tom** ๐Ÿถ is deployed end by `payment/webhook` e.g., `tom.localtunnel.me/microlink.io/payment/webhook`.

The events to send need to be at least contain `checkout.session.completed`.

If you want to test the webhook locally, you can use [localtunnel](https://github.com/localtunnel/localtunnel) to expose your local server.

The [webhook signature](https://stripe.com/docs/webhooks/signatures) will be checked to verify that the events were sent by Stripe.

### notification

It sends notification using different providers and transporters.

#### notification:email

`POST`

![](https://i.imgur.com/MmgFbS3.png)

It sends transactional emails based on templates defined.

Under non production scenario, you can use [ethereal](https://ethereal.email/) as transporter and it will be generate a preview of the email sent.

##### Data Parameters

###### templateId

type: `string`

If it is present, it will be generate `text` and `html` using the template.

###### text

The plain text content version of the email notification.

###### html

The HTML content version of the email notification.

###### from

type: `string`
default: `config.email.template[templateId].from`

The creator of the mail.

###### to

type: `array`
default: `company.email`

The recipients of the mail.

###### cc

type: `array`
default: `config.email.template[templateId].cc`

Carbon copy recipients of the mail.

###### bcc

type: `array`
default: `config.email.template[templateId].cc`

Blind carbon copy recipients of the mail.

###### subject

type: `string`
default: `config.email.template[templateId].subject`

The email subject.

###### attachments

type: `array`
default: `req.body.attachments`

An array of attachment objects (see [nodemailer#attachments](https://nodemailer.com/message/attachments/) for details).

Attachments can be used for embedding images as well.

#### notification:slack

`POST`

![](https://i.imgur.com/cy3KAJ3.png)

It sends a Slack message.

##### Data Parameters

###### webhook

*Required*
type: `string`

The [Incoming Webhook for Slack](https://api.slack.com/incoming-webhooks) used for sending the data.

###### templateId

Type: `string`

If it is present, it load a previous declared template.

###### text

type: `string`

The text of the message.

It supports some specific formatting things, see [formatting text in messages](https://api.slack.com/messaging/composing/formatting).

###### blocks

type: `object`

The [block structure](https://api.slack.com/reference/messaging/blocks) for creating rich messages, see [message layouts](https://api.slack.com/messaging/composing/layouts).

You can compose blocks structures quickly using [Slack Block Kit Builder](https://api.slack.com/tools/block-kit-builder).

#### notification:telegram

`POST`

It sends a telegram message to the specified chat id.

##### Data Parameters

###### templateId

type: `string`

If it is present, it will be generate `text` using the template.

###### chatId

*Required*
type: `number`

The Telegram chat id that will receive the message.

###### text

*Required*
type: `string`

The message that will be sent.

### batch

It runs more than one command in the same action.

#### batch:parallel

`POST`

It runs all the commands in paralell, without waiting until the previous function has completed.

If any of the commands throw an error, the rest continue running.

##### Data Parameters

The commands should be provided as a collection:

```
[
{
"command": "notification.email",
"templateId": "welcome",
"to": "[email protected]"
}, {
"command": "telegram",
"templateId": "welcome",
"to": "[email protected]",
"chatId": 1234
}
]
```

The field `command` determine what command should be used while the rest of parameters provided will be passed through the command.

#### batch:series

`POST`

It runs all the commands in series, each one running once the previous function has completed, each passing its result to the next.

If any of the commands throw an error, no more functions are run.

##### Data Parameters

The commands should be provided as a collection:

```
[
{
"command": "notification.email",
"templateId": "welcome",
"to": "[email protected]"
}, {
"command": "telegram",
"templateId": "welcome",
"to": "[email protected]",
"chatId": 1234
}
]
```

The field `command` determine what command should be used while the rest of parameters provided will be passed through the command.

## Environment Variables

Some credentials could be provided as environment variables as well

### general

#### TOM_ALLOWED_ORIGIN

Type: `boolean`|`string`|`regex`|`array`
Default: `'*'`

It configures the `Access-Control-Allow-Origin` CORS.

See [cors](https://github.com/expressjs/cors#configuration-options) for more information.

#### TOM_API_KEY

Type: `string`
Default: `undefined`

When you provide it, all request to **tom** ๐Ÿถ needs to be authenticated using `req.headers[`x-api-key`] or `req.query.apiKey` and the value provided.

You can use [randomkeygen.com](https://randomkeygen.com) for that.

#### TOM_PORT

Type: `number`
Default: `3000`

The port to uses for run the HTTP microservice.

### payment

#### TOM_STRIPE_KEY

Type: `string`
Default: `config.payment.stripe_key`

The [Stripe key](https://dashboard.stripe.com/account/apikeys) associated with your account.

#### TOM_STRIPE_WEBHOOK_SECRET

Type: `string`
Default: `config.payment.stripe_webhook_secret`

The [Stripe Webhook signature](https://stripe.com/docs/webhooks/signatures) for verifying events were sent by Stripe.

### notification

#### TOM_EMAIL_USER

Type: `string`
Default: `config.email.transporter.auth.user`

Your SMTP authentication user credential.

#### TOM_EMAIL_PASSWORD

Type: `string`
Default: `config.email.transporter.auth.password`

Your SMTP authentication password credential.

#### TOM_TELEGRAM_KEY

![](https://i.imgur.com/xRAqBs6.png)

Type: `string`
Default: `config.telegram.token`

Your [Telegram @BotFather token](https://core.telegram.org/bots#3-how-do-i-create-a-bot).

## License

**tom** ยฉ [Kiko Beats](https://kikobeats.com), released under the [MIT](https://github.com/Kikobeats/tom-microservice/blob/master/LICENSE.md) License.

Spaceman logo by [Nook Fulloption](https://thenounproject.com/term/spaceman/854189) from [the Noun Project](https://thenounproject.com/search/?q=dog%20spaceman&i=854189#).

Authored and maintained by Kiko Beats with help from [contributors](https://github.com/Kikobeats/tom-microservice/contributors).

> [kikobeats.com](https://kikobeats.com) ยท GitHub [@Kiko Beats](https://github.com/Kikobeats) ยท X [@Kikobeats](https://x.com/Kikobeats)