capture total time of fetching a page
This commit is contained in:
@ -1,13 +1,12 @@
|
||||
import { PostHog } from 'posthog-node'
|
||||
|
||||
interface AnalyticEvent {
|
||||
distinctId: string
|
||||
event: string
|
||||
result: 'success' | 'failure'
|
||||
properties?: Record<string | number, any>
|
||||
}
|
||||
|
||||
interface AnalyticClient {
|
||||
capture: (event: AnalyticEvent) => void
|
||||
capture: (userIds: string[], event: AnalyticEvent) => void
|
||||
shutdownAsync?: () => Promise<void>
|
||||
}
|
||||
|
||||
@ -18,17 +17,23 @@ class PostHogClient implements AnalyticClient {
|
||||
this.client = new PostHog(apiKey)
|
||||
}
|
||||
|
||||
capture({ distinctId, event, properties }: AnalyticEvent) {
|
||||
// get client from request context
|
||||
capture(userIds: string[], { properties, result }: AnalyticEvent) {
|
||||
if (process.env.SEND_ANALYTICS) {
|
||||
userIds.forEach((userId) => {
|
||||
this.client.capture({
|
||||
distinctId: userId,
|
||||
event: `content_fetch_${result}`,
|
||||
properties: {
|
||||
...properties,
|
||||
env: process.env.API_ENV,
|
||||
},
|
||||
})
|
||||
})
|
||||
|
||||
this.client.capture({
|
||||
distinctId,
|
||||
event,
|
||||
properties: {
|
||||
...properties,
|
||||
env: process.env.API_ENV || 'demo',
|
||||
},
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
console.log('analytics', { userIds, result, properties })
|
||||
}
|
||||
|
||||
async shutdownAsync() {
|
||||
|
||||
@ -148,33 +148,23 @@ export const contentFetchRequestHandler: RequestHandler = async (req, res) => {
|
||||
logRecord.error = 'unknown error'
|
||||
}
|
||||
|
||||
// capture error event
|
||||
users.forEach((user) => {
|
||||
analytics.capture({
|
||||
distinctId: user.id,
|
||||
event: 'content_fetch_failure',
|
||||
properties: {
|
||||
url,
|
||||
},
|
||||
})
|
||||
})
|
||||
|
||||
return res.sendStatus(500)
|
||||
} finally {
|
||||
logRecord.totalTime = Date.now() - functionStartTime
|
||||
console.log(`parse-page result`, logRecord)
|
||||
}
|
||||
|
||||
// capture success event
|
||||
users.forEach((user) => {
|
||||
analytics.capture({
|
||||
distinctId: user.id,
|
||||
event: 'content_fetch_success',
|
||||
properties: {
|
||||
url,
|
||||
},
|
||||
})
|
||||
})
|
||||
// capture events
|
||||
analytics.capture(
|
||||
users.map((user) => user.id),
|
||||
{
|
||||
result: logRecord.error ? 'failure' : 'success',
|
||||
properties: {
|
||||
url,
|
||||
totalTime: logRecord.totalTime,
|
||||
},
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
res.sendStatus(200)
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user