type Jotform = {
apiKey: string
baseUrl: string
}
export async function main(
resource: Jotform,
formId: string,
submissionData: {
answers: {
[questionId: string]: {
answer: string | { [key: string]: string }
}
}
}
) {
const queryParams = new URLSearchParams({ apiKey: resource.apiKey })
const endpoint = `${resource.baseUrl}/form/${formId}/submissions?${queryParams.toString()}`
// Construct the URLSearchParams body
const bodyParams = new URLSearchParams()
// Add answers to the bodyParams
Object.entries(submissionData.answers).forEach(([questionId, { answer }]) => {
if (typeof answer === 'object') {
// Handle cases where the answer is a complex object, like multiple fields in a question
Object.entries(answer).forEach(([key, value]) => {
bodyParams.append(`submission[${questionId}][${key}]`, value)
})
} else {
// Handle simple answer strings
bodyParams.append(`submission[${questionId}]`, answer)
}
})
// Send the request with the URL-encoded body
const response = await fetch(endpoint, {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
body: bodyParams.toString()
})
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`)
}
const data = await response.json()
return data
}
Submitted by hugo697 621 days ago