export default async function main(args) {
/**
* IMPORTANT
*
* Use with CAUTION. This is a destructive operation.
*
* Please read the Query Parameters documentation carefully
*
* https://firebase.google.com/docs/firestore/reference/rest/v1/projects.databases.documents/patch#query-parameters
*/
// 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 {
reservationType,
updateField,
firebaseProjectId,
firebaseDatabase, // Default database name is '(default)'
firebaseCollection,
firebaseDocumentId,
firebaseApiKey,
} = args.inputVars;
/**
* Build the payload for updating a new document in Firebase
*
* Check Firebase documentation to learn what data types are available
*
* - https://firebase.google.com/docs/firestore/reference/rest/v1/projects.databases.documents/patch
* - https://firebase.google.com/docs/firestore/reference/rest/v1/DocumentMask
* - https://firebase.google.com/docs/firestore/reference/rest/Shared.Types/ArrayValue#Value
*/
const payload = {
fields: {
[updateField]: { // Field name
stringValue: reservationType // New Value
},
}
};
/**
* IMPORTANT
*
* Define the fields you want to update, otherwise
* you will override the existent information in the document
*
* Adapt or add as many fields as you want
*
* The value of "updateField" should match the key name in payload.fields
*/
const updateFields = [updateField]
// Generate the update mask string
const updateMask = updateFields
.map(field => `updateMask.fieldPaths=${field}`)
.join('&')
/**
* Define the URL for Firebase REST operations
*/
const baseUrl = `https://firestore.googleapis.com/v1`;
const pathUrl = `projects/${firebaseProjectId}/databases/${firebaseDatabase}/documents/${firebaseCollection}/${firebaseDocumentId}`
const endpointUrl = `${baseUrl}/${pathUrl}?${updateMask}&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: 'PATCH',
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 document = responseBody;
// Create the success return trace with extracted data
return {
outputVars: {
document: JSON.stringify(document),
},
next: {
path: 'success'
},
trace: [
{
type: "debug",
payload: {
message: 'Firebase API call successful'
}
},
{
type: "debug",
payload: {
message: 'Document updated'
}
},
{
type: "debug",
payload: {
message: JSON.stringify(document),
}
},
]
};
} 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 {
reservationType,
updateField,
firebaseProjectId,
firebaseDatabase,
firebaseCollection,
firebaseDocumentId,
firebaseApiKey,
} = args.inputVars;
// Validate that reservationType variable is provided
if (!reservationType) {
return {
next: { path: 'error' },
trace: [{ type: "debug", payload: { message: "Missing required input variable: reservationType" } }]
};
}
// Validate that updateField variable is provided
if (!updateField) {
return {
next: { path: 'error' },
trace: [{ type: "debug", payload: { message: "Missing required input variable: updateField" } }]
};
}
// 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 firebaseDocumentId variable is provided
if (!firebaseDocumentId) {
return {
next: { path: 'error' },
trace: [{ type: "debug", payload: { message: "Missing required input variable: firebaseDocumentId" } }]
};
}
// Validate that firebaseApiKey variable is provided
if (!firebaseApiKey) {
return {
next: { path: 'error' },
trace: [{ type: "debug", payload: { message: "Missing required input variable: firebaseApiKey" } }]
};
}
return null
}
}