userprefs

package module
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Nov 27, 2024 License: MIT Imports: 8 Imported by: 0

README

UserPrefs

userprefs is a flexible, concurrent-safe user preferences management system for Go applications. While originally designed for Discord bots, it can be used in any application requiring user-specific preference storage.

Go Reference Go Report Card

Features

  • Thread-safe preference management
  • Multiple storage backends (PostgreSQL, SQLite)
  • Optional caching (Redis, in-memory)
  • Flexible type system (string, boolean, number, JSON, enum)
  • Category-based organization
  • Default values support
  • Context-aware operations
  • Discord bot framework agnostic

Installation

go get github.com/CreativeUnicorns/userprefs

Quick Start

package main

import (
    "context"
    "github.com/CreativeUnicorns/userprefs"
    "github.com/CreativeUnicorns/userprefs/storage"
)

func main() {
    // Initialize storage
    store, _ := storage.NewSQLiteStorage("prefs.db")
    defer store.Close()

    // Create manager
    mgr := userprefs.New(
        userprefs.WithStorage(store),
    )

    // Define preferences
    mgr.DefinePreference(userprefs.PreferenceDefinition{
        Key:          "theme",
        Type:         "enum",
        Category:     "appearance",
        DefaultValue: "dark",
        AllowedValues: []interface{}{
            "light", "dark", "system",
        },
    })

    // Set preference
    ctx := context.Background()
    mgr.Set(ctx, "user123", "theme", "light")

    // Get preference
    pref, _ := mgr.Get(ctx, "user123", "theme")
    fmt.Printf("Theme: %v\n", pref.Value)
}

Storage Backends

SQLite
store, err := storage.NewSQLiteStorage("prefs.db")
PostgreSQL
store, err := storage.NewPostgresStorage("postgres://user:pass@localhost/dbname")

Caching

In-Memory
cache := cache.NewMemoryCache()
mgr := userprefs.New(
    userprefs.WithStorage(store),
    userprefs.WithCache(cache),
)
Redis
cache, err := cache.NewRedisCache("localhost:6379", "", 0)
mgr := userprefs.New(
    userprefs.WithStorage(store),
    userprefs.WithCache(cache),
)

Preference Types

  • string: String values
  • boolean: True/false values
  • number: Numeric values
  • json: Complex JSON structures
  • enum: Predefined set of values
// String preference
mgr.DefinePreference(userprefs.PreferenceDefinition{
    Key:          "nickname",
    Type:         "string",
    Category:     "profile",
    DefaultValue: "User",
})

// JSON preference
type Settings struct {
    Language string   `json:"language"`
    Features []string `json:"features"`
}

mgr.DefinePreference(userprefs.PreferenceDefinition{
    Key:      "settings",
    Type:     "json",
    Category: "system",
    DefaultValue: Settings{
        Language: "en",
        Features: []string{"basic"},
    },
})

Discord Integration

The module is framework-agnostic and works with any Discord bot library. Add the /preferences command to your bot:

// Get preference before command execution
prefs, _ := prefManager.Get(ctx, userID, "format")
format := prefs.Value.(string)

// Set preference from slash command
prefManager.Set(ctx, userID, "format", "mp4")

// Get all preferences by category
prefs, _ := prefManager.GetByCategory(ctx, userID, "media")

See the examples directory for complete Discord bot implementations.

Best Practices

  1. Define preferences at startup
  2. Use categories to organize preferences
  3. Always provide default values
  4. Handle errors appropriately
  5. Use context for timeout control
  6. Close storage/cache connections on shutdown

Contributing

Contributions are welcome! Please see CONTRIBUTING.md for guidelines.

License

MIT License - see LICENSE for details.

Documentation

Overview

Package userprefs provides a flexible, concurrent-safe user preferences management system.

It supports multiple storage backends (PostgreSQL, SQLite), optional caching (Redis, in-memory), and a type-safe preference system. While originally designed for Discord bots, it can be used in any application requiring user-specific preference storage.

Package userprefs defines error variables used throughout the user preferences system.

Package userprefs defines interfaces for storage, caching, and logging used in user preferences management.

Package userprefs provides default logging implementations.

Package userprefs provides the Manager responsible for handling user preferences.

Package userprefs defines the core types used in the user preferences management system.

Package userprefs provides validation functions for user preferences.

Index

Constants

This section is empty.

Variables

View Source
var ErrCacheUnavailable = errors.New("cache backend unavailable")

ErrCacheUnavailable indicates that the cache backend is unavailable.

View Source
var ErrInvalidInput = errors.New("invalid input parameters")

ErrInvalidInput indicates that the input parameters provided to a function are invalid.

View Source
var ErrInvalidKey = errors.New("invalid preference key")

ErrInvalidKey indicates that the provided preference key is invalid.

View Source
var ErrInvalidType = errors.New("invalid preference type")

ErrInvalidType indicates that the provided preference type is invalid.

View Source
var ErrInvalidValue = errors.New("invalid preference value")

ErrInvalidValue indicates that the provided preference value is invalid.

View Source
var ErrNotFound = errors.New("preference not found")

ErrNotFound indicates that the requested preference was not found.

View Source
var ErrPreferenceNotDefined = errors.New("preference not defined")

ErrPreferenceNotDefined indicates that the preference has not been defined in the system.

View Source
var ErrStorageUnavailable = errors.New("storage backend unavailable")

ErrStorageUnavailable indicates that the storage backend is unavailable.

Functions

This section is empty.

Types

type Cache

type Cache interface {
	Get(ctx context.Context, key string) (interface{}, error)
	Set(ctx context.Context, key string, value interface{}, ttl time.Duration) error
	Delete(ctx context.Context, key string) error
	Close() error
}

Cache defines the methods required for a caching backend.

type Config

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

Config holds the configuration for the Manager, including storage, cache, logger, and preference definitions.

type Logger

type Logger interface {
	Debug(msg string, args ...interface{})
	Info(msg string, args ...interface{})
	Warn(msg string, args ...interface{})
	Error(msg string, args ...interface{})
}

Logger defines the methods required for logging within the user preferences system.

type Manager

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

Manager manages user preferences by interfacing with storage and cache backends.

func New

func New(opts ...Option) *Manager

New creates a new Manager instance with the provided configuration options.

func (*Manager) DefinePreference

func (m *Manager) DefinePreference(def PreferenceDefinition) error

DefinePreference registers a new preference definition. It returns an error if the key is invalid or the type is unsupported.

func (*Manager) Delete

func (m *Manager) Delete(ctx context.Context, userID, key string) error

Delete removes a preference for a user by key.

func (*Manager) Get

func (m *Manager) Get(ctx context.Context, userID, key string) (*Preference, error)

Get retrieves a preference for a user by key. It returns the preference or an error if not found.

func (*Manager) GetAll

func (m *Manager) GetAll(ctx context.Context, userID string) (map[string]*Preference, error)

GetAll retrieves all preferences for a user.

func (*Manager) GetByCategory

func (m *Manager) GetByCategory(ctx context.Context, userID, category string) (map[string]*Preference, error)

GetByCategory retrieves all preferences for a user within a specific category.

func (*Manager) Set

func (m *Manager) Set(ctx context.Context, userID, key string, value interface{}) error

Set updates or creates a preference for a user. It validates the value against the preference definition.

type Option

type Option func(*Config)

Option defines a configuration option for the Manager.

func WithCache

func WithCache(cache Cache) Option

WithCache sets the caching backend for the Manager.

func WithLogger

func WithLogger(l Logger) Option

WithLogger sets the logger for the Manager.

func WithStorage

func WithStorage(s Storage) Option

WithStorage sets the storage backend for the Manager.

type Preference

type Preference struct {
	UserID       string      `json:"user_id"`
	Key          string      `json:"key"`
	Value        interface{} `json:"value"`
	DefaultValue interface{} `json:"default_value,omitempty"`
	Type         string      `json:"type"`
	Category     string      `json:"category,omitempty"`
	UpdatedAt    time.Time   `json:"updated_at"`
}

Preference represents a single user preference.

type PreferenceDefinition

type PreferenceDefinition struct {
	Key           string        `json:"key"`
	Type          string        `json:"type"`
	DefaultValue  interface{}   `json:"default_value,omitempty"`
	Category      string        `json:"category,omitempty"`
	AllowedValues []interface{} `json:"allowed_values,omitempty"`
}

PreferenceDefinition defines the schema for a preference, including its type and allowed values.

type Storage

type Storage interface {
	Get(ctx context.Context, userID, key string) (*Preference, error)
	Set(ctx context.Context, pref *Preference) error
	Delete(ctx context.Context, userID, key string) error
	GetAll(ctx context.Context, userID string) (map[string]*Preference, error)
	GetByCategory(ctx context.Context, userID, category string) (map[string]*Preference, error)
	Close() error
}

Storage defines the methods required for a storage backend.

Directories

Path Synopsis
Package cache provides in-memory caching implementations.
Package cache provides in-memory caching implementations.
examples
advanced
examples/advanced/main.go
examples/advanced/main.go
basic
examples/basic/main.go
examples/basic/main.go
discordgo-bot
examples/discordgo-bot/main.go
examples/discordgo-bot/main.go
sqlite-advanced
examples/sqlite-advanced/main.go
examples/sqlite-advanced/main.go
Package storage provides a PostgreSQL-based implementation of the Storage interface.
Package storage provides a PostgreSQL-based implementation of the Storage interface.

Jump to

Keyboard shortcuts

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