backend

package module
v1.5.0 Latest Latest
Warning

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

Go to latest
Published: Jun 14, 2023 License: MIT Imports: 14 Imported by: 1

README

backend-go

Go client library for StaticBackend's backend API

Documentation

Overview

Package backend is a client wrapper for StaticBackend API.

Before using its functions you need to supply a Region and PublicKey.

Example
// it's required to set a PublicKey see: https://staticbackend.com/getting-started/local-dev
backend.PublicKey = "Get from CLI, self-hosted or hosted svc email"

// we're setting the Region to "dev" to use with the CLI
// For self-hosted you may set your backend API URL directly:
// backend.Region = "https://your-server.com/""
backend.Region = backend.RegionLocalDev

// we register a new user
// token is the new user's session token, we need it for all subsequent
// requests
token, err := backend.Register("go@example.com", "my-safe-pw")
if err != nil {
	log.Fatal(err)
}

// let's create a task in a tasks repository
//
// you'd typically create your struct normally, not like this.
task := new(struct {
	ID        string `json:"id"`
	AccountID string `json:"accountId"`
	Title     string `json:"title"`
	Done      bool   `json:"done"`
})

task.Title = "My first to-do item"

if err := backend.Create(token, "tasks", task, &task); err != nil {
	log.Fatal(err)
}

// task.ID and task.AccountID has been automatically set
fmt.Println("ID", task.ID, "AccountID", task.AccountID)

// get the same document to showcase the GetByID function
if err := backend.GetByID(token, "tasks", task.ID, &task); err != nil {
	log.Fatal(err)
}

fmt.Println(task.Title)

Index

Examples

Constants

View Source
const (
	RegionNorthAmerica1 = "na1" // managed hosting region of North-America
	RegionLocalDev      = "dev" // local dev region default to http://localhost:8099
)

Variables

View Source
var (
	PublicKey string
	Verbose   bool
	Region    string
)

PublicKey is required for all HTTP requests.

View Source
var (
	ErrNoDocument       = errors.New("no document found")
	ErrMultipleDocument = errors.New("multiple documents found")
)

Functions

func AddFunction

func AddFunction(token string, fn Function) error

AddFunction adds a server-side function to an account

func AddUser added in v1.5.0

func AddUser(token, email, password string) error

AddUser adds a user into the same account as token

func CacheGet

func CacheGet(token, key string, v interface{}) error

CacheGet retrieves a cache value

func CacheSet

func CacheSet(token, key string, v interface{}) error

CacheSet sets a cache value

func Count added in v1.4.3

func Count(token, repo string, filters []QueryItem) (n int64, err error)

Count returns the number of document in a repo matching the optional filters, which are same query filter as Query.

func Create

func Create(token, repo string, body interface{}, v interface{}) error

Create adds a new document to a repository and returns the created document.

func CreateBulk

func CreateBulk(token, repo string, body interface{}) (bool, error)

CreateBulk creates multiple documents, useful when importing data.

func Del added in v1.4.0

func Del(token, url string) error

Delete sends an HTTP DELETE request to the backend API

func Delete

func Delete(token, repo, id string) error

Delete permanently delets a document

func DeleteBulk added in v1.5.0

func DeleteBulk(token, repo string, filters []QueryItem) error

DeleteBulk permanently deletes multiple documents matching filters

func DeleteFile

func DeleteFile(token, id string) (ok bool, err error)

DeleteFile deletes the file from storage and remove from space used for this account

func DeleteFunction

func DeleteFunction(token, name string) error

DeleteFunction removes a function

func DownloadFile

func DownloadFile(token, fileURL string) (buf []byte, err error)

DownloadFile retrieves the file content as []byte

func FindOne

func FindOne(token, repo string, filters []QueryItem, v interface{}) error

FindOne returns one document if it's found

func Get

func Get(token, url string, v interface{}) error

Get sends an HTTP GET request to the backend API

func GetByID

func GetByID(token, repo, id string, v interface{}) error

GetByID returns a specific document.

func GetPasswordResetCode

func GetPasswordResetCode(token, email string) (string, error)

GetPasswordResetCode returns a unique code for a user to change their password

func Increase

func Increase(token, repo, id, field string, n int) error

Increase increases or decreases a field in a document based on n signed

func ListForm

func ListForm(token, name string) (data []map[string]interface{}, err error)

ListForm returns submissions for all or a specific form.

func Login

func Login(email, password string) (string, error)

Login authenticate a user and returns their session token

func NewSystemAccount

func NewSystemAccount(email string) (string, error)

NewSystemAccount initiates the StaticBackend account creation process.

func Post

func Post(token, url string, body interface{}, v interface{}) error

Post sends an HTTP POST request to the backend API

func Publish added in v1.5.0

func Publish(token, channel, typ string, data interface{}) error

Publish sends a message to a channel (topic) where usually a server-side function will process the message.

func Put

func Put(token, url string, body interface{}, v interface{}) error

Put sends an HTTP POST request to the backend API

func QueueWork added in v1.4.0

func QueueWork(token, key, value string) error

QueueWork adds a work queue value that will be dequeue via WorkerQueue

func Register

func Register(email, password string) (string, error)

Register creates a new user and returns their session token.

func RemoveUser added in v1.5.0

func RemoveUser(token, userID string) error

RemoveUser removes a user from same account as token. Token must have a higher level of permission (role) than deleted user

func ResetPassword

func ResetPassword(email, code, password string) error

ResetPassword changes user password using a unique code

func Search(token, repo, keywords string, v interface{}) error

Search returns the matching document of "repo" based on keywords

func SendMail

func SendMail(token, from, fromName, to, subject, body, replyTo string) (ok bool, err error)

SendMail sends an email

func SetPassword

func SetPassword(token, email, oldPassword, newPassword string) error

SetPassword changes the password of a user

func SudoAddIndex added in v1.4.0

func SudoAddIndex(token, repo, field string) error

SudoAddIndex creates a new database index on a specific field

func SudoCreate

func SudoCreate(token, repo string, body interface{}, v interface{}) error

SudoCreate adds a new document to a repository and returns the created document.

func SudoGetByID

func SudoGetByID(token, repo, id string, v interface{}) error

SudoSudoGetByID returns a specific document if a "root token" is provided.

func SudoGetToken

func SudoGetToken(token, accountID string) (string, error)

SudoGetToken returns a token from an AccountID This is useful when performing creation that documents needs to be attached to a specific account id and therefor the SudoCreate would not work on those cases

func SudoListRepositories

func SudoListRepositories(token string) ([]string, error)

SudoListRepositories lists all database repositories if a "root token" is provided.

func SudoSendSMS added in v1.4.0

func SudoSendSMS(token string, data SMSData) error

SudoSendSMS sends a text message via the Twilio API. You need a valid Twilio AccountSID, AuthToken and phone number.

func SudoUpdate

func SudoUpdate(token, repo, id string, body interface{}, v interface{}) error

SudoUpdate perform an update if a "root" token is specified This call cannot be done from JavaScript, only from a backend HTTP call.

You can obtain this token via the CLI or web interface.

func Update

func Update(token, repo, id string, body interface{}, v interface{}) error

Update updates a document. Can be just a subset of the fields.

func UpdateBulk added in v1.4.3

func UpdateBulk(token, repo string, filters []QueryItem, body interface{}) (n int, err error)

UpdateBulk updates multiple documents based on filter clauses

func UpdateFunction

func UpdateFunction(token string, fn Function) error

UpdateFunction updates a function

func WorkerQueue added in v1.4.0

func WorkerQueue(token, key string, worker WorkerTask)

WorkerQueue monitors a work queue each 5 seconds. If there's new work available it will call the WorkerTask function back. This function should be ran concurrently i.e. go backend.WorkerQueue()

Types

type AccountParams

type AccountParams struct {
	Email    string `json:"email"`
	Password string `json:"password"`
}

AccountParams represents a new StaticBackend account

type ConvertParam added in v1.4.0

type ConvertParam struct {
	// ToPDF indicates if the output is a PDF, otherwise a PNG
	ToPDF bool `json:"toPDF"`
	// URL a publicly available URL
	URL string `json:"url"`
	// FullPage indicates to PNG to screenshot the entire page (still not working)
	FullPage bool `json:"fullpage"`
}

ConvertParam used for the ConvertURLToX request.

type CurrentUser added in v1.4.3

type CurrentUser struct {
	AccountID string `json:"accountId"`
	UserID    string `json:"id"`
	Email     string `json:"email"`
	Role      int    `json:"role"`
}

CurrentUser used to access current user's important information

func Me added in v1.4.3

func Me(token string) (me CurrentUser, err error)

Me returns the current user matching this session token This is the only way to get the user's role, account/user ids and email.

func Users added in v1.5.0

func Users(token string) ([]CurrentUser, error)

Users returns all users for the account linked with this token

type EmailData

type EmailData struct {
	FromName string `json:"fromName"`
	From     string `json:"from"`
	To       string `json:"to"`
	Subject  string `json:"subject"`
	Body     string `json:"body"`
	ReplyTo  string `json:"replyTo"`
}

EmailData used to request the send email process

type Function

type Function struct {
	ID           string       `json:"id"`
	FunctionName string       `json:"name"`
	TriggerTopic string       `json:"trigger"`
	Code         string       `json:"code"`
	Version      int          `json:"version"`
	LastUpdated  time.Time    `json:"lastUpdated"`
	LastRun      time.Time    `json:"lastRun"`
	History      []RunHistory `json:"history"`
}

Function represents a server-side function

func FunctionInfo

func FunctionInfo(token, name string) (fn Function, err error)

FunctionInfo gets info on a function, including execution histories

func ListFunctions

func ListFunctions(token string) (results []Function, err error)

ListFunctions lists all functions for this account

type ListParams

type ListParams struct {
	Page       int
	Size       int
	Descending bool
}

ListParams are used to page results and sort.

type ListResult

type ListResult struct {
	Page     int         `json:"page"`
	PageSize int         `json:"size"`
	Total    int         `json:"total"`
	Results  interface{} `json:"results"`
}

ListResult is used for list document

func Find

func Find(token, repo string, filters []QueryItem, v interface{}, params *ListParams) (meta ListResult, err error)

Find returns a slice of matching documents.

Example
package main

import (
	"fmt"
	"log"

	"github.com/staticbackendhq/backend-go"
)

type TaskItem struct {
	ID        string `json:"id"`
	AccountID string `json:"accountId"`
	Title     string `json:"title"`
	Done      bool   `json:"done"`
}

func main() {
	var filters []backend.QueryItem

	// you may add multiple criteria, they're AND combined
	// No OR available at this time.
	filters = append(filters, backend.QueryItem{
		Field: "done",
		Op:    backend.QueryEqual,
		Value: true,
	})

	params := &backend.ListParams{
		Page:       1,    // current result page
		Size:       5,    // number of item per page
		Descending: true, // sort by created time descending
	}

	var matches []TaskItem
	result, err := backend.Find("session-token", "tasks", filters, &matches, params)
	if err != nil {
		log.Fatal(err)
	}

	fmt.Println("Matches", result.Total, "Data", matches)
}

func List

func List(token, repo string, v interface{}, params *ListParams) (meta ListResult, err error)

List returns a list of document in a specific repository.

func SudoFind

func SudoFind(token, repo string, filters []QueryItem, v interface{}, params *ListParams) (meta ListResult, err error)

SudoFind returns a slice of matching documents if a "root token" is provided.

func SudoList

func SudoList(token, repo string, v interface{}, params *ListParams) (meta ListResult, err error)

SudoList returns a list of documents in a specific repository if a "root token" is used.

type NewSystemAccountData added in v1.5.0

type NewSystemAccountData struct {
	PublicKey     string `json:"pk"`
	RootToken     string `json:"rootToken"`
	AdminPassword string `json:"pw"`
}

NewSystemAccountData when bypassing Stripe, this struct will be returned when creating a new system account.

func NewSystemAccountBypassStripe added in v1.5.0

func NewSystemAccountBypassStripe(email, bypassFlag string) (data NewSystemAccountData, err error)

type QueryItem

type QueryItem struct {
	Field string
	Op    QueryOperator
	Value interface{}
}

QueryItem used to perform query

type QueryOperator

type QueryOperator string
const (
	QueryEqual            QueryOperator = "=="
	QueryNotEqual         QueryOperator = "!="
	QueryLowerThan        QueryOperator = "<"
	QueryLowerThanEqual   QueryOperator = "<="
	QueryGreaterThan      QueryOperator = ">"
	QueryGreaterThanEqual QueryOperator = ">="
	QueryIn               QueryOperator = "in"
	QueryNotIn            QueryOperator = "!in"
)

type RunHistory

type RunHistory struct {
	ID        string    `json:"id"`
	Version   int       `json:"version"`
	Started   time.Time `json:"started"`
	Completed time.Time `json:"completed"`
	Success   bool      `json:"success"`
	Output    []string  `json:"output"`
}

RunHistory represents a function execution result

type SMSData added in v1.4.0

type SMSData struct {
	AccountSID string `json:"accountSID"` // Twilio account SID
	AuthToken  string `json:"authToken"`  // Twilio authentication token
	ToNumber   string `json:"toNumber"`   // Destination number
	FromNumber string `json:"fromNumber"` // Twilio phone number
	Body       string `json:"body"`       // text-message body
}

type StoreFileResult

type StoreFileResult struct {
	ID  string `json:"id"`
	URL string `json:"url"`
}

StoreFileResult incluses the file id and url. The ID is required when deleting file

func ConvertURLToX added in v1.4.0

func ConvertURLToX(token string, data ConvertParam) (res StoreFileResult, err error)

ConvertURLToX converts a URL (web page) to either a PDF or a PNG. The ID and URL of the PDF or PNG is returned.

func ResizeImage added in v1.4.0

func ResizeImage(token, filename string, file io.ReadSeeker, maxWidth float64) (StoreFileResult, error)

ResizeImage upload and resize and image based on the max width allowed. The input image must be a PNG or JPG and the end result will always be a JPG

func StoreFile

func StoreFile(token, filename string, file io.ReadSeeker) (StoreFileResult, error)

StoreFile uploads a new file and returns its public URL using SB CDN.

type WorkerTask added in v1.4.0

type WorkerTask func(val string)

WorkerTask is the function type needed for work queue action

Jump to

Keyboard shortcuts

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