2022-09-07 10:14:34 +00:00
|
|
|
import got, { RequestError } from 'got'
|
2022-09-14 19:08:22 +00:00
|
|
|
import { BaseContext } from 'koa'
|
2022-09-07 10:14:34 +00:00
|
|
|
|
|
|
|
interface PlausibleEvent {
|
|
|
|
eventName: string
|
|
|
|
props?: Record<string, string | number | boolean>
|
|
|
|
}
|
|
|
|
|
|
|
|
export const plausibleEvent = (
|
|
|
|
ctx: BaseContext,
|
|
|
|
{ eventName, props }: PlausibleEvent
|
|
|
|
) => {
|
|
|
|
const userAgent = ctx.headers['user-agent'] ?? ''
|
|
|
|
const xForwardedFor =
|
|
|
|
(Array.isArray(ctx.headers['x-forwarded-for'])
|
|
|
|
? ctx.headers['x-forwarded-for'][0]
|
|
|
|
: ctx.headers['x-forwarded-for']) ?? ''
|
|
|
|
const referer = ctx.headers.referer ?? ''
|
|
|
|
const url = ctx.href
|
|
|
|
|
|
|
|
return got('https://plausible.io/api/event', {
|
|
|
|
method: 'POST',
|
|
|
|
headers: {
|
|
|
|
'user-agent': userAgent,
|
|
|
|
'x-forwarded-for': xForwardedFor,
|
|
|
|
},
|
|
|
|
json: {
|
|
|
|
domain: 'mon-entreprise.urssaf.fr/api',
|
|
|
|
name: eventName,
|
|
|
|
referer,
|
|
|
|
url,
|
|
|
|
props,
|
|
|
|
},
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
2022-09-14 19:08:22 +00:00
|
|
|
export const plausibleMiddleware = async (
|
|
|
|
ctx: BaseContext,
|
|
|
|
next: () => Promise<unknown>
|
|
|
|
) => {
|
2022-09-14 17:24:16 +00:00
|
|
|
if (process.env.NODE_ENV !== 'production') {
|
2022-09-14 19:08:22 +00:00
|
|
|
return await next()
|
2022-09-14 17:24:16 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
void plausibleEvent(ctx, { eventName: 'pageview' }).catch((err) => {
|
|
|
|
const error = err as RequestError
|
2022-09-15 08:15:41 +00:00
|
|
|
// eslint-disable-next-line no-console
|
2022-09-14 17:24:16 +00:00
|
|
|
console.error(error.code, error.message)
|
|
|
|
})
|
2022-09-07 10:14:34 +00:00
|
|
|
|
2022-09-14 19:08:22 +00:00
|
|
|
const result = await next()
|
2022-09-07 10:14:34 +00:00
|
|
|
|
|
|
|
void plausibleEvent(ctx, {
|
|
|
|
eventName: 'status',
|
|
|
|
props: {
|
|
|
|
status: ctx.status,
|
|
|
|
},
|
2022-09-14 17:24:16 +00:00
|
|
|
}).catch((err) => {
|
|
|
|
const error = err as RequestError
|
2022-09-15 08:15:41 +00:00
|
|
|
// eslint-disable-next-line no-console
|
2022-09-14 17:24:16 +00:00
|
|
|
console.error(error.code, error.message)
|
2022-09-07 10:14:34 +00:00
|
|
|
})
|
|
|
|
|
|
|
|
return result
|
|
|
|
}
|