-
Notifications
You must be signed in to change notification settings - Fork 623
Expand file tree
/
Copy pathuseValidateEvent.ts
More file actions
229 lines (201 loc) · 6.94 KB
/
Copy pathuseValidateEvent.ts
File metadata and controls
229 lines (201 loc) · 6.94 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
import { useCopy } from "@/hooks"
import { Requestable, RequestStatus } from "@/types"
import { Validator } from "./validator"
import { baseContentSchema } from "./schemas/baseContent"
import { formatCheckLib } from "./handlers/formatCheckLib"
import { formatErrorMessages, formatValidationMessage } from "./handlers/responseUtil"
import {
createContext,
useCallback,
useContext,
useEffect,
useState,
} from "react"
import { EventCtx, UseFirebaseCtx } from ".."
import { InstanceId, ValidationMessage } from "../types"
import usePayload from "./usePayload"
import useInputs from "../useInputs"
import useEvent from "../useEvent"
import useSharableLink from "./useSharableLink"
import {JSONError} from 'json-schema-library';
// Build the query param for the instance that should be used for the event.
// Defaults to an empty measurement_id if neither one is set.
const instanceQueryParamFor = (instanceId: InstanceId) => {
if (instanceId.firebase_app_id) {
return `&firebase_app_id=${instanceId.firebase_app_id}`
}
if (instanceId.measurement_id) {
return `&measurement_id=${instanceId.measurement_id}`
}
return ``
}
const validateHit = async (
payload: {},
instanceId: InstanceId,
api_secret: string
): Promise<ValidationMessage[]> => {
const url = `https://www.google-analytics.com/debug/mp/collect?api_secret=${api_secret}${instanceQueryParamFor(
instanceId
)}`
const body = Object.assign({}, payload, {
validationBehavior: "ENFORCE_RECOMMENDATIONS",
})
const result = await fetch(url, {
method: "POST",
body: JSON.stringify(body),
})
const asJson = await result.json()
return asJson.validationMessages as ValidationMessage[]
}
const sendHit = async (
payload: {},
instanceId: InstanceId,
api_secret: string
): Promise<void> => {
const url = `https://www.google-analytics.com/mp/collect?api_secret=${api_secret}${instanceQueryParamFor(
instanceId
)}`
const body = Object.assign({}, payload, {
validationBehavior: "ENFORCE_RECOMMENDATIONS",
})
await fetch(url, {
method: "POST",
body: JSON.stringify(body),
})
return
}
export type ValidationSuccessful = {
sent: boolean
sendToGA: () => void
copyPayload: () => void
copySharableLink: () => void
}
export type ValidationNotStarted = { validateEvent: () => void }
export type ValidationInProgress = {}
export type ValidationFailed = {
validationMessages: ValidationMessage[]
validateEvent: () => void
payloadErrors: string | undefined
}
export const ValidationRequestCtx = createContext<
ReturnType<typeof useValidateEvent> | undefined
>(undefined)
const useValidateEvent = (): Requestable<
ValidationSuccessful,
ValidationNotStarted,
ValidationInProgress,
ValidationFailed
> => {
const useFirebase = useContext(UseFirebaseCtx)
const { useTextBox } = useContext(EventCtx)!
const [status, setStatus] = useState(RequestStatus.NotStarted)
const [validationMessages, setValidationMessages] = useState<
ValidationMessage[]
>([])
const payload = usePayload()
const [sent, setSent] = useState(false)
const { instanceId, api_secret } = useContext(EventCtx)!
const { categories } = useEvent()
const { payloadErrors } = useInputs(categories)
useEffect(() => {
if (!useTextBox) {
setStatus(RequestStatus.NotStarted)
setSent(false)
}
}, [payload, useTextBox])
const sendToGA = useCallback(() => {
if (status !== RequestStatus.Successful) {
return
}
sendHit(payload, instanceId, api_secret).then(() => setSent(true))
}, [status, payload, instanceId, api_secret])
const copyPayload = useCopy(
JSON.stringify(payload, undefined, " "),
"copied payload"
)
const url = useSharableLink()
const copySharableLink = useCopy(url, "copied link to event")
const validatePayloadAttributes = useCallback((payload: any) => {
const validator = new Validator(baseContentSchema)
const formatCheckErrors: ValidationMessage[] | [] = formatCheckLib(
payload,
instanceId,
api_secret,
useFirebase
)
if (!validator.isValid(payload) || formatCheckErrors) {
let validatorErrors: ValidationMessage[] = validator.getErrors(payload).map((err) => {
return {
description: err.message,
validationCode: err?.data?.validationError?.code ? err?.data?.validationError?.code : err.code,
fieldPath: defineFieldCode(err)
}
})
return [...validatorErrors, ...formatCheckErrors]
}
return []
}, [api_secret, instanceId, useFirebase])
const validateEvent = useCallback(() => {
if (status === RequestStatus.InProgress) {
return
}
setStatus(RequestStatus.InProgress)
setValidationMessages([])
if (!useTextBox || Object.keys(payload).length !== 0) {
let validatorErrors = validatePayloadAttributes(payload)
validateHit(payload, instanceId, api_secret)
.then(messages => {
setTimeout(() => {
if (messages.length > 0 || validatorErrors.length > 0) {
const apiValidationErrors = messages.filter(a =>
a.fieldPath === "measurement_id"
? !useFirebase
: a.fieldPath === "firebase_app_id"
? useFirebase
: true
)
apiValidationErrors.forEach(err => {
if (!validatorErrors.map(e => e.description).includes(err.description)) {
validatorErrors.push(err)
}
})
validatorErrors = formatErrorMessages(validatorErrors, payload, useFirebase)
setValidationMessages(validatorErrors)
setStatus(RequestStatus.Failed)
} else {
setStatus(RequestStatus.Successful)
}
}, 250)
})
.catch(e => {
console.error(e)
})
} else {
const validatorErrors = formatValidationMessage()
setValidationMessages(validatorErrors)
setStatus(RequestStatus.Failed)
}
}, [status, payload, api_secret, instanceId, useFirebase, useTextBox, validatePayloadAttributes])
const defineFieldCode = (error: JSONError) => {
const { data } = error
if (data?.pointer) {
if (data?.key) {
return data.pointer + '/' + data.key
} else if (data?.missingProperty) {
return data.pointer + '/' + data.missingProperty
}
return data?.pointer
}
return data?.key
}
if (status === RequestStatus.Successful) {
return { status, sendToGA, copyPayload, copySharableLink, sent }
} else if (status === RequestStatus.NotStarted) {
return { status, validateEvent }
} else if (status === RequestStatus.Failed) {
return { status, validationMessages, validateEvent, payloadErrors}
} else {
return { status }
}
}
export default useValidateEvent