otpm/models/user.go
“xHuPo” bcd986e3f7 beta
2025-05-23 18:57:11 +08:00

114 lines
2.6 KiB
Go

package models
import (
"context"
"database/sql"
"fmt"
"time"
"github.com/jmoiron/sqlx"
)
// User represents a user in the system
type User struct {
ID string `db:"id" json:"id"`
OpenID string `db:"openid" json:"openid"`
SessionKey string `db:"session_key" json:"-"`
CreatedAt time.Time `db:"created_at" json:"created_at"`
UpdatedAt time.Time `db:"updated_at" json:"updated_at"`
}
// UserRepository handles user data operations
type UserRepository struct {
db *sqlx.DB
}
// NewUserRepository creates a new UserRepository
func NewUserRepository(db *sqlx.DB) *UserRepository {
return &UserRepository{db: db}
}
// FindByID finds a user by ID
func (r *UserRepository) FindByID(ctx context.Context, id string) (*User, error) {
var user User
query := `SELECT * FROM users WHERE id = ?`
err := r.db.GetContext(ctx, &user, query, id)
if err != nil {
if err == sql.ErrNoRows {
return nil, fmt.Errorf("user not found: %w", err)
}
return nil, fmt.Errorf("failed to find user: %w", err)
}
return &user, nil
}
// FindByOpenID finds a user by OpenID
func (r *UserRepository) FindByOpenID(ctx context.Context, openID string) (*User, error) {
var user User
query := `SELECT * FROM users WHERE openid = ?`
err := r.db.GetContext(ctx, &user, query, openID)
if err != nil {
if err == sql.ErrNoRows {
return nil, nil // User not found, but not an error
}
return nil, fmt.Errorf("failed to find user: %w", err)
}
return &user, nil
}
// Create creates a new user
func (r *UserRepository) Create(ctx context.Context, user *User) error {
query := `
INSERT INTO users (id, openid, session_key, created_at, updated_at)
VALUES (?, ?, ?, ?, ?)
`
now := time.Now()
user.CreatedAt = now
user.UpdatedAt = now
_, err := r.db.ExecContext(
ctx,
query,
user.ID,
user.OpenID,
user.SessionKey,
user.CreatedAt,
user.UpdatedAt,
)
if err != nil {
return fmt.Errorf("failed to create user: %w", err)
}
return nil
}
// Update updates an existing user
func (r *UserRepository) Update(ctx context.Context, user *User) error {
query := `
UPDATE users
SET session_key = ?, updated_at = ?
WHERE id = ?
`
user.UpdatedAt = time.Now()
_, err := r.db.ExecContext(
ctx,
query,
user.SessionKey,
user.UpdatedAt,
user.ID,
)
if err != nil {
return fmt.Errorf("failed to update user: %w", err)
}
return nil
}
// Delete deletes a user
func (r *UserRepository) Delete(ctx context.Context, id string) error {
query := `DELETE FROM users WHERE id = ?`
_, err := r.db.ExecContext(ctx, query, id)
if err != nil {
return fmt.Errorf("failed to delete user: %w", err)
}
return nil
}