[英]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.