Skip to content

Instantly share code, notes, and snippets.

@JamieCurnow
Created April 7, 2022 10:33
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JamieCurnow/b4d8231118e19925cd34e6c8e6a969a8 to your computer and use it in GitHub Desktop.
Save JamieCurnow/b4d8231118e19925cd34e6c8e6a969a8 to your computer and use it in GitHub Desktop.
Using firebase in a back-end node service
// Get the imports
import { credential } from 'firebase-admin'
import { initializeApp } from 'firebase-admin/app'
import { getFirestore, CollectionReference, DocumentData } from 'firebase-admin/firestore'
// get the service account - IT SHOULD BE GIT IGNORED!
// Make one and download it here:
// https://console.firebase.google.com/u/0/project/your-project-name/settings/serviceaccounts/adminsdk
const serviceAccount = require('../../firebase-admin-service-account.json')
// Init the firebase app
export const firebaseApp = initializeApp({
projectId: 'your-project-name',
// if we're running this on google cloud in prod (eg: Cloud Run) then it'll auto auth us.
// So we only need the service account in dev.
credential: process.env.NODE_ENV === 'production' ? undefined : credential.cert(serviceAccount)
})
// Export firestore incase we need to access it directly
export const firestore = getFirestore()
// This is just a helper to add the type to the db responses
const createCollection = <T = DocumentData>(collectionName: string) => {
return firestore.collection(collectionName) as CollectionReference<T>
}
// Import all your model types
import { User } from '@your-app/types'
// export all your collections
export const db = {
users: createCollection<User>('users')
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment