简体   繁体   中英

how to get firestore data with firebase-admin when I use firebase emulators and next.js

I use Next.js and firebase emulators. I can add some data to firestore but I couldn't get data with firebase-admin. how to get api data with firebase-admin.

// lib/firebaseAdmin.ts

const cert = {
  projectId: process.env.FIREBASE_PROJECT_ID,
  clientEmail: process.env.FIREBASE_CLIENT_EMAIL,
  privateKey: process.env.FIREBASE_PRIVATE_KEY.replace(/\\n/g, "\n"),
}

admin.initializeApp({
  credential: admin.credential.cert(cert),
})

admin.firestore();
// api/foos/[id].tsx

import { NextApiRequest, NextApiResponse } from 'next'
import 'lib/firebaseAdmin'
import { firestore } from 'firebase-admin'

export default async (req: NextApiRequest, res: NextApiResponse<ResType>) => {
  const fooId = req.query.id as string
  const doc = await firestore().collection('foo').doc(fooId).get();
  const result = doc.id ? { id: doc.id, ...doc.data() } : {}
  
  res.status(200).json({
    foos: result
  })
}

To run firebase-admin against the emulator, set the FIRESTORE_EMULATOR_HOST environment variable, and point it to the host:port address of the emulator.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM