Skip to content

Commit

Permalink
Fastify amplitude decorator (#61)
Browse files Browse the repository at this point in the history
* Amplitude fastify decorator

* doc changes
  • Loading branch information
CarlosGamero authored Jul 6, 2023
1 parent 296da8f commit d63dc12
Show file tree
Hide file tree
Showing 4 changed files with 33 additions and 18 deletions.
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -155,7 +155,7 @@ To add this plugin to your Fastify instance, register it with the following conf
* `apiUsageTracking` (optional): You can use this callback to generate an event that will automatically be sent for tracking API usage. Non-specification of this feature will lead to disabling of API tracking.
* `plugins` (optional): This feature allows you to expand the plugin's functionality, from altering event properties to relaying to third-party APIs. To learn more, visit [this link](https://www.docs.developers.amplitude.com/data/sdks/typescript-node/#plugins).

While `apiUsageTracking` can be configured for automatic tracking of API usage, the `amplitudeTrack` method allows you to send events to Amplitude whenever necessary.
The plugin decorates your Fastify instance with a `Amplitude`, which you can inject and use the `track` method on it to send events whenever you need

> 📘 To ensure optimal functionality with this plugin, you may need to incorporate Amplitude types into your development dependencies.
> ```
Expand Down
2 changes: 1 addition & 1 deletion lib/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ export type { PublicHealthcheckPluginOptions, HealthCheck } from './plugins/publ

export {
amplitudePlugin,
amplitudeTrack,
Amplitude,
type AmplitudeConfig,
type CreateApiTrackingEventFn,
} from './plugins/amplitudePlugin'
6 changes: 3 additions & 3 deletions lib/plugins/amplitudePlugin.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import type { BaseEvent, EnrichmentPlugin, Result, Event } from '@amplitude/anal
import type { FastifyInstance } from 'fastify'
import fastify from 'fastify'

import { amplitudePlugin, amplitudeTrack } from './amplitudePlugin'
import { amplitudePlugin } from './amplitudePlugin'

describe('amplitudePlugin', () => {
let app: FastifyInstance
Expand Down Expand Up @@ -57,7 +57,7 @@ describe('amplitudePlugin', () => {
})

// When
const result = await amplitudeTrack({ event_type: 'event not tracked' }).promise
const result = await app.amplitude.track({ event_type: 'event not tracked' }).promise

// Then
expect(result).toBeNull()
Expand All @@ -81,7 +81,7 @@ describe('amplitudePlugin', () => {

// When
const event: BaseEvent = { event_type: 'event tracked' }
const response = await amplitudeTrack(event).promise
const response = await app.amplitude.track(event).promise

// Then
expect(response).toBe(trackResponse)
Expand Down
41 changes: 28 additions & 13 deletions lib/plugins/amplitudePlugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,14 +14,19 @@ import type {
} from 'fastify'
import fp from 'fastify-plugin'

let pluginConfig: AmplitudeConfig | null = null
declare module 'fastify' {
interface FastifyInstance {
amplitude: Amplitude
}
}

async function plugin(
fastify: FastifyInstance,
config: AmplitudeConfig,
next: (err?: Error) => void,
) {
pluginConfig = config
const amplitudeInstance = new Amplitude(config.isEnabled)
fastify.decorate('amplitude', amplitudeInstance)

if (!config.isEnabled) {
return next()
Expand All @@ -34,7 +39,7 @@ async function plugin(
await init(config.apiKey, config.options).promise

if (config.apiUsageTracking) {
enableApiUsageTracking(fastify, config.apiUsageTracking)
enableApiUsageTracking(fastify, amplitudeInstance, config.apiUsageTracking)
}
if (config.plugins) {
// @ts-expect-error
Expand All @@ -46,14 +51,15 @@ async function plugin(

function enableApiUsageTracking(
fastify: FastifyInstance,
amplitude: Amplitude,
eventCreationFn: CreateApiTrackingEventFn,
) {
fastify.addHook(
'onResponse',
(req: FastifyRequest, res: FastifyReply, done: HookHandlerDoneFunction) => {
const event = eventCreationFn(req, res)
if (event) {
amplitudeTrack(event)
amplitude.track(event)
}
return done()
},
Expand Down Expand Up @@ -114,12 +120,21 @@ export const amplitudePlugin = fp<AmplitudeConfig>(plugin, {
name: 'amplitude-plugin',
})

/**
* Sends the given event to Amplitude
*
* @param event Event to send to amplitude. Please check
* [this](https://amplitude.github.io/Amplitude-TypeScript/interfaces/_amplitude_analytics_node.Types.BaseEvent.html)
* to get more info about the BaseEvent type
*/
export const amplitudeTrack = (event: BaseEvent): AmplitudeReturn<Result | null> =>
pluginConfig?.isEnabled ? track(event) : { promise: Promise.resolve(null) }
export class Amplitude {
private readonly isEnabled: boolean

constructor(isEnabled: boolean) {
this.isEnabled = isEnabled
}

/**
* Sends the given event to Amplitude
*
* @param event Event to send to amplitude. Please check
* [this](https://amplitude.github.io/Amplitude-TypeScript/interfaces/_amplitude_analytics_node.Types.BaseEvent.html)
* to get more info about the BaseEvent type
*/
public track(event: BaseEvent): AmplitudeReturn<Result | null> {
return this.isEnabled ? track(event) : { promise: Promise.resolve(null) }
}
}

0 comments on commit d63dc12

Please sign in to comment.