turso

package module
v0.0.4 Latest Latest
Warning

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

Go to latest
Published: Apr 5, 2024 License: Apache-2.0 Imports: 10 Imported by: 2

README

Build status Quality Gate Status

Go-Turso

Golang client for interacting with the Turso Platform API.

Currently supports the following endpoints:

  1. Organizations: List
  2. Groups: List, Get, Create, Delete
  3. Databases: List, Get, Create, Delete
  4. Database Locations: Add, Remove
  5. Database Tokens: Create

Usage

go get github.com/datumforge/go-turso
package main

import (
	"context"
	"fmt"
	"log"
	"os"

	"github.com/datumforge/go-turso"
)

func main() {
	// setup the configuration
	apiToken := os.Getenv("TURSO_API_TOKEN")
	config := turso.Config{
		Token:   apiToken,
		BaseURL: "https://api.turso.tech",
		OrgName: "datum",
	}

	// create the Turso Client
	tc, err := turso.NewClient(config)
	if err != nil {
		log.Fatalf("failed to initialize turso client", "error", err)
	}

	// List All Groups
	groups, err := tc.Group.ListGroups(context.Background())
	if err != nil {
		fmt.Println("error listing groups:", err)

		return
	}

	for _, group := range groups.Groups {
		fmt.Println("Group:", group.Name)
	}

	// List All Databases
	databases, err := tc.Database.ListDatabases(context.Background())
	if err != nil {
		fmt.Println("error listing databases:", err)

		return
	}

	for _, database := range databases.Databases {
		fmt.Println("Database:", database.Name)
	}

	// List All Organizations
	orgs, err := tc.Organization.ListOrganizations(context.Background())
	if err != nil {
		fmt.Println("error listing organizations:", err)

		return
	}

	for _, org := range *orgs {
		fmt.Println("Organization:", org.Name, org.Slug)
	}

	// Create a new Group
	g := turso.CreateGroupRequest{
		Name:     "test-group",
		Location: "ord",
	}

	group, err := tc.Group.CreateGroup(context.Background(), g)
	if err != nil {
		fmt.Println("error creating group:", err)
	}

	fmt.Println("Group Created:", group.Group.Name, group.Group.Locations)

	// Delete the Group
	deletedGroup, err := tc.Group.DeleteGroup(context.Background(), g.Name)
	if err != nil {
		fmt.Println("error deleting group:", err)
	}

	fmt.Println("Group Deleted:", deletedGroup.Group.Name, deletedGroup.Group.Locations)

	// Create a new Database
	d := turso.CreateDatabaseRequest{
		Group:    "default",
		IsSchema: false,
		Name:     "test-database",
	}

	database, err := tc.Database.CreateDatabase(context.Background(), d)
	if err != nil {
		fmt.Println("error creating database:", err)
	}

	fmt.Println("Database Created:", database.Database.Name)

	// Delete the Database
	deletedDatabase, err := tc.Database.DeleteDatabase(context.Background(), d.Name)
	if err != nil {
		fmt.Println("error deleting database:", err)
	}

	fmt.Println("Database Deleted:", deletedDatabase.Database)
}

References

  1. Turso Platform API

Documentation

Overview

Package turso provides a client for interacting with the Turso API.

Index

Constants

View Source
const (
	FullAccess        = "full-access"
	ReadOnly          = "read-only"
	DefaultExpiration = "never"
)

Variables

View Source
var (
	// ErrAPITokenNotSet is returned when the API token is not set
	ErrAPITokenNotSet = errors.New("api token not set, but required")

	// ErrInvalidDatabaseName is returned when a database name is invalid
	ErrInvalidDatabaseName = errors.New("invalid database name, can only contain lowercase letters, numbers, dashes with a maximum of 32 characters")

	// ErrExpirationNotSet is returned when the expiration is not set
	ErrExpirationInvalid = errors.New("expiration invalid, must be a valid duration (e.g. 12w) or never")

	// ErrAuthorizationInvalid is returned when the authorization is invalid
	ErrAuthorizationInvalid = errors.New("authorization invalid, valid options are full-access or read-only")
)

Functions

This section is empty.

Types

type Client

type Client struct {

	// Services
	Organization   organizationService
	Group          groupService
	Database       databaseService
	DatabaseTokens databaseTokensService
	// contains filtered or unexported fields
}

Client manages communication with the Turso API

func NewClient

func NewClient(c Config) (*Client, error)

NewClient creates a new client for interacting with the Turso API.

func NewMockClient added in v0.0.3

func NewMockClient() *Client

NewMockClient creates a new client for interacting with the Turso API to mock ok requests this can be used to test the client without hitting the actual API an expect an 200 OK response.

func (*Client) Client

func (c *Client) Client() HTTPRequestDoer

Client returns the http client

func (*Client) DoRequest

func (c *Client) DoRequest(ctx context.Context, method string, url string, data interface{}) (*http.Response, error)

DoRequest performs an HTTP request and returns the response

type Config

type Config struct {
	// Token is the token used to authenticate with the turso API
	Token string `json:"token" koanf:"token" jsonschema:"required"`
	// BaseURL is the base URL for the turso API
	BaseURL string `json:"baseUrl" koanf:"baseUrl" jsonschema:"required" default:"https://api.turso.tech"`
	// OrgName is the name of the organization to use for the turso API
	OrgName string `json:"orgName" koanf:"orgName" jsonschema:"required"`
}

Config is the configuration for the turso client

type CreateDatabase added in v0.0.3

type CreateDatabase struct {
	// DatabaseID is the ID of the database
	DatabaseID string `json:"DbId"`
	// Name is the name of the database
	Name string `json:"Name"`
	// Hostname is the hostname of the database
	Hostname string `json:"Hostname"`
	// IssuedCertCount is the number of certificates issued
	IssuedCertCount int `json:"IssuedCertCount"`
	// IssuedCertLimit is the limit of certificates that can be issued
	IssuedCertLimit int `json:"IssuedCertLimit"`
}

CreateDatabase is the struct for the Turso API database create request

type CreateDatabaseRequest

type CreateDatabaseRequest struct {
	// Group is the group the database is in
	Group string `json:"group"`
	// IsSchema is this database controls other child databases then this will be true
	IsSchema bool `json:"is_schema"`
	// Name is the name of the database
	// Must contain only lowercase letters, numbers, dashes. No longer than 32 characters.
	Name string `json:"name"`
}

CreateDatabaseRequest is the struct for the Turso API database create request

type CreateDatabaseResponse

type CreateDatabaseResponse struct {
	Database CreateDatabase `json:"database"`
}

CreateDatabaseResponse is the struct for the Turso API database create response

type CreateDatabaseTokenRequest

type CreateDatabaseTokenRequest struct {
	// DatabaseName is the name of the database
	DatabaseName string
	// Expiration is the expiration time for the token
	Expiration string
	// Permissions is the permissions for the token
	Authorization string
	// ReadAttach permission for the token
	AttachPermissions Permissions `json:"permissions"`
}

CreateDatabaseTokenRequest is the struct for the Turso API database token create request

type CreateDatabaseTokenResponse

type CreateDatabaseTokenResponse struct {
	JWT string `json:"jwt"`
}

CreateDatabaseTokenResponse is the struct for the Turso API database token create response

type CreateGroupRequest added in v0.0.2

type CreateGroupRequest struct {
	Extensions string `json:"extensions"`
	Location   string `json:"location"`
	Name       string `json:"name"`
}

CreateGroupRequest is the struct for the Turso API group create request

type CreateGroupResponse

type CreateGroupResponse struct {
	Group Group `json:"group"`
}

CreateGroupResponse is the struct for the Turso API group create response

type Database

type Database struct {
	// Name is the name of the database
	Name string `json:"Name"`
	// DatabaseID is the ID of the database
	DatabaseID string `json:"DbId"`
	// Hostname is the hostname of the database`
	Hostname string `json:"Hostname"` // this is in the response twice, once with a capital H and once with a lowercase h
	// IsSchema is this database controls other child databases then this will be true
	IsSchema bool `json:"is_schema"`
	// Schema is the name of the parent database that owns the schema for this database
	Schema string `json:"schema"`
	// BlockedReads is true if reads are blocked
	BlockReads bool `json:"block_reads"`
	// BlockedWrites is true if writes are blocked
	BlockWrites bool `json:"block_writes"`
	// AllowAttach is true if the database allows attachments of a child database
	AllowAttach bool `json:"allow_attach"`
	// Regions is a list of regions the database is available in
	Regions []string `json:"regions"`
	// PrimaryRegion is the primary region for the database
	PrimaryRegion string `json:"primaryRegion"`
	// Type is the type of the database
	Type string `json:"type"`
	// Version is the version of libsql used by the database
	Version string `json:"version"`
	// Group is the group the database is in
	Group string `json:"group"`
	// Sleeping is true if the database is sleeping
	Sleeping bool `json:"sleeping"`
}

Database is the struct for the Turso Database object

type DatabaseService

type DatabaseService service

DatabaseService is the interface for the Turso API database endpoint

func (*DatabaseService) CreateDatabase

CreateDatabase satisfies the databaseService interface

func (*DatabaseService) DeleteDatabase

func (s *DatabaseService) DeleteDatabase(ctx context.Context, dbName string) (*DeleteDatabaseResponse, error)

DeleteDatabase satisfies the databaseService interface

func (*DatabaseService) GetDatabase

func (s *DatabaseService) GetDatabase(ctx context.Context, dbName string) (*GetDatabaseResponse, error)

GetDatabase satisfies the databaseService interface

func (*DatabaseService) ListDatabases

func (s *DatabaseService) ListDatabases(ctx context.Context) (*ListDatabaseResponse, error)

ListDatabases satisfies the databaseService interface

type DatabaseTokensService

type DatabaseTokensService service

DatabaseTokensService is the interface for the Turso API database tokens service

func (*DatabaseTokensService) CreateDatabaseToken

CreateDatabaseToken satisfies the databaseTokensService interface

type DeleteDatabaseResponse

type DeleteDatabaseResponse struct {
	Database string `json:"database"`
}

DeleteDatabaseResponse is the struct for the Turso API database delete response

type DeleteGroupResponse

type DeleteGroupResponse struct {
	Group Group `json:"group"`
}

DeleteGroupResponse is the struct for the Turso API group delete response

type GetDatabaseResponse

type GetDatabaseResponse struct {
	Database *Database `json:"database"`
}

GetDatabaseResponse is the struct for the Turso API database get response

type GetGroupResponse

type GetGroupResponse struct {
	Group Group `json:"group"`
}

GetGroupResponse is the struct for the Turso API group get response

type Group

type Group struct {
	Archived  bool     `json:"archived"`
	Locations []string `json:"locations"`
	Name      string   `json:"name"`
	Primary   string   `json:"primary"`
	UUID      string   `json:"uuid"`
	Version   string   `json:"version"`
}

Group is the struct for the Turso API group service

type GroupLocationRequest added in v0.0.2

type GroupLocationRequest struct {
	// GroupName is the name of the group to add the location
	GroupName string
	// Location is the location to add to the group
	Location string
}

GroupLocationRequest is the struct for the Turso API to add or remove a location to a group request

type GroupLocationResponse added in v0.0.2

type GroupLocationResponse struct {
	Group Group `json:"group"`
}

GroupLocationResponse is the struct for the Turso API to add or remove location to group response

type GroupService

type GroupService service

GroupService is the interface for the Turso API group endpoint

func (*GroupService) AddLocation added in v0.0.2

AddLocation satisfies the groupService interface

func (*GroupService) CreateGroup

CreateGroup satisfies the groupService interface

func (*GroupService) DeleteGroup

func (s *GroupService) DeleteGroup(ctx context.Context, groupName string) (*DeleteGroupResponse, error)

DeleteGroup satisfies the groupService interface

func (*GroupService) GetGroup

func (s *GroupService) GetGroup(ctx context.Context, groupName string) (*GetGroupResponse, error)

GetGroup satisfies the groupService interface

func (*GroupService) ListGroups

func (s *GroupService) ListGroups(ctx context.Context) (*ListGroupResponse, error)

ListGroups satisfies the groupService interface

func (*GroupService) RemoveLocation added in v0.0.2

RemoveLocation satisfies the groupService interface

type HTTPRequestDoer

type HTTPRequestDoer interface {
	Do(req *http.Request) (*http.Response, error)
}

HTTPRequestDoer implements the standard http.Client interface.

type InvalidFieldError added in v0.0.2

type InvalidFieldError struct {
	Field   string
	Message string
}

InvalidFieldError is returned when a required field does not meet the required criteria

func (*InvalidFieldError) Error added in v0.0.2

func (e *InvalidFieldError) Error() string

Error returns the InvalidFieldError in string format

type InvalidateDatabaseTokenRequest

type InvalidateDatabaseTokenRequest struct {
	// DatabaseName is the name of the database
	DatabaseName string `json:"database_name"`
}

InvalidateDatabaseTokenRequest is the struct for the Turso API database token invalidate request

type ListDatabaseResponse

type ListDatabaseResponse struct {
	Databases []*Database `json:"databases"`
}

ListDatabaseResponse is the struct for the Turso API database list response

type ListGroupResponse

type ListGroupResponse struct {
	Groups []Group `json:"groups"`
}

ListGroupResponse is the struct for the Turso API group list response

type MissingRequiredFieldError added in v0.0.2

type MissingRequiredFieldError struct {
	// RequiredField that is missing
	RequiredField string
}

MissingRequiredFieldError is returned when a required field was not provided in a request

func (*MissingRequiredFieldError) Error added in v0.0.2

func (e *MissingRequiredFieldError) Error() string

Error returns the MissingRequiredFieldError in string format

type MockDatabaseService added in v0.0.3

type MockDatabaseService struct {
	ListDatabaseResponse   *ListDatabaseResponse
	CreateDatabaseResponse *CreateDatabaseResponse
	GetDatabaseResponse    *GetDatabaseResponse
	DeleteDatabaseResponse *DeleteDatabaseResponse
	Error                  error
}

func (*MockDatabaseService) CreateDatabase added in v0.0.3

func (*MockDatabaseService) DeleteDatabase added in v0.0.3

func (md *MockDatabaseService) DeleteDatabase(ctx context.Context, dbName string) (*DeleteDatabaseResponse, error)

func (*MockDatabaseService) GetDatabase added in v0.0.3

func (md *MockDatabaseService) GetDatabase(ctx context.Context, dbName string) (*GetDatabaseResponse, error)

func (*MockDatabaseService) ListDatabases added in v0.0.3

func (md *MockDatabaseService) ListDatabases(ctx context.Context) (*ListDatabaseResponse, error)

type MockDatabaseTokensService added in v0.0.3

type MockDatabaseTokensService struct {
	CreateDatabaseTokenResponse *CreateDatabaseTokenResponse
	Error                       error
}

func (*MockDatabaseTokensService) CreateDatabaseToken added in v0.0.3

type MockGroupService added in v0.0.3

type MockGroupService struct {
	ListGroupResponse     *ListGroupResponse
	CreateGroupResponse   *CreateGroupResponse
	GetGroupResponse      *GetGroupResponse
	DeleteGroupResponse   *DeleteGroupResponse
	GroupLocationResponse *GroupLocationResponse
	Error                 error
}

func (*MockGroupService) AddLocation added in v0.0.3

func (*MockGroupService) CreateGroup added in v0.0.3

func (*MockGroupService) DeleteGroup added in v0.0.3

func (mg *MockGroupService) DeleteGroup(ctx context.Context, groupName string) (*DeleteGroupResponse, error)

func (*MockGroupService) GetGroup added in v0.0.3

func (mg *MockGroupService) GetGroup(ctx context.Context, groupName string) (*GetGroupResponse, error)

func (*MockGroupService) ListGroups added in v0.0.3

func (mg *MockGroupService) ListGroups(ctx context.Context) (*ListGroupResponse, error)

func (*MockGroupService) RemoveLocation added in v0.0.3

type MockHTTPRequestDoer added in v0.0.3

type MockHTTPRequestDoer struct {
	Response *http.Response
	Error    error
}

MockHTTPRequestDoer implements the standard http.Client interface.

func (*MockHTTPRequestDoer) Do added in v0.0.3

Do implements the standard http.Client interface for MockHTTPRequestDoer

type MockOrganizationService added in v0.0.3

type MockOrganizationService struct {
	ListOrganizationsResponse *[]Organization
	Error                     error
}

func (*MockOrganizationService) ListOrganizations added in v0.0.3

func (mo *MockOrganizationService) ListOrganizations(ctx context.Context) (*[]Organization, error)

type Organization

type Organization struct {
	Name          string `json:"name"`
	Slug          string `json:"slug"`
	Type          string `json:"type"`
	PlanID        string `json:"plan_id"`
	Overages      bool   `json:"overages"`
	BlockedReads  bool   `json:"blocked_reads"`
	BlockedWrites bool   `json:"blocked_writes"`
	PlanTimeline  string `json:"plan_timeline"`
	Memory        int    `json:"memory"`
}

Organization is the struct for the Turso Organization object

type OrganizationService

type OrganizationService service

func (*OrganizationService) ListOrganizations

func (s *OrganizationService) ListOrganizations(ctx context.Context) (*[]Organization, error)

ListOrganizations satisfies the organizationService interface

type Permissions

type Permissions struct {
	ReadAttach struct {
		Database []string `json:"database"`
	} `json:"read_attach"`
}

type TursoError

type TursoError struct {
	// Object is the object that the error occurred on
	Object string
	// Method is the method that the error occurred in
	Method string
	// Status is the status code of the error
	Status int
}

TursoError is returned when a request to the Turso API fails

func (*TursoError) Error

func (e *TursoError) Error() string

Error returns the RequiredFieldMissingError in string format

Jump to

Keyboard shortcuts

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