Back to all functions

Firebase Firestore: Get Document

This function fetches a document from a root Firestore Collection in Firebase. The function returns the document.

Created By
Voiceflow Community
Community
download-icon
INPUT VARIABLES
{
firebaseApiKey
}
The Web API Key of your Firestore project. You can find it in the settings
{
firebaseDatabase
}
The name of the Firestore database. Default name is "(default)"
{
firebaseProjectId
}
The Project ID of your Firestore project. You can find it in the settings
{
firebaseCollection
}
The name of the collection where the document is going to be created
{
firebaseDocumentId
}
The ID of the document in Firebase
{
}
share-icon
OUTPUT VARIABLES
{
document
}
The document response
{
}
{
}
{
}
{
}
{
}
paths-icon
PATHS
{
success
}
Success
{
error
}
Error
{
}
{
}
{
}
{
}

Function Walkthrough

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 {
    firebaseProjectId,
    firebaseDatabase, // Default database name is '(default)'
    firebaseCollection,
    firebaseDocumentId,
    firebaseApiKey,
  } = args.inputVars;

  /**
   * Define the URL for Firebase REST operations
   *
   * Read more about the 'get' operation
   * - https://firebase.google.com/docs/firestore/reference/rest/v1/projects.databases.documents/get
   */
  const baseUrl = `https://firestore.googleapis.com/v1`;
  const pathUrl = `projects/${firebaseProjectId}/databases/${firebaseDatabase}/documents/${firebaseCollection}/${firebaseDocumentId}`
  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: 'GET',
  };

  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
     *
     * Use the fields you have on your Firestore document. For example:
     *
     * const userName = responseBody.fields.userName;
     **/
    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: JSON.stringify(responseBody)
          }
        },
      ]
    };
  } 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 {
      firebaseProjectId,
      firebaseDatabase,
      firebaseCollection,
      firebaseDocumentId,
      firebaseApiKey,
    } = args.inputVars;
  
    // 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
  }
}
copy-icon

Have something to share?

Share your creation with over 250,000 other global Voiceflow users.

ghraphic
No items found.