Skip to content

Commit

Permalink
feat(firestore): add UsesEmulator field to Client (googleapis#11359)
Browse files Browse the repository at this point in the history
* feat(firestore): add UsingEmulator field to Client

* rename to UsesEmulator
  • Loading branch information
raymonstah authored Jan 13, 2025
1 parent 58cab62 commit c2eccfe
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 0 deletions.
4 changes: 4 additions & 0 deletions firestore/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,7 @@ type Client struct {
projectID string
databaseID string // A client is tied to a single database.
readSettings *readSettings // readSettings allows setting a snapshot time to read the database
UsesEmulator bool // a boolean that indicates if the client is using the emulator
}

// NewClient creates a new Firestore client that uses the given project.
Expand All @@ -81,12 +82,14 @@ func NewClient(ctx context.Context, projectID string, opts ...option.ClientOptio
return nil, errors.New("firestore: projectID was empty")
}
var o []option.ClientOption
var usesEmulator bool
// If this environment variable is defined, configure the client to talk to the emulator.
if addr := os.Getenv("FIRESTORE_EMULATOR_HOST"); addr != "" {
conn, err := grpc.Dial(addr, grpc.WithInsecure(), grpc.WithPerRPCCredentials(emulatorCreds{}))
if err != nil {
return nil, fmt.Errorf("firestore: dialing address from env var FIRESTORE_EMULATOR_HOST: %s", err)
}
usesEmulator = true
o = []option.ClientOption{option.WithGRPCConn(conn)}
projectID, _ = detect.ProjectID(ctx, projectID, "", opts...)
if projectID == "" {
Expand All @@ -111,6 +114,7 @@ func NewClient(ctx context.Context, projectID string, opts ...option.ClientOptio
projectID: projectID,
databaseID: DefaultDatabaseID,
readSettings: &readSettings{},
UsesEmulator: usesEmulator,
}
return c, nil
}
Expand Down
17 changes: 17 additions & 0 deletions firestore/client_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ package firestore

import (
"context"
"os"
"testing"
"time"

Expand Down Expand Up @@ -399,3 +400,19 @@ func TestClient_WithReadOptions(t *testing.T) {
t.Fatal(err)
}
}

func TestClient_UsesEmulator(t *testing.T) {
c, _, cleanup := newMock(t)
defer cleanup()
if c.UsesEmulator {
t.Error("got true, want false")
}

os.Setenv("FIRESTORE_EMULATOR_HOST", "localhost:8080")
defer os.Unsetenv("FIRESTORE_EMULATOR_HOST")
c, _, cleanup = newMock(t)
defer cleanup()
if !c.UsesEmulator {
t.Error("got false, want true")
}
}

0 comments on commit c2eccfe

Please sign in to comment.