我的 Firestore 连接一直想要连接到默认数据库,但我想连接到名为“dbsomething”的数据库,这不是默认数据库。
我可以在这里连接到我的数据库吗?
firestoreClient, err := app.Firestore(ctx)
下面是我用来连接到我使用 Golang 的 Firestore 数据库的代码。
package config
import (
"context"
"encoding/json"
"fatfiresocial/src/logger"
"fmt"
"time"
"cloud.google.com/go/firestore"
firebase "firebase.google.com/go/v4"
"go.uber.org/zap"
"google.golang.org/api/option"
)
func getAndValidateServiceAccount() ([]byte, error) {
cfg := EnvVariables()
serviceAccountJSONString := cfg.ServiceAccount
if serviceAccountJSONString == "" {
logger.Logger.Error("GOOGLE_APPLICATION_CREDENTIALS environment variable not set")
return nil, fmt.Errorf("GOOGLE_APPLICATION_CREDENTIALS environment variable not set")
}
serviceAccountJSON := []byte(serviceAccountJSONString)
var temp map[string]interface{}
err := json.Unmarshal(serviceAccountJSON, &temp)
if err != nil {
logger.Logger.Error("Error parsing service account JSON", zap.Error(err), zap.String("serviceAccountJSON", string(serviceAccountJSON))) // Log masked sensitive data
return nil, fmt.Errorf("invalid service account JSON: %w", err)
}
return serviceAccountJSON, nil
}
func InitializeFirestore() (*firestore.Client, error) {
logger.InitialzieLogger()
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) // Add timeout
defer cancel()
serviceAccountJSON, err := getAndValidateServiceAccount()
if err != nil {
return nil, err
}
opt := option.WithCredentialsJSON(serviceAccountJSON)
config := &firebase.Config{ProjectID: "projectName"}
app, err := firebase.NewApp(ctx, config, opt)
if err != nil {
logger.Logger.Error("Error initializing Firebase app", zap.Error(err))
return nil, fmt.Errorf("firebase app initialization failed: %w", err)
}
firestoreClient, err := app.Firestore(ctx)
if err != nil {
logger.Logger.Error("Error getting Firestore client", zap.Error(err))
return nil, fmt.Errorf("firestore client initialization failed: %w", err)
}
//firestoreClient, err := app.Firestore(ctx)
if err != nil {
logger.Logger.Error("Error getting Firestore client", zap.Error(err))
return nil, fmt.Errorf("firestore client initialization failed: %w", err)
}
logger.Logger.Info("Firestore client initialized for project projectName")
return firestoreClient, nil
}
这就是我给客户打电话的方式:
func SaveNotification(notification openapi.Notification, db *firestore.Client) error {
logger.Logger.Info("Saving notification", zap.String("notificationId", notification.Id))
collectionRef := db.Collection("dbSomething")
logger.Logger.Info("Saving notification", zap.String("notificationId", collectionRef.Path))
_, err := collectionRef.Doc("notifications").Set(context.Background(), notification)
if err != nil {
logger.Logger.Error("Failed to save notification", zap.Error(err))
return err
}
return nil
}
在打字稿中,我能够像这样连接数据库:
import { app } from '@config/firebase';
import {
collection,
doc,
getDoc,
getDocs,
getFirestore,
setDoc,
updateDoc,
deleteDoc,
} from 'firebase/firestore';
import { getCurrentUser } from '@/lib/api/auth';
import { Community } from '@/types/community';
const db = getFirestore(app, 'guap-social');
golang 中的 getFirestore 相当于什么?
这是答案,替换这一行:
firestoreClient, err := app.Firestore(ctx)
使用此行将数据库设置为非默认值:
firestoreClient, err := firestore.NewClientWithDatabase(ctx, "guap-social", "guap-social", opt)