0

I have config/firebase.ts:

import { initializeApp, cert } from 'firebase-admin/app';
import { getFirestore } from 'firebase-admin/firestore'

const firebaseAdminApp = initializeApp({
    credential: cert({
        privateKey: process.env.NEXT_PUBLIC_FIREBASE_PRIVATE_KEY.replace(/\\n/g, '\n'),
        clientEmail: process.env.NEXT_PUBLIC_FIREBASE_SERVICE_EMAIL,
        projectId: process.env.NEXT_PUBLIC_FIREBASE_PROJECT_ID
    }),
    databaseURL: `https://${process.env.NEXT_PUBLIC_FIREBASE_PROJECT_ID}.firebaseio.com`
});


const firestore = getFirestore(firebaseAdminApp);

export default firestore

and when trying to upsert, I have:

import firestore from "../config/firebaseAdmin";

const upsertInstance = async (instance: Instance) => {
  const hashedUri = createHash('sha256').update(instance.uri).digest('hex')
  const res = await firestore.doc(`instances/${hashedUri}`).set(instance);
  return res
}

but I get:

Error: expected a function

What am I doing wrong?

Shamoon
  • 41,293
  • 91
  • 306
  • 570
  • Firebase Admin is not totally modular yet. Are you importing `setDoc()` and `doc()` from `"firebase/firestore"`? Please share the complete code including the imports. – Dharmaraj Nov 12 '22 at 16:35
  • Yup - updated the question to reflect imports – Shamoon Nov 12 '22 at 16:36

1 Answers1

3

Firebase Admin is not totally modular yet like the client SDK yet so you would have to use namespaced syntax. Admin SDK's Firestore instance won't work perfectly with client SDK functions. Try refactoring the code as shown below:

export const db = getFirestore(firebaseAdminApp);
import { db } from "../path/to/firebase"

const upsertInstance = async (instance: Instance) => {
  const res = await db.doc(`instances/${instance.uri}`).set(instance);
  return res;
}

Checkout the documentation for more information.

Dharmaraj
  • 47,845
  • 8
  • 52
  • 84