robin – go.trulyao.dev/robin Index | Files | Directories

package robin

import "go.trulyao.dev/robin"

Index

Constants

const (
	ProcSeparator = "__"
	ProcNameKey   = ProcSeparator + "proc"

	// Environment variables to control code generation outside of the code
	EnvEnableSchemaGen   = "ROBIN_ENABLE_SCHEMA_GEN"
	EnvEnableBindingsGen = "ROBIN_ENABLE_BINDINGS_GEN"
)

Variables

var (
	// Valid procedure name regex
	ReValidProcedureName = regexp.MustCompile(`(?m)^([a-zA-Z0-9]+)([_\.\-]?[a-zA-Z0-9]+)+$`)

	// Invalid characters in a procedure name
	ReAlphaNumeric = regexp.MustCompile(`[^a-zA-Z0-9]+`)

	// Multiple dots in a procedure name
	ReIllegalDot = regexp.MustCompile(`\.{2,}`)

	// Valid/common words associated with queries
	ReQueryWords = regexp.MustCompile(`(?i)(^(get|fetch|list|lookup|search|find|query|retrieve|show|view|read)\.)`)

	// Valid/common words associated with mutations
	ReMutationWords = regexp.MustCompile(`(?i)(^(create|add|insert|update|upsert|edit|modify|change|delete|remove|destroy)\.)`)
)

Functions

func CorsHandler

func CorsHandler(w http.ResponseWriter, opts *CorsOptions)

func M

func M[R any, B any](name string, fn MutationFn[R, B]) *mutation[R, B]

Alias for `Mutation` to create a new mutation procedure

func Mutation

func Mutation[R any, B any](name string, fn MutationFn[R, B]) *mutation[R, B]

Creates a new mutation with the given name and handler function

func MutationWithMiddleware

func MutationWithMiddleware[R any, B any](
	name string,
	fn MutationFn[R, B],
	middleware ...types.Middleware,
) *mutation[R, B]

Creates a new mutation with the given name, handler function, and middleware functions

func PreflightHandler

func PreflightHandler(w http.ResponseWriter, opts *CorsOptions)

func Q

func Q[R any, B any](name string, fn QueryFn[R, B]) *query[R, B]

Alias for `Query` to create a new query procedure

func Query

func Query[R any, B any](name string, fn QueryFn[R, B]) *query[R, B]

Creates a new query with the given name and handler function

func QueryWithMiddleware

func QueryWithMiddleware[R any, B any](
	name string,
	fn QueryFn[R, B],
	middleware ...types.Middleware,
) *query[R, B]

Creates a new query with the given name, handler function and middleware functions

Types

type CodegenOptions

type CodegenOptions struct {
	// Path to the generated folder for typescript bindings and/or schema
	Path string

	// Whether to generate the typescript bindings or not.
	//
	// NOTE: You can simply generate the schema without the bindings by enabling `GenerateSchema` and disabling this
	//
	// WARNING: If this is enabled and `GenerateSchema` is disabled, the schema will be generated as part of the bindings in the same file
	GenerateBindings bool

	// Whether to generate the typescript schema separately or not
	GenerateSchema bool

	// Whether to use the union result type or not - when enabled, the result type will be a uniion of the Ok and Error types which would disallow access to any of the fields without checking the `ok` field first
	UseUnionResult bool

	// Whether to throw a ProcedureCallError when a procedure call fails for any reason (e.g. invalid payload, user-defined error, etc.) instead of returning an error result
	ThrowOnError bool
}

type Context

type Context = types.Context

Re-exported types

type CorsOptions

type CorsOptions struct {
	// Allowed origins
	Origins []string

	// Allowed headers
	Headers []string

	// Allowed methods
	Methods []string

	// Exposed headers
	ExposedHeaders []string

	// Allow credentials
	AllowCredentials bool

	// Max age
	MaxAge int

	// Preflight headers
	PreflightHeaders map[string]string
}

type Endpoints

type Endpoints []*RestEndpoint

func (Endpoints) String

func (e Endpoints) String() string

String returns the string representation of the rest endpoints

type Error

type Error = types.Error

Re-exported types

type ErrorHandler

type ErrorHandler func(error) (Serializable, int)

type ErrorString

type ErrorString string

func (ErrorString) MarshalJSON

func (e ErrorString) MarshalJSON() ([]byte, error)

type GlobalMiddleware

type GlobalMiddleware struct {
	Name string
	Fn   Middleware
}

type Instance

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

func (*Instance) AttachRestEndpoints

func (i *Instance) AttachRestEndpoints(mux *http.ServeMux, opts *RestApiOptions)

AttachRestEndpoints attaches the RESTful endpoints to the provided mux router automatically

NOTE: If you require more control, look at the `BuildRestEndpoints` and the `BuildProcedureHttpHandler` methods on the `Robin` instance

func (*Instance) BuildProcedureHttpHandler

func (i *Instance) BuildProcedureHttpHandler(procedure Procedure) http.HandlerFunc

BuildProcedureHttpHandler builds an http handler for the given procedure

func (*Instance) BuildRestEndpoints

func (i *Instance) BuildRestEndpoints(
	prefix string,
) Endpoints

BuildRestEndpoints builds the rest endpoints for the robin instance based on the procedures

The prefix is used to prefix the path of the rest endpoints (e.g. /api/v1)

This should be called after all the procedures have been added to the robin instance

func (*Instance) Export

func (i *Instance) Export(optPath ...string) error

Export exports the typescript schema (and bindings; if enabled) to the specified path

func (*Instance) Handler

func (i *Instance) Handler() http.HandlerFunc

Handler returns the robin handler to be used with a custom (mux) router

func (*Instance) Robin

func (i *Instance) Robin() *Robin

Robin returns the internal robin instance which allowes for more control over the instance if ever needed

func (*Instance) Serve

func (i *Instance) Serve(opts ...ServeOptions) error

Serve starts the robin server on the specified port

func (*Instance) SetPort

func (i *Instance) SetPort(port int)

SetPort sets the port to run the server on (default is 8081; to avoid conflicts with other services) WARNING: this only applies when calling `Serve()`, if you're using the default handler, you can set the port directly on the `http.Server` instance, you may have to update the client side to reflect the new port

func (*Instance) SetRoute

func (i *Instance) SetRoute(route string)

SetRoute sets the route to run the robin handler on (default is `/_robin`) WARNING: this only applies when calling `Serve()`, if you're using the default handler, you can set the route using a mux router or similar, ensure that the client side reflects the new route

type Middleware

type Middleware = types.Middleware

Re-exported types

type MutationFn

type MutationFn[ReturnType any, BodyType any] func(ctx *Context, body BodyType) (ReturnType, error)

type Options

type Options struct {
	// Options for controlling code generation
	CodegenOptions CodegenOptions

	// Enable debug mode to log useful info
	EnableDebugMode bool

	// A function that will be called when an error occurs, it should ideally return a marshallable struct
	ErrorHandler ErrorHandler
}

type Procedure

type Procedure = types.Procedure

Re-exported types

type ProcedureType

type ProcedureType = types.ProcedureType

Re-exported types

const (
	ProcedureTypeQuery    ProcedureType = types.ProcedureTypeQuery
	ProcedureTypeMutation ProcedureType = types.ProcedureTypeMutation
)

Re-exported constants

type Procedures

type Procedures []Procedure

func (*Procedures) Add

func (p *Procedures) Add(procedure Procedure)

Add adds a procedure to the procedures map

func (*Procedures) Exists

func (p *Procedures) Exists(name string, procedureType types.ProcedureType) bool

func (*Procedures) Get

func (p *Procedures) Get(name string, procedureType ProcedureType) (Procedure, bool)

Get returns a procedure by name

func (*Procedures) Keys

func (p *Procedures) Keys() []string

func (*Procedures) List

func (p *Procedures) List() []Procedure

List returns the procedures as a slice NOTE: this is retained in case the underlying structure needs to ever change

func (Procedures) Map

func (p Procedures) Map() map[string]Procedure

Map returns the procedures as a map

func (*Procedures) Remove

func (p *Procedures) Remove(name string, procedureType types.ProcedureType)

Remove removes a procedure from the procedures map

type QueryFn

type QueryFn[ReturnType any, ParamsType any] func(ctx *Context, body ParamsType) (ReturnType, error)

type RestApiOptions

type RestApiOptions struct {
	// Enable RESTful endpoints as alternatives to the defualt RPC procedures
	Enable bool

	// Prefix for the RESTful endpoints (default is `/api`)
	Prefix string

	// Whether to attach a 404 handler to the RESTful endpoints (enabled by default)
	DisableNotFoundHandler bool
}

type RestEndpoint

type RestEndpoint struct {
	// Name of the procedure
	ProcedureName string

	// Path to the endpoint e.g. /list.users
	Path string

	// HTTP method to use for the endpoint
	Method types.HttpMethod

	// HTTP method to use for the endpoint
	HandlerFunc http.HandlerFunc
}

func (*RestEndpoint) String

func (re *RestEndpoint) String() string

String returns the string representation of the rest endpoint

type Robin

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

func New

func New(opts Options) (*Robin, error)

Robin is just going to be an adapter for something like Echo

func (*Robin) Add

func (r *Robin) Add(procedure Procedure) *Robin

Add a new procedure to the Robin instance If a procedure with the same name already exists, it will be skipped and a warning will be logged in debug mode

func (*Robin) AddProcedure

func (r *Robin) AddProcedure(procedure Procedure) *Robin

Add a new procedure to the Robin instance - an alias for `Add`

func (*Robin) Build

func (r *Robin) Build() (*Instance, error)

Build the Robin instance

func (*Robin) Debug

func (r *Robin) Debug() bool

Debug returns the debug mode status of the Robin instance

func (*Robin) Use

func (r *Robin) Use(name string, middleware Middleware) *Robin

Use adds a global middleware to the robin instance, these middlewares will be executed before any procedure is called unless explicitly excluded/opted out of The order in which the middlewares are added is the order in which they will be executed before the procedures

WARNING: Global middlewares are ALWAYS executed before the procedure's middleware functions

NOTE: Use `procedure.ExcludeMiddleware(...)` to exclude a middleware from a specific procedure

type RobinError

type RobinError = types.RobinError

Re-exported types

type Serializable

type Serializable interface {
	json.Marshaler
}

A type that can be marshalled to JSON or simply a string

func DefaultErrorHandler

func DefaultErrorHandler(err error) (Serializable, int)

type ServeOptions

type ServeOptions struct {
	// Port to run the server on
	Port int

	// Route to run the robin handler on
	Route string

	// CORS options
	CorsOptions *CorsOptions

	// REST options
	// NOTE: Json API endpoints carry an RPC-style notation by default, if you need to customise this, use the `Alias()` method on the prodecure
	RestApiOptions *RestApiOptions
}

type Void

type Void = types.Void

Re-exported types

Source Files

error.go handle.go instance.go mutation.go procedures.go query.go rest.go robin.go

Directories

PathSynopsis
examples
examples/simple
examples/with-rest-endpoint
generator
generator/templates
internal
types
Version
v0.5.0 (latest)
Published
Nov 23, 2024
Platform
linux/amd64
Imports
14 packages
Last checked
2 weeks ago

Tools for package owners.