简体   繁体   English

当我使用 firebase 模拟器和 next.js 时如何使用 firebase-admin 获取 Firestore 数据

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

I use Next.js and firebase emulators.我使用 Next.js 和 firebase 仿真器。 I can add some data to firestore but I couldn't get data with firebase-admin.我可以向 firestore 添加一些数据,但无法使用 firebase-admin 获取数据。 how to get api data with firebase-admin.如何使用 firebase-admin 获取 api 数据。

// 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.要针对模拟器运行firebase-admin ,请设置FIRESTORE_EMULATOR_HOST环境变量,并将其指向模拟器的host:port地址。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何使用firebase-admin删除数据? - How to remove data with firebase-admin? 如何为我的 next.js 项目导出 firebase firestore - How to export firebase firestore for my next.js project 如何使用firebase-admin模块使用Node.js从Firebase数据库返回有序数据? - How can I return ordered data from Firebase database with Node.js using the firebase-admin module? 如何使用 Node.js 和“firebase-admin”SDK 查询 Firebase? - How to query Firebase with Node.js and "firebase-admin" SDK? 由firebase-admin写入数据时,使用规则验证Firebase - Validate Firebase with rules when data is written by firebase-admin 如何在 express.js Vue.js 中使用 firebase-admin - How to use firebase-admin in express.js Vue.js 如何在firebase-admin node.js中限制.once(&#39;value) - How to limit .once('value) in firebase-admin node.js 用于导出 Firestore 备份数据的云功能。 使用 firebase-admin 还是 @google-cloud/firestore? - Cloud function to export Firestore backup data. Using firebase-admin or @google-cloud/firestore? 使用在 Firestore 模拟器上运行的 Firebase-Admin 时找不到 Firestore 文档 - Firestore document not found when using Firebase-Admin running on Firestore Emulator 当有多个站点时如何在 firebase 上部署 next.js 应用程序 - how to deploy next.js app on firebase when there are multi sites
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM