firebase

package module
v0.0.0-...-a9cfc41 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Sep 28, 2018 License: MIT Imports: 21 Imported by: 2

README

About firebase

Package firebase provides a Firebase v3+ compatible API.

Installation

Install in the usual way:

go get -u github.com/knq/firebase

Usage

Please see the GoDoc API page for a full API listing.

Below is a short example showing basic usage. Additionally, a more complete examples are available.

package main

import (
	"flag"
	"log"
	"time"

	"golang.org/x/net/context"

	"github.com/knq/firebase"
)

type Person struct {
	Name      string                   `json:"name"`
	Birthdate time.Time                `json:"birth_date"`
	Created   firebase.ServerTimestamp `json:"created"`
}

var (
	flagCredentialsFile = flag.String("c", "test-1470ffbcc1d8.json", "credentials file")
)

func main() {
	var err error

	flag.Parse()

	// create initial firebase database ref using Google service account
	// credentials as downloaded from the Google cloud console
	db, err := firebase.NewDatabaseRef(
		firebase.GoogleServiceAccountCredentialsFile(*flagCredentialsFile),
	)
	if err != nil {
		log.Fatal(err)
	}

	// set up a watch context
	ctxt, cancel := context.WithCancel(context.Background())
	defer cancel()

	// start watch
	go startWatch(db.Ref("/people"), ctxt)

	// do a short wait (otherwise the watch won't start in time to see the
	// calls below)
	time.Sleep(5 * time.Second)

	john := &Person{
		Name:      "john doe",
		Birthdate: time.Now().Add(-18 * 365 * 24 * time.Hour),
	}

	// push john
	log.Printf("pushing: %+v", john)
	id, err := db.Ref("/people").Push(john)
	if err != nil {
		log.Fatal(err)
	}
	log.Printf("created: %s", id)

	// retrieve john
	var res Person
	err = db.Ref("/people/" + id).Get(&res)
	if err != nil {
		log.Fatal(err)
	}
	log.Printf("retrieved: %+v", res)

	// set john (causes all values to be overwritten)
	john.Name = "Jon Dunce"
	err = db.Ref("/people/" + id).Set(john)
	if err != nil {
		log.Fatal(err)
	}

	// update a value on john
	err = db.Ref("/people/" + id).Update(map[string]interface{}{
		"nickname": "JD",
	})
	if err != nil {
		log.Fatal(err)
	}

	// retrieve a shallow map (ie, the keys)
	keys := make(map[string]interface{})
	err = db.Ref("/people").Get(&keys, firebase.Shallow)
	if err != nil {
		log.Fatal(err)
	}
	log.Printf("keys: %+v", keys)

	// delete keys
	for key, _ := range keys {
		err = db.Ref("/people/" + key).Remove()
		if err != nil {
			log.Fatal(err)
		}
		log.Printf("deleted: %s", key)
	}

	// wait before returning to see at least one keep alive event
	time.Sleep(45 * time.Second)
}

func startWatch(r *firebase.Ref, ctxt context.Context) {
	log.Printf("starting watch on %s", r.URL().String())
	evs, err := r.Watch(ctxt)
	if err != nil {
		log.Fatal(err)
	}

	for {
		select {
		case e := <-evs:
			if e == nil {
				log.Printf("events channel closed")
				return
			}
			log.Printf("server event: %s", e.String())
		case <-ctxt.Done():
			log.Printf("context done")
			return
		}
	}
}

Documentation

Overview

Package firebase provides Firebase v3+ compatible clients.

Index

Constants

View Source
const (
	// DefaultTokenExpiration is the default expiration for generated OAuth2
	// tokens.
	DefaultTokenExpiration = 1 * time.Hour
)
View Source
const (
	// DefaultWatchBuffer is the default length of an event channel created on
	// a call to Watch.
	DefaultWatchBuffer = 64
)

Variables

View Source
var GeneratePushID func() string

GeneratePushID generates a unique, 20-character ID for use with Firebase, using the default Push ID generator.

Functions

func Do

func Do(op OpType, r *DatabaseRef, v, d interface{}, opts ...QueryOption) error

Do executes an HTTP operation on Firebase database ref r passing the supplied value v as JSON marshaled data and decoding the response to d.

func Get

func Get(r *DatabaseRef, d interface{}, opts ...QueryOption) error

Get retrieves the values stored at Firebase database ref r and decodes them into d.

func GetRulesJSON

func GetRulesJSON(r *DatabaseRef) ([]byte, error)

GetRulesJSON retrieves the security rules for Firebase database ref r.

func Listen

func Listen(r *DatabaseRef, ctxt context.Context, eventTypes []EventType, opts ...QueryOption) <-chan *Event

Listen listens on a Firebase ref for any of the the specified eventTypes, emitting them on the returned channel.

The returned channel is closed only when the context is done. If the Firebase connection closes, or the auth token is revoked, then Listen will continue to reattempt connecting to the Firebase ref.

NOTE: the Log option will not work with Watch/Listen. events from the server.

func PrintPretty

func PrintPretty(v url.Values) error

PrintPretty is a query option that toggles pretty formatting for query results.

func Push

func Push(r *DatabaseRef, v interface{}, opts ...QueryOption) (string, error)

Push pushes values v to Firebase database ref r, returning the name (ID) of the pushed node.

func Remove

func Remove(r *DatabaseRef, opts ...QueryOption) error

Remove removes the values stored at Firebase database ref r.

func Set

func Set(r *DatabaseRef, v interface{}, opts ...QueryOption) error

Set stores values v at Firebase database ref r.

func SetRules

func SetRules(r *DatabaseRef, v interface{}) error

SetRules sets the security rules for Firebase database ref r.

func SetRulesJSON

func SetRulesJSON(r *DatabaseRef, buf []byte) error

SetRulesJSON sets the JSON-encoded security rules for Firebase database ref r.

func Shallow

func Shallow(v url.Values) error

Shallow is a query option that toggles a query to return shallow result (ie, the keys only).

func Update

func Update(r *DatabaseRef, v interface{}, opts ...QueryOption) error

Update updates the values stored at Firebase database ref r to v.

func Watch

func Watch(r *DatabaseRef, ctxt context.Context, opts ...QueryOption) (<-chan *Event, error)

Watch watches a Firebase ref for events, emitting encountered events on the returned channel. Watch ends when the passed context is done, when the remote connection is closed, or when an error is encountered while reading data.

NOTE: the Log option will not work with Watch/Listen. events from the server.

Types

type DatabaseRef

type DatabaseRef struct {
	// contains filtered or unexported fields
}

DatabaseRef is a Firebase database reference.

func NewDatabaseRef

func NewDatabaseRef(opts ...Option) (*DatabaseRef, error)

NewDatabaseRef creates a new Firebase base database ref using the supplied options.

func (*DatabaseRef) Get

func (r *DatabaseRef) Get(d interface{}, opts ...QueryOption) error

Get retrieves the values stored at the Firebase database ref and decodes them into d.

func (*DatabaseRef) GetRulesJSON

func (r *DatabaseRef) GetRulesJSON() ([]byte, error)

GetRulesJSON retrieves the security rules for the Firebase database ref.

func (*DatabaseRef) Listen

func (r *DatabaseRef) Listen(ctxt context.Context, eventTypes []EventType, opts ...QueryOption) <-chan *Event

Listen listens on the Firebase database ref for any of the the specified eventTypes, emitting them on the returned channel.

The returned channel is closed only when the context is done. If the Firebase connection closes, or the auth token is revoked, then Listen will continue to reattempt connecting to the Firebase database ref.

NOTE: the Log option will not work with Watch/Listen.

func (*DatabaseRef) Push

func (r *DatabaseRef) Push(v interface{}, opts ...QueryOption) (string, error)

Push pushes values v to the Firebase database ref, returning the name (ID) of the pushed node.

func (*DatabaseRef) Ref

func (r *DatabaseRef) Ref(path string, opts ...Option) *DatabaseRef

Ref creates a new Firebase database child ref, locked to the specified path.

NOTE: any Option passed returning an error will cause this func to panic. Instead if an Option might return an error, then it should be applied after the child ref has been created in the following manner:

    child := db.Ref("/path/to/child")
    err := SomeOption(child)
	   if err != nil { log.Fatal(err) }

func (*DatabaseRef) Remove

func (r *DatabaseRef) Remove(opts ...QueryOption) error

Remove removes the values stored at the Firebase database ref.

func (*DatabaseRef) Set

func (r *DatabaseRef) Set(v interface{}, opts ...QueryOption) error

Set stores values v at the Firebase database ref.

func (*DatabaseRef) SetRules

func (r *DatabaseRef) SetRules(v interface{}) error

SetRules sets the security rules for the Firebase database ref.

func (*DatabaseRef) SetRulesJSON

func (r *DatabaseRef) SetRulesJSON(buf []byte) error

SetRulesJSON sets the JSON-encoded security rules for the Firebase database ref.

func (*DatabaseRef) URL

func (r *DatabaseRef) URL() *url.URL

URL returns the URL for the Firebase database ref.

func (*DatabaseRef) Update

func (r *DatabaseRef) Update(v interface{}, opts ...QueryOption) error

Update updates the values stored at the Firebase database ref to v.

func (*DatabaseRef) Watch

func (r *DatabaseRef) Watch(ctxt context.Context, opts ...QueryOption) (<-chan *Event, error)

Watch watches the Firebase database ref for events, emitting encountered events on the returned channel. Watch ends when the passed context is done, when the remote connection is closed, or when an error is encountered while reading events from the server.

NOTE: the Log option will not work with Watch/Listen.

type Error

type Error struct {
	Err string `json:"error"`
}

Error is a general Firebase error.

func (*Error) Error

func (e *Error) Error() string

Error satisfies the error interface.

type Event

type Event struct {
	Type EventType
	Data []byte
}

Event is a Firebase server side event emitted from Watch and Listen.

func (Event) String

func (e Event) String() string

String satisfies the stringer interface.

type EventType

type EventType string

EventType is a Firebase event type.

const (

	// EventTypePut is the event type sent when new data is inserted to a
	// watched Firebase ref.
	EventTypePut EventType = "put"

	// EventTypePatch is the event type sent when data is updated at a watched
	// Firebase ref.
	EventTypePatch EventType = "patch"

	// EventTypeKeepAlive is the event type sent when a keep alive is
	// encountered.
	EventTypeKeepAlive EventType = "keep-alive"

	// EventTypeCancel is the event type sent when the Firebase security rules
	// on the watched ref are altered to no longer allow the auth token to read
	// data at the watched ref.
	EventTypeCancel EventType = "cancel"

	// EventTypeAuthRevoked is the event type sent when the auth token is
	// revoked or expired.
	EventTypeAuthRevoked EventType = "auth_revoked"

	// EventTypeClosed is the event type sent when the connection with the
	// Firebase server is closed.
	EventTypeClosed EventType = "closed"

	// EventTypeUnknownError is the event type sent when an unknown error is
	// encountered.
	EventTypeUnknownError EventType = "unknown_error"

	// EventTypeMalformedEventError is the event type sent when a malformed
	// event is read from the Firebase server.
	EventTypeMalformedEventError EventType = "malformed_event_error"

	// EventTypeMalformedDataError is the event type sent when malformed data
	// is read from the Firebase server.
	EventTypeMalformedDataError EventType = "malformed_data_error"
)

func (EventType) String

func (e EventType) String() string

String satisfies the stringer interface.

type IDGen

type IDGen struct {
	// contains filtered or unexported fields
}

IDGen holds the information related to generating a Push ID.

func NewPushIDGenerator

func NewPushIDGenerator(r *rand.Rand) (*IDGen, error)

NewPushIDGenerator creates a new Push ID generator.

func (*IDGen) GeneratePushID

func (ig *IDGen) GeneratePushID() string

GeneratePushID generates a unique, 20-character ID for use with Firebase.

type Logf

type Logf func(string, ...interface{})

Logf is a logging func.

type OpType

type OpType string

OpType is the Firebase operation type.

const (
	// OpTypeGet is the Firebase Push operation.
	OpTypeGet OpType = "GET"

	// OpTypePush is the Firebase Push operation.
	OpTypePush OpType = "POST"

	// OpTypeSet is the Firebase Set operation.
	OpTypeSet OpType = "PUT"

	// OpTypeUpdate is the Firebase Update operation.
	OpTypeUpdate OpType = "PATCH"

	// OpTypeRemove is the Firebase Remove operation.
	OpTypeRemove OpType = "DELETE"
)

type Option

type Option func(r *DatabaseRef) error

Option is an option to modify a Firebase database ref.

func DefaultAuthOverride

func DefaultAuthOverride(val interface{}) Option

DefaultAuthOverride is an option that sets the default auth_variable_override variable on the database ref.

func DefaultAuthUID

func DefaultAuthUID(uid string) Option

DefaultAuthUID is an option that sets the default auth user id ("uid") via the auth_variable_override on the database ref.

func DefaultQueryOptions

func DefaultQueryOptions(opts ...QueryOption) Option

DefaultQueryOptions is an option that sets the default query options on the database ref.

func GoogleComputeCredentials

func GoogleComputeCredentials(serviceAccount string) Option

GoogleComputeCredentials is an option that loads the Google Service Account credentials from the GCE metadata associated with the GCE compute instance. If serviceAccount is empty, then the default service account credentials associated with the GCE instance will be used.

func GoogleServiceAccountCredentialsFile

func GoogleServiceAccountCredentialsFile(path string) Option

GoogleServiceAccountCredentialsFile is an option that loads Google Service Account credentials for use with the Firebase database ref from the specified file.

Google Service Account credentials can be downloaded from the Google Cloud console: https://console.cloud.google.com/iam-admin/serviceaccounts/

func GoogleServiceAccountCredentialsJSON

func GoogleServiceAccountCredentialsJSON(buf []byte) Option

GoogleServiceAccountCredentialsJSON is an option that loads Google Service Account credentials for use with the Firebase database ref from a JSON encoded buf.

Google Service Account credentials can be downloaded from the Google Cloud console: https://console.cloud.google.com/iam-admin/serviceaccounts/

func Log

func Log(requestLogf, responseLogf Logf) Option

Log is an option that writes all HTTP request and response data to the respective logger.

NOTE: this Option will not work with Watch/Listen.

func ProjectID

func ProjectID(projectID string) Option

ProjectID is an option that sets the Firebase database base ref (ie, URL) as https://<projectID>.firebaseio.com/.

func Transport

func Transport(roundTripper http.RoundTripper) Option

Transport is an option to set the underlying HTTP transport used when making requests against a Firebase database ref.

func URL

func URL(urlstr string) Option

URL is an option to set Firebase database base ref (ie, URL) to urlstr.

func WatchBufferLen

func WatchBufferLen(len int) Option

WatchBufferLen is an option that sets the channel buffer size for the returned event channels from Watch and Listen.

type QueryOption

type QueryOption func(url.Values) error

QueryOption is an option used to modify the underlying http.Request for Firebase.

func AuthOverride

func AuthOverride(val interface{}) QueryOption

AuthOverride is a query option that sets the auth_variable_override.

func AuthUID

func AuthUID(uid string) QueryOption

AuthUID is a query option that sets the auth user id ("uid") via the auth_variable_override for a single query.

func EndAt

func EndAt(val interface{}) QueryOption

EndAt is a query option that sets the order by filter to endAt val.

func EqualTo

func EqualTo(val interface{}) QueryOption

EqualTo is a query option that sets the order by filter to equalTo val.

func LimitToFirst

func LimitToFirst(n uint) QueryOption

LimitToFirst is a query option that limit's Firebase's returned results to the first n items.

func LimitToLast

func LimitToLast(n uint) QueryOption

LimitToLast is a query option that limit's Firebase's returned results to the last n items.

func OrderBy

func OrderBy(field string) QueryOption

OrderBy is a query option that sets Firebase's returned result order.

func StartAt

func StartAt(val interface{}) QueryOption

StartAt is a query option that sets the order by filter to startAt val.

type ServerTimestamp

type ServerTimestamp time.Time

ServerTimestamp provides a json.Marshal'able (and Unmarshal'able) type for use with Firebase.

When this type has a zero value, and is serialized to Firebase, Firebase will store the current time in milliseconds since the Unix epoch. When the value is unserialized from Firebase, then the stored time (ie, milliseconds since the Unix epoch) will be returned.

func (ServerTimestamp) MarshalJSON

func (st ServerTimestamp) MarshalJSON() ([]byte, error)

MarshalJSON satisfies the json.Marshaler interface.

func (ServerTimestamp) String

func (st ServerTimestamp) String() string

String satisfies the stringer interface.

func (ServerTimestamp) Time

func (st ServerTimestamp) Time() time.Time

Time returns the ServerTimestamp as time.Time.

func (*ServerTimestamp) UnmarshalJSON

func (st *ServerTimestamp) UnmarshalJSON(buf []byte) error

UnmarshalJSON satisfies the json.Unmarshaler interface.

type Time

type Time time.Time

Time provides a json.Marshal'able (and Unmarshal'able) type for that is compatible with Firebase server timestamps.

The Firebase representation of time is a JSON Number of milliseconds since the Unix epoch.

func (Time) MarshalJSON

func (t Time) MarshalJSON() ([]byte, error)

MarshalJSON satisfies the json.Marshaler interface.

func (Time) String

func (t Time) String() string

String satisfies the stringer interface.

func (Time) Time

func (t Time) Time() time.Time

Time returns the Time as time.Time.

func (*Time) UnmarshalJSON

func (t *Time) UnmarshalJSON(buf []byte) error

UnmarshalJSON satisfies the json.Unmarshaler interface.

Directories

Path Synopsis
cmd
examples
full
example/full/full.go
example/full/full.go
gce
example/gce/gce.go
example/gce/gce.go

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL