Skip to content

Instantly share code, notes, and snippets.

@hakimio
Last active December 8, 2020 09:14
Show Gist options
  • Select an option

  • Save hakimio/7e9fa48b58061d55cea0c8f858b22ddb to your computer and use it in GitHub Desktop.

Select an option

Save hakimio/7e9fa48b58061d55cea0c8f858b22ddb to your computer and use it in GitHub Desktop.
Improve Firebase and Google Cloud function cold starts by using Firestore REST client instead of the default gRPC (time to retrieve a single document down from ~1.5 s to ~250 ms in cold start function)
import {firestore_v1, google} from 'googleapis';
import {convert} from 'firestore-adapter';
let fs: firestore_v1.Firestore;
const getFirestore = async (): Promise<firestore_v1.Firestore> => {
if (!fs) {
const auth = new google.auth.GoogleAuth({
scopes: ['https://www.googleapis.com/auth/cloud-platform']
}),
authClient = await auth.getClient();
fs = new firestore_v1.Firestore({
auth: authClient
});
}
return fs;
};
export const googleApiFirestoreTest = functions.region('europe-west3').https.onRequest(
async (request, response) => {
const path = `projects/${process.env.GCLOUD_PROJECT}/databases/(default)/documents/users/{some-user-uid}`,
firestore = await getFirestore();
const result = await firestore.projects.databases.documents.get({
name: path
}),
doc = result.data,
idRegex = /([^/]+$)/g,
id = doc.name.match(idRegex)[0],
fields = doc.fields;
response.send({
id,
data: convert.docToData(fields)
});
}
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment