File tree 2 files changed +63
-0
lines changed
2 files changed +63
-0
lines changed Original file line number Diff line number Diff line change
1
+ import type { AnalyticsEngineDataPoint } from '@cloudflare/workers-types/experimental'
2
+
3
+ export default eventHandler ( async ( event ) => {
4
+ const { data } = await readValidatedBody ( event , z . object ( {
5
+ data : z . custom < AnalyticsEngineDataPoint > ( )
6
+ } ) . parse )
7
+
8
+ await useAnalytics ( ) . put ( data )
9
+
10
+ return true
11
+ } )
Original file line number Diff line number Diff line change
1
+ import type { AnalyticsEngineDataPoint , AnalyticsEngineDataset } from '@cloudflare/workers-types/experimental'
2
+ import { ofetch } from 'ofetch'
3
+ import { joinURL } from 'ufo'
4
+
5
+ const _datasets : Record < string , AnalyticsEngineDataset > = { }
6
+
7
+ function _useDataset ( ) {
8
+ const name = 'ANALYTICS'
9
+ if ( _datasets [ name ] ) {
10
+ return _datasets [ name ]
11
+ }
12
+
13
+ // @ts -ignore
14
+ const binding = process . env [ name ] || globalThis . __env__ ?. [ name ] || globalThis [ name ]
15
+ if ( binding ) {
16
+ _datasets [ name ] = binding as AnalyticsEngineDataset
17
+ return _datasets [ name ]
18
+ }
19
+ throw createError ( `Missing Cloudflare ${ name } binding (Analytics Engine)` )
20
+ }
21
+
22
+ export function useAnalytics ( ) {
23
+ if ( import . meta. dev && process . env . NUXT_HUB_URL ) {
24
+ return useProxyAnalytics ( process . env . NUXT_HUB_URL , process . env . NUXT_HUB_SECRET_KEY )
25
+ }
26
+ const dataset = _useDataset ( )
27
+
28
+ return {
29
+ put ( data : AnalyticsEngineDataPoint ) {
30
+ dataset . writeDataPoint ( data )
31
+ return true
32
+ }
33
+ }
34
+ }
35
+
36
+ export function useProxyAnalytics ( projectUrl : string , secretKey ?: string ) {
37
+ const analyticsAPI = ofetch . create ( {
38
+ baseURL : joinURL ( projectUrl , '/api/_hub/analytics' ) ,
39
+ headers : {
40
+ Authorization : `Bearer ${ secretKey } `
41
+ }
42
+ } )
43
+
44
+ return {
45
+ async put ( data : AnalyticsEngineDataPoint ) {
46
+ return analyticsAPI < boolean > ( '/' , {
47
+ method : 'PUT' ,
48
+ body : { data }
49
+ } )
50
+ }
51
+ }
52
+ }
You can’t perform that action at this time.
0 commit comments