'How to send data via HTTP request to Firestore database

So, I am trying to make an app with Node.js, Vue, and Firebase. I currently have a very basic function using firebase functions to send data to the realtime database via http request. I cant figure out how to do the same for Firestore database.

My goal is to send data or a file of some JSON data to my Firestore database from outside the app with an HTTP request. I know how to deploy functions I just am not sure how to send files or JSON to the database for further use.

Any help is greatly appreciated!

I have been playing around with different functions but can't seem to figure it out. I have looked at many of the docs/videos for firebase but I am pretty knew to this and can't quite grasp it.

const functions = require('firebase-functions');
const admin = require('firebase-admin')
admin.initializeApp() //need admin sdk

const toUpperCase = (string) => string.toUpperCase();

exports.addMessage = functions.https.onRequest((request, response) => {
const text = request.query.text;

const secretText = toUpperCase(text);

admin
    .database()
    .ref('/sentMSG')
    .push({ text: secretText })
    .then(() =>
        response.json({
            message: 'great!!!!',
            text
        })
    )
    .catch(() => {
        response.json({
            message: 'not great :^('
        });
    });
});

exports.writeToStore = functions.firestore.https.onRequest((request, 
response) => {
  let data = request.query.text
  let setDoc = db.collection('cities').doc('LA').set(data)
   .then(() =>
        response.json({
            message: 'great!!!!',
            text
        })
    )
    .catch(() => {
        response.json({
            message: 'not great :^('
        });
    });
});

The addMessage function adds data to realtime database but I need to do it for Firestore



Solution 1:[1]

index.js


const functions = require('firebase-functions');
const admin = require('firebase-admin');
const _ = require('lodash');
admin.initializeApp();
const db = admin.firestore();

const express = require('express');
const cors = require('cors');

const app = express();
const bodyParser = require('body-parser');

app.use(bodyParser.json());

app.get('/', async (req, res) => {
let data = req.query.data;

  try {
          await db.collection('users').doc().set({ userId: data });
        } catch(err) { res.send(JSON.stringify(err)) }

      res.send('Success');
})

app.post('/', async (req, res) => {
  let payload = req.body;
  let keys = Object.keys(payload);
  let obj = {};
  let i = 0;

  try {
    _.forEach(payload, async data => {
      obj[keys[i]] = data;
      i++;
    })

   await db.collection('users').doc().set(obj);
  } catch(err) { res.send(JSON.stringify(err))}

    res.send('Success');
})

exports.writeToFirestore = functions.https.onRequest(app);

You can then call this Cloud Function like such: linkToURL/writeToFirestore?data=5 or make a Post request to linkURL/writeToFirestore


From what I understand, whenever the Cloud Function is triggered, you want to write data in both the Firebase Realtime Database and in Firestore. Cloud Function will only execute one function in the exports object. In this case, since the function is being triggered by HTTPS, you can create a single exports.writeToBoth that encapsulates the code to write in Realtime DB and Firestore. Furthermore, I noticed that the writeToFirestore written is invalid, you need to change functions.firestore.https.onRequest to functions.https.onRequest.

In any case, you can refer to this code as a base, should you want:


const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp();
const db = admin.firestore();

let writeToFirestore = data => {
  let setDoc = db.collection('users').doc('0').set(data);
} 

let writeToRealtimeDB = data => {
  // ...
 // Your code
 // ...
}

exports.writeToBoth = functions.https.onRequest((req, res) => {
  let data = req.query.text;

  // Write to both DB
try {
  writeToFirestore(data);
  writeToRealtimeDB(data);
} catch(err) { res.send('Error') } 

  res.send('Success');
})

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1