data

package
v0.0.0-...-c9a51ec Latest Latest
Warning

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

Go to latest
Published: Jan 20, 2024 License: MIT Imports: 16 Imported by: 0

Documentation

Overview

Package data provides structs and validation methods for business entities.

Index

Constants

View Source
const (
	// ScopeActivation is used to activate a user account.
	ScopeActivation = "activation"
	// ScopeAuthentication is used to authenticate users.
	ScopeAuthentication = "authentication"
)

Scopes are used to limit the use cases of tokens.

Variables

View Source
var (
	// ErrRecordNotFound is returned when a record couldn't be found in the DB.
	ErrRecordNotFound = errors.New("record not found")
	// ErrEditConflict is returned when updating a record with an incorrect version.
	// This kind of update is very likely due to a data race in the update endpoint.
	ErrEditConflict = errors.New("edit conflict")
)
View Source
var AnonymousUser = &User{}

AnonymousUser is a sentinel variable to check whether a user is authenticated or not.

View Source
var ErrDuplicateEmail = errors.New("duplicate email")

ErrDuplicateEmail is returned when inserting or updating a user in the DB if there's already another user with the same email address.

View Source
var ErrInvalidRuntimeFormat = errors.New("invalid runtime format")

ErrInvalidRuntimeFormat is returned when unmarshaling JSON. The expected format is "\d+ mins".

Functions

func ValidateEmail

func ValidateEmail(v *validator.Validator, email string)

ValidateEmail validates an email address. The passed validator will contain all detected errors. The caller is expected to call validator.Validator.Valid after this method.

func ValidateFilters

func ValidateFilters(validate *validator.Validator, filters Filters)

ValidateFilters validates filters. The passed validator will contain all detected errors. The caller is expected to call validator.Validator.Valid after this method.

func ValidateMovie

func ValidateMovie(validate *validator.Validator, movie *Movie)

ValidateMovie validates a movie. The passed validator will contain all detected errors. The caller is expected to call validator.Validator.Valid after this method.

func ValidatePasswordPlaintext

func ValidatePasswordPlaintext(v *validator.Validator, password string)

ValidatePasswordPlaintext validates a plaintext password. The passed validator will contain all detected errors. The caller is expected to call validator.Validator.Valid after this method.

func ValidateTokenPlaintext

func ValidateTokenPlaintext(v *validator.Validator, tokenPlaintext string)

ValidateTokenPlaintext validates a token. The passed validator will contain all detected errors. The caller is expected to call validator.Validator.Valid after this method.

func ValidateUser

func ValidateUser(v *validator.Validator, user *User)

ValidateUser validates a user. The passed validator will contain all detected errors. The caller is expected to call validator.Validator.Valid after this method.

Types

type Filters

type Filters struct {
	Page         int
	PageSize     int
	Sort         string
	SortSafelist []string
}

Filters are used to filter and sort pages of data. They should be validated using ValidateFilters.

type Metadata

type Metadata struct {
	CurrentPage  int `json:"currentPage,omitempty"`
	PageSize     int `json:"pageSize,omitempty"`
	FirstPage    int `json:"firstPage,omitempty"`
	LastPage     int `json:"lastPage,omitempty"`
	TotalRecords int `json:"totalRecords,omitempty"`
}

Metadata holds pagination metadata.

type Models

type Models struct {
	Movies      MovieModel
	Tokens      TokenModel
	Users       UserModel
	Permissions PermissionModel
}

Models holds all model interfaces.

func NewModels

func NewModels(db *sqlx.DB) Models

NewModels initializes Models with the proper implementations for production use.

type Movie

type Movie struct {
	ID        int64          `db:"id"         json:"id"`
	CreatedAt time.Time      `db:"created_at" json:"-"`
	Title     string         `db:"title"      json:"title"`
	Year      int32          `db:"year"       json:"year,omitempty"`
	Runtime   Runtime        `db:"runtime"    json:"runtime,omitempty"`
	Genres    pq.StringArray `db:"genres"     json:"genres,omitempty"`
	Version   int32          `db:"version"    json:"version"`
}

Movie holds information about a single movie. It represents the entity as stored in the DB.

type MovieModel

type MovieModel struct {
	DB *sqlx.DB
}

MovieModel implements methods to query the database.

func (MovieModel) Delete

func (m MovieModel) Delete(id int64) error

Delete deletes a movie from the DB.

func (MovieModel) Get

func (m MovieModel) Get(id int64) (*Movie, error)

Get returns the Movie with the given id from the DB, or an error if it couldn't be found.

func (MovieModel) GetAll

func (m MovieModel) GetAll(title string, genres []string, filters Filters) ([]*Movie, Metadata, error)

GetAll returns a filtered list of movies from the DB.

func (MovieModel) Insert

func (m MovieModel) Insert(movie *Movie) error

Insert inserts a movie in the database. Movie.CreatedAt and Movie.Version are set on the passed movie.

func (MovieModel) Update

func (m MovieModel) Update(movie *Movie) error

Update updates a movie in the DB. Movie.Version is set on the passed movie.

type PermissionModel

type PermissionModel struct {
	DB *sqlx.DB
}

PermissionModel implements methods to query the database.

func (PermissionModel) AddForUser

func (m PermissionModel) AddForUser(userID int64, codes ...string) error

AddForUser gives permissions to the user.

func (PermissionModel) GetAllForUser

func (m PermissionModel) GetAllForUser(userID int64) (Permissions, error)

GetAllForUser returns all permission codes the user passed in parameter has.

type Permissions

type Permissions []string

Permissions holds permission codes as strings.

func (Permissions) Include

func (p Permissions) Include(code string) bool

Include checks whether the permissions table contains the given permission code. Typically used to check whether a user has a permission.

type Runtime

type Runtime int32

Runtime represents the duration of a movie.

func (Runtime) MarshalJSON

func (r Runtime) MarshalJSON() ([]byte, error)

MarshalJSON implements json.Marshaler. intentionally using a value receiver.

func (*Runtime) UnmarshalJSON

func (r *Runtime) UnmarshalJSON(jsonValue []byte) error

UnmarshalJSON implements json.Unmarshaler.

type Token

type Token struct {
	Plaintext string    `json:"token"`
	Hash      []byte    `json:"-"`
	UserID    int64     `json:"-"`
	Expiry    time.Time `json:"expiry"`
	Scope     string    `json:"-"`
}

A Token is used to activate a User account.

type TokenModel

type TokenModel struct {
	DB *sqlx.DB
}

TokenModel implements methods to query the database.

func (TokenModel) DeleteAllForUser

func (m TokenModel) DeleteAllForUser(scope string, userID int64) error

DeleteAllForUser deletes all tokens for a specific user and scope.

func (TokenModel) Insert

func (m TokenModel) Insert(token *Token) error

Insert inserts a token in the DB.

func (TokenModel) New

func (m TokenModel) New(userID int64, ttl time.Duration, scope string) (*Token, error)

New creates a token and stores it in the DB.

type User

type User struct {
	ID        int64     `db:"id"         json:"id"`
	CreatedAt time.Time `db:"created_at" json:"createdAt"`
	Name      string    `db:"name"       json:"name"`
	Email     string    `db:"email"      json:"email"`
	Password  password  `db:"-"          json:"-"`
	Activated bool      `db:"activated"  json:"activated"`
	Version   int       `db:"version"    json:"-"`
}

A User represents a single user of our service, as stored in the DB.

func (*User) IsAnonymous

func (u *User) IsAnonymous() bool

IsAnonymous returns true if the User is the AnonymousUser.

type UserModel

type UserModel struct {
	DB *sqlx.DB
}

UserModel implements methods to query the database.

func (UserModel) GetByEmail

func (m UserModel) GetByEmail(email string) (*User, error)

GetByEmail retrieves a user in the DB by its email address.

func (UserModel) GetForToken

func (m UserModel) GetForToken(tokenScope, tokenPlaintext string) (*User, error)

GetForToken retrieves a user given a plaintext token and its scope.

func (UserModel) Insert

func (m UserModel) Insert(user *User) error

Insert inserts a user in the DB.

func (UserModel) Update

func (m UserModel) Update(user *User) error

Update updates a user in DB.

Jump to

Keyboard shortcuts

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