Created
January 31, 2019 23:19
-
-
Save MichaelSolati/4de01bd32c726c4f81e21bddc30edca2 to your computer and use it in GitHub Desktop.
Using GeoFirestore with Firebase Functions
This file contains hidden or 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
import * as admin from 'firebase-admin'; | |
import * as functions from 'firebase-functions'; | |
import { GeoFirestore } from 'geofirestore'; | |
import '@google-cloud/firestore/types/firestore'; | |
admin.initializeApp(); | |
// A simple cloud function that will take any doc created in the geocollection collection and convert it to a geofirestore doc | |
const onCreate = functions.firestore | |
.document('geocollection/{uid}') | |
.onCreate((snap: FirebaseFirestore.DocumentSnapshot) => { | |
const collection = new GeoFirestore(admin.firestore()).collection('geocollection'); | |
return collection.doc(snap.id).set(snap.data()); | |
}); | |
// A simple GET query for some locations | |
// Sooo a get to https://somefirebaseapp.cloudfunctions.net/query?lat=0&lng=0&radius=10 | |
const query = functions.https.onRequest((req, res) => { | |
if (req.method === 'GET') { | |
const lat = req.body.lat || 0; | |
const lng = req.body.lng || 0; | |
const radius = req.body.radius || 10; | |
const center = new admin.firestore.GeoPoint(lat, lng); | |
const collection = new GeoFirestore(admin.firestore()).collection('geocollection'); | |
return collection.near({ center, radius }).get().then(value => res.status(200).send(value.docs)); | |
} else { | |
return res.status(405).send({error: 'Something blew up!'}); | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks for this man, means a great deal! Would be nice if it was in the docs somewhere