FireStore Quick Start Guide
Base64 Encoded Private Key as Environment Variable
Encode -> const encoded = Buffer.from('username:password', 'utf8').toString('base64')
Decode -> const plain = Buffer.from('dXNlcm5hbWU6cGFzc3dvcmQ=', 'base64').toString('utf8')
Using .env
// CAUTION: Remove in PROD if .env file is present
require('dotenv').config();
const projectId = process.env.GOOGLE_PROJECT_ID;
const email = process.env.GOOGLE_SERVICE_ACCOUNT_EMAIL;
// const key = process.env.GOOGLE_PRIVATE_KEY.replace(/\\n/g, '\n');
const key = Buffer.from(process.env.GOOGLE_PRIVATE_KEY_ENC, 'base64').toString('utf8') ; // decode from base64 encoded string
Firestore - Connect and Access Sample
// Based on : https://cloud.google.com/firestore/docs/create-database-server-client-library#node.js
const Firestore = require('@google-cloud/firestore');
const { Timestamp } = require('@google-cloud/firestore');
const db = new Firestore({
projectId: projectId,
credentials: {
client_email: email,
private_key: key,
},
});
async function insertData() {
const docRef = db.collection('users').doc('alovelace');
await docRef.set({
first: 'Ada',
last: 'Lovelace',
born: 1815
});
const aTuringRef = db.collection('users').doc('aturing');
await aTuringRef.set({
'first': 'Alan',
'middle': 'Mathison',
'last': 'Turing',
'born': 1912
});
const data = {
stringExample: 'Hello, World!',
booleanExample: true,
numberExample: 3.14159265,
dateExample: Timestamp.fromDate(new Date('December 10, 1815')),
arrayExample: [5, true, 'hello'],
nullExample: null,
objectExample: {
a: 5,
b: true
}
};
const res = await db.collection('data').doc('one').set(data);
}