core

package
v0.15.49 Latest Latest
Warning

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

Go to latest
Published: Dec 16, 2020 License: Apache-2.0 Imports: 35 Imported by: 1

Documentation

Overview

Package core provides the primary API to include and use GraphJin with your own code. For detailed documentation visit https://graphjin.com

Example usage:

package main

import (
	"database/sql"
	"fmt"
	"time"
	"github.com/dosco/graphjin/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)
	}

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

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

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

	res, err := gj.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 NewGraphJin 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"`

	// DisableAllowList when set to true entirely disables the
	// allow list workflow and all queries are always compiled
	// even in production. (Warning possible security concern)
	DisableAllowList bool `mapstructure:"disable_allow_list"`

	// EnforceAllowList (aka production mode) when set to true ensures
	// only queries saved to the allow list folders can be used.
	EnforceAllowList bool `mapstructure:"enforce_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"`

	// HeaderVars is a map of dynamic variables that map to http header
	// values.
	HeaderVars map[string]string `mapstructure:"header_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 []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"`

	// DefaultLimit sets the default max limit (number of rows) when a
	// limit is not defined in the query or the table role config.
	// Default to 20
	DefaultLimit int `mapstructure:"default_limit"`
}

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 GraphJin 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 GraphJin

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

GraphJin struct is an instance of the GraphJin 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 NewGraphJin

func NewGraphJin(conf *Config, db *sql.DB) (*GraphJin, error)

NewGraphJin creates the GraphJin struct, this involves querying the database to learn its schemas and relationships

func (*GraphJin) GraphQL

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

GraphQL function is called on the GraphJin 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 (*GraphJin) GraphQLEx

func (gj *GraphJin) GraphQLEx(
	c context.Context,
	query string,
	vars json.RawMessage,
	rc *ReqConfig) (*Result, error)

GraphQLEx is the extended version of the GraphQL function allowing for request specific config.

func (*GraphJin) GraphQLSchema

func (gj *GraphJin) GraphQLSchema() (string, error)

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

func (*GraphJin) Subscribe

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

func (*GraphJin) SubscribeEx

func (gj *GraphJin) SubscribeEx(
	c context.Context,
	query string,
	vars json.RawMessage,
	rc *ReqConfig) (*Member, error)

GraphQLEx is the extended version of the Subscribe function allowing for request specific config.

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 ReqConfig

type ReqConfig struct {
	Vars map[string]interface{}
}

ReqConfig is used to pass request specific config values to the GraphQLEx and SubscribeEx functions. Dynamic variables can be set here.

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 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
module
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