tom-microservice

3.9.11 • Public • Published



Last version Coverage Status NPM Status

Stripe API version: 2023-10-16

tom 🐶 is a backoffice for your projects, oriented for doing things like:

Install

$ npm install tom-microservice

Usage

!> You can see a fully production ready example at tom-example.

You can consume tom 🐶 from different ways.

as microservice

Just execute tom and the server will start:

To see details of a command use tom --help

Also declare it as part of your npm scripts:

{
  "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:

$ tom --command=notification.email --templateId=welcome --to=hello@kikobeats.com --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:

// 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:

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:

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 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 or forwardemail.net.

The minimal configuration necessary is related with your company.

company:
  name: microlink
  site: microlink.io
  link: https://microlink.io
  logo: https://microlink.io/logo.png
  email: hello@microlink.io
  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.

Tax Rates

!> Open an issue for requesting more tax rates strategies!

If you define country and tax_type in your company configuration, then customers bills will generated considering the company tax rate declared

company:
  # ... rest of company configuration
  country: es
  tax_type: vatmoss

Current strategies supported are:

  • vatmos: Use VATMOSS EU VAT Compliance for Digital Products.

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:

// 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:

// 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.

payment

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 previously created via Stripe Checkout.

Data Parameters
sessionId

Required type: string

The Stripe session identifier.

payment:webhook

POST

It exposes an endpoint to be triggered by Stripe Webhook.

For using Stripe webhook you need to setup webhook in your account.

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 to expose your local server.

The webhook signature will be checked to verify that the events were sent by Stripe.

notification

It sends notification using different providers and transporters.

notification:email

POST

It sends transactional emails based on templates defined.

Under non production scenario, you can use ethereal 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 for details).

Attachments can be used for embedding images as well.

notification:slack

POST

It sends a Slack message.

Data Parameters
webhook

Required type: string

The Incoming Webhook for Slack 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.

blocks

type: object

The block structure for creating rich messages, see message layouts.

You can compose blocks structures quickly using Slack 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": "hello@kikobeats.com"
	}, {
		"command": "telegram",
		"templateId": "welcome",
		"to": "hello@kikobeats.com",
		"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": "hello@kikobeats.com"
	}, {
		"command": "telegram",
		"templateId": "welcome",
		"to": "hello@kikobeats.com",
		"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 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 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 associated with your account.

TOM_STRIPE_WEBHOOK_SECRET

Type: string Default: config.payment.stripe_webhook_secret

The Stripe Webhook signature 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

Type: string Default: config.telegram.token

Your Telegram @BotFather token.

License

tom © Kiko Beats, released under the MIT License.

Spaceman logo by Nook Fulloption from the Noun Project.

Authored and maintained by Kiko Beats with help from contributors.

kikobeats.com · GitHub @Kiko Beats · Twitter @Kikobeats

Package Sidebar

Install

npm i tom-microservice

Homepage

tom.js.org

Weekly Downloads

8

Version

3.9.11

License

MIT

Unpacked Size

45.4 kB

Total Files

32

Last publish

Collaborators

  • kikobeats