Firebase Firestore: Create Document

Template
Function
3
Template
Function
by
Voiceflow Community

This function creates a new document in a root Firestore Collection in Firebase. The function returns the newly created document path.

Created:

Heading

Voiceflow APIs used:

Channels
No items found.
Created By
Voiceflow Community
This is some text inside of a div block.

Function Code Snippet

 
export default async function main(args) {
// Validate input variables from args - find the "validateInputs" function below
const invalidFieldTrace = validateInputs(args)

if (invalidFieldTrace) return invalidFieldTrace;

// Extract input variables from args (destructuring)
const {
serviceType,
serviceDateTime,
userName,
userEmail,
firebaseProjectId,
firebaseDatabase, // Default database name is '(default)'
firebaseCollection,
firebaseApiKey,
} = args.inputVars;

/**
* IMPORTANT
*
* Build the payload for creating a new document in Firebase with your own data
*
* Check Firebase documentation to learn what data types are available
*
* - https://firebase.google.com/docs/firestore/reference/rest/v1/projects.databases.documents/createDocument
* - https://firebase.google.com/docs/firestore/reference/rest/Shared.Types/ArrayValue#Value
*/
const payload = {
fields: {
serviceType: { // Field name
stringValue: serviceType // Value
},
serviceDateTime: {
stringValue: serviceDateTime
},
userName: {
stringValue: userName
},
userEmail: {
stringValue: userEmail
}
}
};

/**
* Define the URL for Firebase REST operations
*/
const baseUrl = `https://firestore.googleapis.com/v1`;
const pathUrl = `projects/${firebaseProjectId}/databases/${firebaseDatabase}/documents/${firebaseCollection}`
const endpointUrl = `${baseUrl}/${pathUrl}?key=${firebaseApiKey}`

/**
* Configure the fetch request
*
* Get your Firebase Web API Key from the project settings
*
* https://console.firebase.google.com/project/YOUR_PROJECT_ID/settings/general
*/
const config = {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(payload)
};

try {
// Make the API call
const response = await fetch(endpointUrl, config);

// Check if the response status is OK
if (!response.ok) {
throw new Error(`HTTP status code ${response.status}`);
}

// Extract the JSON body from the response
const responseBody = response.json;

// Validate the responseBody structure as expected
if (!responseBody || typeof responseBody !== 'object') {
throw new Error("Invalid or missing response body");
}

// Extract data from the response
const documentPath = responseBody.name;

// Create the success return trace with extracted data
return {
outputVars: {
documentPath,
},
next: {
path: 'success'
},
trace: [
{
type: "debug",
payload: {
message: 'Firebase API call successful'
}
},
{
type: "debug",
payload: {
message: 'Document created'
}
},
{
type: "debug",
payload: {
message: `Record created - Document Path: ${documentPath}`
}
},
]
};
} catch (error) {
return {
next: {
path: 'error'
},
trace: [{
type: "debug",
payload: {
message: `Firebase API call error: ${error.message}`
}
}]
};
}

/**
* Here we validate all the inputs of the Voiceflow function
*
* The function can be used in the first lines of the code
* because of a Javascript concept called hoisting
*
* Read more: https://developer.mozilla.org/en-US/docs/Glossary/Hoisting
*/
function validateInputs(args) {
// Extract input variables from args (destructuring)
const {
serviceType,
serviceDateTime,
userName,
userEmail,
firebaseProjectId,
firebaseDatabase,
firebaseCollection,
firebaseApiKey,
} = args.inputVars;

// Validate that serviceType variable is provided
if (!serviceType) {
return {
next: { path: 'error' },
trace: [{ type: "debug", payload: { message: "Missing required input variable: serviceType" } }]
};
}

// Validate that serviceDateTime variable is provided
if (!serviceDateTime) {
return {
next: { path: 'error' },
trace: [{ type: "debug", payload: { message: "Missing required input variable: serviceDateTime" } }]
};
}

// Validate that userName variable is provided
if (!userName) {
return {
next: { path: 'error' },
trace: [{ type: "debug", payload: { message: "Missing required input variable: userName" } }]
};
}

// Validate that userEmail variable is provided
if (!userEmail) {
return {
next: { path: 'error' },
trace: [{ type: "debug", payload: { message: "Missing required input variable: userEmail" } }]
};
}

// Validate that firebaseProjectId variable is provided
if (!firebaseProjectId) {
return {
next: { path: 'error' },
trace: [{ type: "debug", payload: { message: "Missing required input variable: firebaseProjectId" } }]
};
}

// Validate that firebaseDatabase variable is provided
if (!firebaseDatabase) {
return {
next: { path: 'error' },
trace: [{ type: "debug", payload: { message: "Missing required input variable: firebaseDatabase" } }]
};
}

// Validate that firebaseCollection variable is provided
if (!firebaseCollection) {
return {
next: { path: 'error' },
trace: [{ type: "debug", payload: { message: "Missing required input variable: firebaseCollection" } }]
};
}

// Validate that firebaseApiKey variable is provided
if (!firebaseApiKey) {
return {
next: { path: 'error' },
trace: [{ type: "debug", payload: { message: "Missing required input variable: firebaseApiKey" } }]
};
}

return null
}
}
copy-icon

Explore More Templates

Build and submit a Template to have it featured in the community.

ghraphic
No items found.
No items found.