hmn/src/hmndata/education_helper.go

58 lines
1.3 KiB
Go

package hmndata
import (
"context"
"git.handmade.network/hmn/hmn/src/db"
"git.handmade.network/hmn/hmn/src/models"
"git.handmade.network/hmn/hmn/src/oops"
"git.handmade.network/hmn/hmn/src/perf"
)
type EduArticleQuery struct {
Slugs []string
Types []models.EduArticleType
}
type EduArticleAndStuff struct {
Article models.EduArticle `db:"a"`
CurrentVersion models.EduArticleVersion `db:"v"`
}
func FetchEduArticles(
ctx context.Context,
dbConn db.ConnOrTx,
currentUser *models.User,
q EduArticleQuery,
) ([]*EduArticleAndStuff, error) {
perf := perf.ExtractPerf(ctx)
perf.StartBlock("SQL", "Fetch education articles")
defer perf.EndBlock()
var qb db.QueryBuilder
qb.Add(`
SELECT $columns
FROM
education_article AS a
JOIN education_article_version AS v ON a.current_version = v.id
WHERE
TRUE
`)
if len(q.Slugs) > 0 {
qb.Add(`AND a.slug = ANY ($?)`, q.Slugs)
}
if len(q.Types) > 0 {
qb.Add(`AND a.type = ANY ($?)`, q.Types)
}
if currentUser == nil || !currentUser.CanSeeUnpublishedEducationContent() {
qb.Add(`AND a.published`)
}
articles, err := db.Query[EduArticleAndStuff](ctx, dbConn, qb.String(), qb.Args()...)
if err != nil {
return nil, oops.New(err, "failed to fetch education articles")
}
return articles, nil
}