threadr-rewritten/models/board.go

101 lines
3.1 KiB
Go

package models
import (
"database/sql"
"encoding/json"
)
type Board struct {
ID int
Name string
Description string
Private bool
PublicVisible bool
PinnedThreads []int // Stored as JSON
CustomLandingPage string
ColorScheme string
}
func GetBoardByID(db *sql.DB, id int) (*Board, error) {
query := "SELECT id, name, description, private, public_visible, pinned_threads, custom_landing_page, color_scheme FROM boards WHERE id = ?"
row := db.QueryRow(query, id)
board := &Board{}
var pinnedThreadsJSON sql.NullString
var customLandingPage sql.NullString
var colorScheme sql.NullString
var description sql.NullString
err := row.Scan(&board.ID, &board.Name, &description, &board.Private, &board.PublicVisible, &pinnedThreadsJSON, &customLandingPage, &colorScheme)
if err == sql.ErrNoRows {
return nil, nil
}
if err != nil {
return nil, err
}
if description.Valid {
board.Description = description.String
} else {
board.Description = ""
}
if pinnedThreadsJSON.Valid && pinnedThreadsJSON.String != "" {
err = json.Unmarshal([]byte(pinnedThreadsJSON.String), &board.PinnedThreads)
if err != nil {
return nil, err
}
}
if customLandingPage.Valid {
board.CustomLandingPage = customLandingPage.String
} else {
board.CustomLandingPage = ""
}
if colorScheme.Valid {
board.ColorScheme = colorScheme.String
} else {
board.ColorScheme = ""
}
return board, nil
}
func GetAllBoards(db *sql.DB, private bool) ([]Board, error) {
query := "SELECT id, name, description, private, public_visible, pinned_threads, custom_landing_page, color_scheme FROM boards WHERE private = ? ORDER BY id ASC"
rows, err := db.Query(query, private)
if err != nil {
return nil, err
}
defer rows.Close()
var boards []Board
for rows.Next() {
board := Board{}
var pinnedThreadsJSON sql.NullString
var customLandingPage sql.NullString
var colorScheme sql.NullString
var description sql.NullString
err := rows.Scan(&board.ID, &board.Name, &description, &board.Private, &board.PublicVisible, &pinnedThreadsJSON, &customLandingPage, &colorScheme)
if err != nil {
return nil, err
}
if description.Valid {
board.Description = description.String
} else {
board.Description = ""
}
if pinnedThreadsJSON.Valid && pinnedThreadsJSON.String != "" {
err = json.Unmarshal([]byte(pinnedThreadsJSON.String), &board.PinnedThreads)
if err != nil {
return nil, err
}
}
if customLandingPage.Valid {
board.CustomLandingPage = customLandingPage.String
} else {
board.CustomLandingPage = ""
}
if colorScheme.Valid {
board.ColorScheme = colorScheme.String
} else {
board.ColorScheme = ""
}
boards = append(boards, board)
}
return boards, nil
}