|
| 1 | +import { PostHog } from 'posthog-node' |
| 2 | +import { Feedback } from 'vocs/config' |
| 3 | +import { POSTHOG_EVENTS, POSTHOG_PROPERTIES } from './posthog' |
| 4 | + |
| 5 | +type FeedbackData = { |
| 6 | + helpful: boolean |
| 7 | + category?: string | undefined |
| 8 | + message?: string | undefined |
| 9 | + pageUrl: string |
| 10 | + timestamp: string |
| 11 | +} |
| 12 | + |
| 13 | +export function createFeedbackAdapter() { |
| 14 | + const slackAdapter = Feedback.slack() |
| 15 | + |
| 16 | + const posthogKey = process.env.VITE_POSTHOG_KEY |
| 17 | + const posthogHost = process.env.VITE_POSTHOG_HOST || 'https://us.i.posthog.com' |
| 18 | + |
| 19 | + const posthog = posthogKey ? new PostHog(posthogKey, { host: posthogHost }) : null |
| 20 | + |
| 21 | + return Feedback.from({ |
| 22 | + type: 'slack+posthog', |
| 23 | + async submit(data: FeedbackData) { |
| 24 | + const slackPromise = slackAdapter.submit(data) |
| 25 | + |
| 26 | + const posthogPromise = (async () => { |
| 27 | + if (!posthog) return |
| 28 | + |
| 29 | + let pagePath: string | undefined |
| 30 | + try { |
| 31 | + pagePath = new URL(data.pageUrl).pathname |
| 32 | + } catch { |
| 33 | + pagePath = undefined |
| 34 | + } |
| 35 | + |
| 36 | + const distinctId = `docs_feedback_${Date.now()}_${Math.random().toString(36).slice(2)}` |
| 37 | + const ts = data.timestamp ? new Date(data.timestamp) : undefined |
| 38 | + |
| 39 | + const commonProperties = { |
| 40 | + [POSTHOG_PROPERTIES.FEEDBACK_HELPFUL]: data.helpful, |
| 41 | + [POSTHOG_PROPERTIES.FEEDBACK_CATEGORY]: data.category, |
| 42 | + [POSTHOG_PROPERTIES.FEEDBACK_MESSAGE]: data.message, |
| 43 | + [POSTHOG_PROPERTIES.FEEDBACK_PAGE_URL]: data.pageUrl, |
| 44 | + [POSTHOG_PROPERTIES.PAGE_PATH]: pagePath, |
| 45 | + [POSTHOG_PROPERTIES.SITE]: 'docs', |
| 46 | + } |
| 47 | + |
| 48 | + posthog.capture({ |
| 49 | + distinctId, |
| 50 | + event: POSTHOG_EVENTS.FEEDBACK_SUBMITTED, |
| 51 | + properties: commonProperties, |
| 52 | + timestamp: ts, |
| 53 | + }) |
| 54 | + |
| 55 | + posthog.capture({ |
| 56 | + distinctId, |
| 57 | + event: data.helpful |
| 58 | + ? POSTHOG_EVENTS.FEEDBACK_HELPFUL |
| 59 | + : POSTHOG_EVENTS.FEEDBACK_NOT_HELPFUL, |
| 60 | + properties: commonProperties, |
| 61 | + timestamp: ts, |
| 62 | + }) |
| 63 | + |
| 64 | + await posthog.flush() |
| 65 | + })().catch(() => {}) |
| 66 | + |
| 67 | + await Promise.allSettled([slackPromise, posthogPromise]) |
| 68 | + }, |
| 69 | + }) |
| 70 | +} |
0 commit comments