mercury/web/app/app.go

109 lines
2.5 KiB
Go

package app
import (
"context"
"encoding/base64"
"emperror.dev/errors"
"git.sleepycat.moe/sam/mercury/config"
"git.sleepycat.moe/sam/mercury/internal/concurrent"
"git.sleepycat.moe/sam/mercury/internal/database"
"git.sleepycat.moe/sam/mercury/internal/database/sql"
"git.sleepycat.moe/sam/mercury/web/templates"
"github.com/flosch/pongo2/v6"
"github.com/go-chi/chi/v5"
"github.com/go-chi/chi/v5/middleware"
)
const (
ErrSecretKeyEmpty = errors.Sentinel("core.secret_key cannot be empty")
)
type App struct {
Router chi.Router
AppConfig config.Config
DBConfig *concurrent.Value[database.Config]
Database *sql.Base
tmpl *pongo2.TemplateSet
tokenKey []byte
}
func NewApp(ctx context.Context, cfg config.Config, db *sql.Base) (*App, error) {
app := &App{
Router: chi.NewRouter(),
AppConfig: cfg,
Database: db,
}
if cfg.Core.SecretKey == "" {
return nil, ErrSecretKeyEmpty
}
tokenKey, err := base64.RawStdEncoding.DecodeString(cfg.Core.SecretKey)
if err != nil {
return nil, errors.Wrap(err, "decoding core.secret_key")
}
app.tokenKey = tokenKey
tmpl, err := templates.New(cfg.Core.Dev)
if err != nil {
return nil, errors.Wrap(err, "creating templates")
}
app.tmpl = tmpl
if cfg.Core.Dev {
app.Router.Use(app.Logger)
}
app.Router.Use(middleware.Recoverer)
dbCfg, err := app.Config().Get(ctx)
if err != nil {
return nil, errors.Wrap(err, "getting database config")
}
app.DBConfig = concurrent.NewValue(dbCfg)
return app, nil
}
func (a *App) Account(q ...sql.Querier) *sql.AccountStore {
if len(q) == 0 || q[0] == nil {
return sql.NewAccountStore(a.Database.PoolQuerier())
}
return sql.NewAccountStore(q[0])
}
func (a *App) Blog(q ...sql.Querier) *sql.BlogStore {
if len(q) == 0 || q[0] == nil {
return sql.NewBlogStore(a.Database.PoolQuerier())
}
return sql.NewBlogStore(q[0])
}
func (a *App) Config(q ...sql.Querier) *sql.ConfigStore {
if len(q) == 0 || q[0] == nil {
return sql.NewConfigStore(a.Database.PoolQuerier())
}
return sql.NewConfigStore(q[0])
}
func (a *App) Post(q ...sql.Querier) *sql.PostStore {
if len(q) == 0 || q[0] == nil {
return sql.NewPostStore(a.Database.PoolQuerier())
}
return sql.NewPostStore(q[0])
}
func (a *App) Timeline(q ...sql.Querier) *sql.TimelineStore {
if len(q) == 0 || q[0] == nil {
return sql.NewTimelineStore(a.Database.PoolQuerier())
}
return sql.NewTimelineStore(q[0])
}
func (a *App) Token(q ...sql.Querier) *sql.TokenStore {
if len(q) == 0 || q[0] == nil {
return sql.NewTokenStore(a.Database.PoolQuerier())
}
return sql.NewTokenStore(q[0])
}