Skip to content

Instantly share code, notes, and snippets.

@kmelve
Created February 16, 2020 12:56
Show Gist options
  • Save kmelve/ef0f3cebaf00f8bab7b01689328817ac to your computer and use it in GitHub Desktop.
Save kmelve/ef0f3cebaf00f8bab7b01689328817ac to your computer and use it in GitHub Desktop.
Very crude TypeForm integration for Sanity.io on Zeit’s Now.
// api/get-response.ts
import SanityClient from "@sanity/client";
const projectId = "<yourProjectId>";
const dataset = "<yourDataset>";
const token = process.env.SANITY_EVENT_TOKEN; // Add to now secrets and .env
const client = SanityClient({
projectId,
dataset,
token,
useCdn: false
});
// Reformat reponse values
function resolveResponseItem(answer) {
const { field } = answer;
if (field.type === "multiple_choice") {
return answer[answer.type].label;
}
return answer[answer.type];
}
export default async (request: NowRequest, response: NowResponse) => {
const { body } = request;
const { form_response, event_id } = body;
if (!form_response) {
return response.status(404);
}
const { form_id, answers, submitted_at } = form_response;
const res = await client.create({
_type: "response",
// Use id path to hide document from public
_id: `typeform.${event_id}`,
submittedAt: submitted_at,
answers: answers.map(answer => ({
_key: answer.field.ref,
_type: "answer",
[answer.field.type]: resolveResponseItem(answer)
}))
});
console.log(res);
return response.status(200).send(body);
};
// schemas/response.js
export default {
name: 'response',
type: 'document',
title: 'Reponse',
preview: {
select: {
title: 'submittedAt',
},
},
fields: [
{
name: 'submittedAt',
type: 'datetime',
},
{
name: 'answers',
type: 'array',
of: [
{
name: 'answer',
type: 'object',
preview: {
select: {
multiple_choice: 'multiple_choice',
short_text: 'short_text',
rating: 'rating',
},
prepare({ multiple_choice, short_text, rating }) {
return {
title: multiple_choice || short_text || rating,
};
},
},
fields: [
{
type: 'string',
name: 'multiple_choice',
},
{
type: 'text',
name: 'short_text',
},
{
type: 'number',
name: 'rating',
},
],
},
],
},
],
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment