README

fuego

Build Status Go Report Card codebeat badge GoDoc License

Fuego is a Go client library for Google Firestore. It can be used in App Engine, Cloud Run, Google Cloud Functions and more.

It does not do anything crazy or magic – the purpose is to reduce the amount of boilerplate by hiding the ceremony that comes with interacting with Firestore.

Context

While working on a project running on multiple services and serverless functions, I quickly realised that the amount of repetitive and boilerplate code related to Firestore increased exponentially.

I decided to extract this code in a thin layer on top of the Firestore admin client. That's how fuego came to life.

Fuego

Features

Documents
  • CRUD operations
  • Retrieving/Updating specific fields only
  • Simple Exists check
  • Write Batches
Collections
  • Batch processing (update field for all, delete all, etc.)
  • Better flexibility with Arrays and Maps (append/merge or override data)

Usage

Import
go get github.com/remychantenay/fuego
Set Up
import "github.com/remychantenay/fuego"

func main() {
    fuegoClient := fuego.New(firestoreClient) // firestoreClient needs to be created beforehand.
    /// Your code here...
}
Document

Bear in mind that the examples below are not including how to initialize Firebase and nor create the Firestore client. Check Firebase's documentation for more info.

Create
type User struct {
    FirstName       string              `firestore:"FirstName"`
    LastName        string              `firestore:"LastName"`
    EmailAddress    string              `firestore:"EmailAddress"`
    Address         string              `firestore:"Address"`
    Tokens          map[string]string   `firestore:"Tokens"`
}

func main() {
    user := User{
        FirstName:      "John",
        LastName:       "Smith",
        EmailAddress:   "jsmith@email.com",
        Address:        []string{"123 Street", "2nd Building"},
        Tokens: map[string]string{
            "Android": "cHzDGYfl5G8vnNCd9xQsbZ:APA...",
        },
    }

    err := fuegoClient.Document("users", "jsmith").Create(ctx, user)
    if err != nil {
        panic(err)
    }
}
Retrieve
user := User{}
err := fuegoClient.Document("users", "jsmith").Retrieve(ctx, &user)
if err != nil {
    panic(err)
}

fmt.Println("LastName: ", user.LastName) // prints: Smith
Exists

You also may want to only check if a given document exists without providing a struct:

// Note: false will be returned if an error occurs as well
value := fuegoClient.Document("users", "jsmith").Exists(ctx)
fmt.Println("Exists: ", value)

Please read the doc to see all the documents related operations.

Collections

Below the list of operations available for collections (read the doc for more details):

Operation Description Additional Information
Retrieve Retrieve all documents from a collection.
RetrieveWith Retrieve documents from a collection (if they meet the criteras). Uses firestore.Query.
SetForAll Set a field value for all documents in the collection Uses Write Batches.
DeleteAll Removes all documents from a collection. Uses Write Batches.

Please read the doc to see all the collections related operations.

Write Batches

Write Batches allow to group writes together to avoid multiple round trips. They are NOT transactions. More info here.

IMPORTANT: not all operations are compatible with Write Batches.

fuegoClient.StartBatch()

// All **supported** operations executed between here and commit will be batched.
fuegoClient.Document("users", "jsmith").Number("Age").Update(33)
fuegoClient.Document("users", "enorton").String("FirstName").Update("Eddy")
fuegoClient.Document("users", "jdoe").Boolean("Premium").Update(true)

wr, err := fuegoClient.CommitBatch(ctx)
if err != nil {
    panic(err)
}

Integration Tests

  1. Start the Firestore emulator:
firebase emulators:start --only firestore
  1. Run the tests
go test . -v

Dependencies

  • Firebase: firebase.google.com/go
  • Firestore: cloud.google.com/go/firestore

More info here

License

Apache License Version 2.0

Documentation

Overview

Package fuego provides the necessary to create a client.

Usage

Create a fuego client:

	fuegoClient := fuego.New(firestoreClient)
    /// Your code here...

Note: firestoreClient needs to be created beforehand.

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrBatchWriteNotStarted indicates that the a commit can't happen if the batch write hasn't been started.
	ErrBatchWriteNotStarted = errors.New("fuego: no batch write started")
)

Functions

This section is empty.

Types

type Fuego

type Fuego struct {

	// FirestoreClient is a ptr to a firestore client.
	FirestoreClient *firestore.Client

	// WriteBatch is a ptr to a writebatch.
	// will be nil if not started with StartBatch() or cancelled with CancelBatch().
	WriteBatch *firestore.WriteBatch
}

    Fuego is a wrapper for the Firestore client. Contains the Firestore client.

    func New

    func New(fs *firestore.Client) *Fuego

      New creates and returns a Fuego wrapper.

      func (*Fuego) CancelBatch

      func (f *Fuego) CancelBatch()

        CancelBatch cancels an on-going write batch (if any).

        func (*Fuego) Collection

        func (f *Fuego) Collection(path string) *collection.FirestoreCollection

          Collection returns a new FirestoreCollection.

          func (*Fuego) CommitBatch

          func (f *Fuego) CommitBatch(ctx context.Context) ([]*firestore.WriteResult, error)

            CommitBatch commits the write batch previously started with StartBatch().

            func (*Fuego) Document

            func (f *Fuego) Document(path, documentID string) *document.FirestoreDocument

              Document returns a new FirestoreDocument.

              func (*Fuego) DocumentWithGeneratedID

              func (f *Fuego) DocumentWithGeneratedID(path string) *document.FirestoreDocument

                DocumentWithGeneratedID returns a new FirestoreDocument without ID.

                func (*Fuego) StartBatch

                func (f *Fuego) StartBatch()

                  StartBatch starts a write batch. Write operations that follow will be added to the batch and processed when CommitBatch is called.

                  Directories

                  Path Synopsis
                  Package collection provides generic methods to interact with Firestore collections.
                  Package collection provides generic methods to interact with Firestore collections.
                  Package document provides generic methods to interact with Firestore documents.
                  Package document provides generic methods to interact with Firestore documents.