core

package
v0.15.16-0...-9fff2f5 Latest Latest
Warning

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

Go to latest
Published: Aug 27, 2020 License: Apache-2.0 Imports: 34 Imported by: 0

Documentation

Overview

Package core provides the primary API to include and use Super Graph with your own code. For detailed documentation visit https://supergraph.dev

Example usage:

package main

import (
	"database/sql"
	"fmt"
	"time"
	"github.com/renathoaz/super-graph/core"
	_ "github.com/jackc/pgx/v4/stdlib"
)

func main() {
	db, err := sql.Open("pgx", "postgres://postgrs:@localhost:5432/example_db")
	if err != nil {
		log.Fatal(err)
	}

	sg, err := core.NewSuperGraph(nil, db)
	if err != nil {
		log.Fatal(err)
	}

	query := `
		query {
			posts {
			id
			title
		}
	}`

	ctx = context.WithValue(ctx, core.UserIDKey, 1)

	res, err := sg.GraphQL(ctx, query, nil)
	if err != nil {
		log.Fatal(err)
	}

}

Index

Constants

View Source
const (
	// Name of the authentication provider. Eg. google, github, etc
	UserIDProviderKey contextkey = iota

	// User ID value for authenticated users
	UserIDKey

	// User role if pre-defined
	UserRoleKey
)

Constants to set values on the context passed to the NewSuperGraph function

Variables

This section is empty.

Functions

func Name

func Name(query string) string

Name function return the operation name from the query. It uses a very fast algorithm to extract the operation name without having to parse the query.

Types

type Column

type Column struct {
	Name       string
	Type       string
	Primary    bool
	ForeignKey string `mapstructure:"related_to"`
}

Column struct defines a database column

type Config

type Config struct {
	// SecretKey is used to encrypt opaque values such as
	// the cursor. Auto-generated if not set
	SecretKey string `mapstructure:"secret_key"`

	// UseAllowList (aka production mode) when set to true ensures
	// only queries lists in the allow.list file can be used. All
	// queries are pre-prepared so no compiling happens and things are
	// very fast.
	UseAllowList bool `mapstructure:"use_allow_list"`

	// AllowListFile if the path to allow list file if not set the
	// path is assumed to be the same as the config path (allow.list)
	AllowListFile string `mapstructure:"allow_list_file"`

	// SetUserID forces the database session variable `user.id` to
	// be set to the user id. This variables can be used by triggers
	// or other database functions
	SetUserID bool `mapstructure:"set_user_id"`

	// DefaultBlock ensures that in anonymous mode (role 'anon') all tables
	// are blocked from queries and mutations. To open access to tables in
	// anonymous mode they have to be added to the 'anon' role config.
	DefaultBlock bool `mapstructure:"default_block"`

	// Vars is a map of hardcoded variables that can be leveraged in your
	// queries (eg. variable admin_id will be $admin_id in the query)
	Vars map[string]string `mapstructure:"variables"`

	// Blocklist is a list of tables and columns that should be filtered
	// out from any and all queries
	Blocklist []string

	// Tables contains all table specific configuration such as aliased tables
	// creating relationships between tables, etc
	Tables []Table

	// RolesQuery if set enabled attributed based access control. This query
	// is used to fetch the user attributes that then dynamically define the users
	// role.
	RolesQuery string `mapstructure:"roles_query"`

	// Roles contains all the configuration for all the roles you want to support
	// `user` and `anon` are two default roles. User role is for when a user ID is
	// available and Anon when it's not.
	//
	// If you're using the RolesQuery config to enable atribute based acess control then
	// you can add more custom roles.
	Roles []Role

	// Inflections is to add additionally singular to plural mappings
	// to the engine (eg. sheep: sheep)
	Inflections map[string]string `mapstructure:"inflections"`

	// Database schema name. Defaults to 'public'
	DBSchema string `mapstructure:"db_schema"`

	// Log warnings and other debug information
	Debug bool

	// Useful for quickly debugging. Please set to false in production
	CredsInVars bool `mapstructure:"creds_in_vars"`

	// Subscriptions poll the database to query for updates
	// this sets the duration (in seconds) between requests.
	// Defaults to 5 seconds
	PollDuration time.Duration `mapstructure:"poll_every_seconds"`
}

Core struct contains core specific config value

func ReadInConfig

func ReadInConfig(configFile string) (*Config, error)

ReadInConfig function reads in the config file for the environment specified in the GO_ENV environment variable. This is the best way to create a new Super Graph config.

func (*Config) AddRoleTable

func (c *Config) AddRoleTable(role, table string, conf interface{}) error

AddRoleTable function is a helper function to make it easy to add per-table row-level config

type Delete

type Delete struct {
	Filters []string
	Columns []string
	Block   bool
}

Delete struct contains access control values for delete operations

type Insert

type Insert struct {
	Filters []string
	Columns []string
	Presets map[string]string
	Block   bool
}

Insert struct contains access control values for insert operations

type Member

type Member struct {
	Result chan *Result
	// contains filtered or unexported fields
}

func (*Member) String

func (m *Member) String() string

func (*Member) Unsubscribe

func (m *Member) Unsubscribe()

type OpType

type OpType int
const (
	OpUnknown OpType = iota
	OpQuery
	OpSubscription
	OpMutation
)

func Operation

func Operation(query string) OpType

Operation function return the operation type from the query. It uses a very fast algorithm to extract the operation without having to parse the query.

type Query

type Query struct {
	Limit            int
	Filters          []string
	Columns          []string
	DisableFunctions bool `mapstructure:"disable_functions"`
	Block            bool
}

Query struct contains access control values for query operations

type Remote

type Remote struct {
	Name        string
	ID          string
	Path        string
	URL         string
	Debug       bool
	PassHeaders []string `mapstructure:"pass_headers"`
	SetHeaders  []struct {
		Name  string
		Value string
	} `mapstructure:"set_headers"`
}

Remote struct defines a remote API endpoint

type Result

type Result struct {
	Error      string          `json:"message,omitempty"`
	Data       json.RawMessage `json:"data,omitempty"`
	Extensions *extensions     `json:"extensions,omitempty"`
	// contains filtered or unexported fields
}

Result struct contains the output of the GraphQL function this includes resulting json from the database query and any error information

func (*Result) Operation

func (r *Result) Operation() OpType

func (*Result) OperationName

func (r *Result) OperationName() string

func (*Result) QueryName

func (r *Result) QueryName() string

func (*Result) Role

func (r *Result) Role() string

func (*Result) SQL

func (r *Result) SQL() string

type Role

type Role struct {
	Name   string
	Match  string
	Tables []RoleTable
	// contains filtered or unexported fields
}

Role struct contains role specific access control values for for all database tables

func (*Role) GetTable

func (r *Role) GetTable(name string) *RoleTable

type RoleTable

type RoleTable struct {
	Name     string
	ReadOnly bool `mapstructure:"read_only"`

	Query  *Query
	Insert *Insert
	Update *Update
	Upsert *Upsert
	Delete *Delete
}

RoleTable struct contains role specific access control values for a database table

type SuperGraph

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

SuperGraph struct is an instance of the Super Graph engine it holds all the required information like datase schemas, relationships, etc that the GraphQL to SQL compiler would need to do it's job.

func NewSuperGraph

func NewSuperGraph(conf *Config, db *sql.DB) (*SuperGraph, error)

NewSuperGraph creates the SuperGraph struct, this involves querying the database to learn its schemas and relationships

func (*SuperGraph) GraphQL

func (sg *SuperGraph) GraphQL(c context.Context, query string, vars json.RawMessage) (*Result, error)

GraphQL function is called on the SuperGraph struct to convert the provided GraphQL query into an SQL query and execute it on the database. In production mode prepared statements are directly used and no query compiling takes places.

In developer mode all names queries are saved into a file `allow.list` and in production mode only queries from this file can be run.

func (*SuperGraph) GraphQLSchema

func (sg *SuperGraph) GraphQLSchema() (string, error)

GraphQLSchema function return the GraphQL schema for the underlying database connected to this instance of Super Graph

func (*SuperGraph) Subscribe

func (sg *SuperGraph) Subscribe(c context.Context, query string, vars json.RawMessage) (*Member, error)

type Table

type Table struct {
	Name      string
	Table     string
	Type      string
	Blocklist []string
	Remotes   []Remote
	Columns   []Column
}

Table struct defines a database table

type Update

type Update struct {
	Filters []string
	Columns []string
	Presets map[string]string
	Block   bool
}

Insert struct contains access control values for update operations

type Upsert

type Upsert struct {
	Filters []string
	Columns []string
	Presets map[string]string
	Block   bool
}

Directories

Path Synopsis
internal
crypto
Provides symmetric authenticated encryption using 256-bit AES-GCM with a random nonce.
Provides symmetric authenticated encryption using 256-bit AES-GCM with a random nonce.

Jump to

Keyboard shortcuts

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