Created
September 22, 2021 20:04
-
-
Save jhonsore/d5084d73b06936ef3a234b341994ab89 to your computer and use it in GitHub Desktop.
Firestore tips
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Firestore data from a Cloud Function | |
const functions = require('firebase-functions'); | |
const admin = require('firebase-admin'); | |
admin.initializeApp(); | |
const db = admin.firestore(); | |
exports.getData = functions.https.onRequest((req, res) => { | |
const docRef = db.collection('my-collection').doc('doc-id'); | |
const getDoc = docRef.get() | |
.then(doc => { | |
if (!doc.exists) { | |
console.log('No such document!'); | |
return res.send('Not Found') | |
} | |
console.log(doc.data()); | |
return res.send(doc.data()); | |
}) | |
.catch(err => { | |
console.log('Error getting document', err); | |
}); | |
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Firestore data from a Cloud Function | |
------------- | |
// Async and TS | |
import * as functions from "firebase-functions"; | |
import * as admin from "firebase-admin"; | |
admin.initializeApp(); | |
const db = admin.firestore(); | |
export {admin, db}; | |
const getDocById = | |
functions.https.onRequest(async ( | |
request:functions.https.Request, response: functions.Response) => { | |
if (request.method !== "GET") { | |
response.status(400).send("Please send a GET request"); | |
return; | |
} | |
if (!request.query.id) { | |
response.status(400).send("ID is missing"); | |
return; | |
} | |
const ID:string = request.query.id as string; | |
const doc = | |
await db.collection("my-collection").doc(ID).get(); | |
let data:any; | |
if (!doc.exists) { | |
data = null; | |
} else { | |
data = {...doc.data()}; | |
} | |
response.send(data); | |
}); | |
export default getDocById; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment