mapi

package module
v0.0.8 Latest Latest
Warning

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

Go to latest
Published: Feb 23, 2021 License: MIT Imports: 20 Imported by: 0

README

mapi

Visit https://opposite-bracket.github.io/mapi/ for more information

Documentation

Index

Constants

View Source
const AuthTokenKey string = "x-auth"

AuthTokenKey is the key used to identify

Auth key token received from clients
View Source
const InputLayout = "2006-01-02T15:04:05.000Z"
View Source
const OutputLayout = "2006 01 01"

Variables

View Source
var API *apiServer

API holds a server instance

Functions

func ConvertToJSONBytes added in v0.0.3

func ConvertToJSONBytes(body interface{}) *bytes.Reader

ConvertToJSONBytes convert given interface into bytes

func ConvertToStruct

func ConvertToStruct(data []byte, instance interface{})

ConvertToStruct convert byte data into the given interface

func CreateJwtToken

func CreateJwtToken(payload JWTPayload, jwtSecret string) (string, error)

CreateJwtToken creates a JWT token along with payload

func FatalLog

func FatalLog(msg string, err error)

FatalLog will call log.Fatal if err exists

func GetJSONSeed added in v0.0.3

func GetJSONSeed(fixturePath string, data interface{})

GetJSONSeed will load data from a json file and turn it

into a struct

func HashAndSalt

func HashAndSalt(plain string) string

HashAndSalt creates a salted hash out of a plain text

func ValidateHash

func ValidateHash(hash string, plain string) bool

ValidateHash validates a previously hashed password

with its plain formatted counterpart

Types

type APIError added in v0.0.3

type APIError struct {
	Message string    `json:"message,omitempty"`
	Code    ErrorCode `json:"code,omitempty"`
}

APIError is an individual error in an endpoint

func ValidateRequest

func ValidateRequest(request interface{}) []APIError

ValidateRequest will validate the request received from a client

and convert the errors (if applicable) into a list
of APIErrors

type ConfigOptions

type ConfigOptions struct {
	ServerAddress string        `json:"serverAddress,omitempty"`
	Cors          CorsOptions   `json:"cors,omitempty"`
	Env           EnvInfo       `json:"env,omitempty"`
	JwtSecret     string        `json:"jwtSecret,omitempty"`
	DbURL         string        `json:"dbURL,omitempty"`
	DbName        string        `json:"dbName,omitempty"`
	DbTimeout     time.Duration `json:"DbTimeout,omitempty"`
}

ConfigOptions holds all configuration options

var Config *ConfigOptions

Config stores server configuration information

func (*ConfigOptions) LoadDotEnv added in v0.0.4

func (config *ConfigOptions) LoadDotEnv(env string)

LoadDotEnv loads file which contains environment variables

func (*ConfigOptions) SetCors

func (config *ConfigOptions) SetCors(options CorsOptions)

SetCors allows api to configure CORS options with CorsOptions struct

func (*ConfigOptions) SetDbName

func (config *ConfigOptions) SetDbName(dbName string)

SetDbName set database name

func (*ConfigOptions) SetDbURL added in v0.0.3

func (config *ConfigOptions) SetDbURL(dbURL string)

SetDbURL holds Mongo URL connection

func (*ConfigOptions) SetDeployment

func (config *ConfigOptions) SetDeployment(deployment string)

SetDeployment is the id of the deployment that released the code

func (*ConfigOptions) SetEnv

func (config *ConfigOptions) SetEnv(env string)

SetEnv environment variable (local, dev, stg, prd)

func (*ConfigOptions) SetJwtSecret

func (config *ConfigOptions) SetJwtSecret(jwtSecret string)

SetJwtSecret allows api to configure CORS options with CorsOptions struct

func (*ConfigOptions) SetVersion

func (config *ConfigOptions) SetVersion(version string)

SetVersion sets the version of project (eg. v0.0.1)

type CorsOptions

type CorsOptions struct {
	Origins string `json:"origins,omitempty"`
	Headers string `json:"headers,omitempty"`
	Methods string `json:"methods,omitempty"`
}

CorsOptions holds information to serve CORS on APIs

type EnvInfo

type EnvInfo struct {
	Env        string `json:"env,omitempty"`
	Version    string `json:"version,omitempty"`
	Deployment string `json:"deployment,omitempty"`
}

EnvInfo holds information associated to the server environment

func (*EnvInfo) ToString

func (info *EnvInfo) ToString() string

ToString prints out the Env, Version and Deployment set

type ErrorCode

type ErrorCode string

ErrorCode is an enum that describes an error

const (
	// NotFound error takes place when a resource is not found
	NotFound ErrorCode = "E_1"
	// InvalidData error takes place when invalid data has been received
	InvalidData ErrorCode = "E_2"
	// InternalError takes place when an unexpected scenario took place
	InternalError ErrorCode = "E_3"
	// Duplicate error takes place when a resource is duplicated
	Duplicate ErrorCode = "E_4"
)

type ErrorResponse

type ErrorResponse struct {
	Errors []APIError `json:"errors,omitempty"`
}

ErrorResponse is an API response when something goes wrong

type FromDate added in v0.0.7

type FromDate struct {
	time.Time
}

func NewFromDate added in v0.0.7

func NewFromDate() FromDate

func NewFromDateByStr added in v0.0.7

func NewFromDateByStr(str string) (*FromDate, error)

func ParseDateString added in v0.0.7

func ParseDateString(str string) (*FromDate, error)

func (FromDate) MarshalJSON added in v0.0.7

func (d FromDate) MarshalJSON() ([]byte, error)

func (*FromDate) UnmarshalJSON added in v0.0.7

func (d *FromDate) UnmarshalJSON(buf []byte) error

type HandlerFunc

type HandlerFunc func(context *RequestContext)

HandlerFunc handles an API request and provides various utilities

type JWTPayload

type JWTPayload struct {
	UserID   primitive.ObjectID `json:"userId"`
	TenantID primitive.ObjectID `json:"tenantId"`
}

JWTPayload store tenantId and userId

func ValidateJwtToken

func ValidateJwtToken(tokenString string, jwtSecret string) (JWTPayload, error)

ValidateJwtToken ensures that token is valid, extracts & retrieves payload

type Model

type Model struct {
	Collection *mongo.Collection
}

Model defines a collection

func NewModel

func NewModel(name string) (*Model, error)

NewModel creates a collection

func (*Model) DeleteByID added in v0.0.3

func (model *Model) DeleteByID(id primitive.ObjectID) (*mongo.DeleteResult, error)

DeleteByID deletes DB with default 10 second context timeout

func (*Model) FindByID added in v0.0.3

func (model *Model) FindByID(id primitive.ObjectID, data interface{}) error

FindByID finds DB with default 10 second context timeout

func (*Model) FindByIDAndTenantInfo added in v0.0.8

func (model *Model) FindByIDAndTenantInfo(id primitive.ObjectID, userId primitive.ObjectID, tenantId primitive.ObjectID, data interface{}) error

FindByIDAndTenantInfo

func (*Model) InsertOne

func (model *Model) InsertOne(data interface{}) (*mongo.InsertOneResult, error)

InsertOne creates a document with default 10 second context timeout

func (*Model) UpdateByID added in v0.0.5

func (model *Model) UpdateByID(id primitive.ObjectID, data interface{}) (*mongo.UpdateResult, error)

UpdateByID changes the description for a movie identified by its name

type MongoServer added in v0.0.2

type MongoServer struct {
	Client   *mongo.Client
	Database *mongo.Database
}

MongoServer holds information regarding a mongo connection

var Mongo *MongoServer

Mongo holds mongo instance

func (*MongoServer) Connect added in v0.0.2

func (server *MongoServer) Connect() error

Connect tries to connect to mongodb provided

		   provided that the server is configured
        properly

func (*MongoServer) Disconnect added in v0.0.2

func (server *MongoServer) Disconnect() error

Disconnect will close an active connection

type RequestContext

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

RequestContext is a utility to facilitate implementation of endpoints

func NewRequestContext

func NewRequestContext(writer http.ResponseWriter, request *http.Request, server *apiServer, jwtPayload *JWTPayload) *RequestContext

NewRequestContext instantiates request context utility

func (*RequestContext) GetBodyPayload

func (context *RequestContext) GetBodyPayload(bodyPayload interface{}) []APIError

GetBodyPayload returns jwt payload found in request

func (*RequestContext) GetEnvStatus

func (context *RequestContext) GetEnvStatus() string

GetEnvStatus returns info about the environment

func (*RequestContext) GetJWTPayload

func (context *RequestContext) GetJWTPayload() *JWTPayload

GetJWTPayload returns jwt payload found in request

func (*RequestContext) GetPathParam

func (context *RequestContext) GetPathParam() map[string]string

GetPathParam returns data collected from path params (not GET PARAMETERS)

func (*RequestContext) GetUriParams added in v0.0.5

func (context *RequestContext) GetUriParams() map[string]string

GetUriParams returns params found in URL

func (*RequestContext) JSON

func (context *RequestContext) JSON(statusCode int, response interface{})

JSON will write a JSON response with statusCode and Payload

type RequestOptions

type RequestOptions struct {
	URI     string
	Methods []string
	Name    RouteName
	Handler HandlerFunc
}

RequestOptions enables api endpoint to be configured

type Response

type Response struct {
	Payload interface{} `json:"payload,omitempty"`
}

Response holds an abstracted response from API endpoints

type ResponseRecorder added in v0.0.2

type ResponseRecorder struct {
	*httptest.ResponseRecorder
}

ResponseRecorder prepares a response recorder to east

test implementation

func (*ResponseRecorder) GetJwt added in v0.0.2

func (r *ResponseRecorder) GetJwt(token string) (JWTPayload, error)

GetJwt gets jwt payload from recorded response

type RouteName

type RouteName string

RouteName to typecast request names

type Void

type Void struct{}

Void is an empty response

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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