# songwhip-events

A service that ingests events from different services in the Songwhip stack and forwards them on to a variety of endpoints:

- Google Analytics
- `songwhip-analytics`
- Slack
- Amplitude

The service is deployed to [Vercel Edge Functions](https://vercel.com/docs/functions/edge-functions) which runs on a limited Javascript runtime.

`songwhip-events` is cool because it keeps your client code _super_ simple and lightweight. Just fire-n-forget via HTTP and let `songwhip-events` take care of ensuring events arrive at the correct endpoint in the correct format.

```js
fetch('https://events.songwhip.com/send', {
  method: 'POST',

  body: JSON.stringify({
    context: {
      url: 'https://songwhip.com/edsheeran',
      env: 'production',
    },

    event: {
      type: 'page-view',
      pageType: 'artist',
      artistId: 123,
    },
  }),
});
```

## Prerequisites

- Node.js configured repo\
  https://www.notion.so/Node-js-project-setup-guide-86feadffeb304962b06e6b1bb8f09213
- Vercel CLI (for `yarn dev`)

## Running

- Create a `.env` file based on the `.env.shadow` template
- Run `yarn dev` to spin up Vercel dev server

## Testing

- Run `yarn test` to check for format, lint or types errors

## Defining event `env`

All events should be sent with an `context.env` value; this should either be `staging` or `production`. The `env` is used to decide which final endpoint an event is sent to. For example we have a separate `songwhip-analytics` store for each env.

## The (optional) JS client

`songwhip-events` also exposes a JS client that can be installed via `npm`. You don't need the client to push events but it comes with typings to check event objects are formatted correctly. It also wraps `navigator.sendBeacon()` for sending front-end events.

### Installing the client in other repos

To install Github Packages from `theorchard` you'll need to first follow the npm setup guide in Notion:\
https://www.notion.so/JavaScript-Package-Setup-9553d5d491c94835aa787fdf0fc4838d

Then you can run:

```bash
yarn add @theorchard/songwhip-events
```

### Usage

```js
import { songwhipEventApi } from '@theorchard/songwhip-events';

// send an event
await songwhipEventApi({
  context: {
    url: 'https://songwhip.com/edsheeran',
    env: 'production',
  },

  event: {
    type: 'page-view',
    pageType: 'artist',
    artistId: 123,
  },
});
```

### Publishing a new JS client version

If you need to make changes to the client library, land your code as normal, then run the [Publish version Github Action](https://github.com/theorchard/songwhip-events/actions/workflows/publishVersion.yml). This will stamp a new `npm version` and publish it to [Github Packages](https://github.com/theorchard/songwhip-events/packages/1087744).
