65 lines
1.8 KiB
Go
65 lines
1.8 KiB
Go
package repository
|
|
|
|
import (
|
|
"context"
|
|
|
|
"go.mongodb.org/mongo-driver/v2/bson"
|
|
"go.mongodb.org/mongo-driver/v2/mongo"
|
|
"go.mongodb.org/mongo-driver/v2/mongo/options"
|
|
)
|
|
|
|
type EssayRepo struct {
|
|
col *mongo.Collection
|
|
}
|
|
|
|
func NewEssayRepo(db *MongoDB) *EssayRepo {
|
|
return &EssayRepo{col: db.Collection("essays")}
|
|
}
|
|
|
|
type EssayDoc struct {
|
|
ID bson.ObjectID `bson:"_id" json:"id"`
|
|
Slug string `bson:"slug" json:"slug"`
|
|
Title string `bson:"title" json:"title"`
|
|
Author string `bson:"author" json:"author"`
|
|
Year *int `bson:"year,omitempty" json:"year,omitempty"`
|
|
Group *string `bson:"group,omitempty" json:"group,omitempty"`
|
|
Order int `bson:"order" json:"order"`
|
|
Paragraphs []string `bson:"paragraphs" json:"paragraphs"`
|
|
}
|
|
|
|
type EssaySummaryDoc struct {
|
|
ID bson.ObjectID `bson:"_id" json:"id"`
|
|
Slug string `bson:"slug" json:"slug"`
|
|
Title string `bson:"title" json:"title"`
|
|
Year *int `bson:"year,omitempty" json:"year,omitempty"`
|
|
Group *string `bson:"group,omitempty" json:"group,omitempty"`
|
|
}
|
|
|
|
func (r *EssayRepo) GetAll(ctx context.Context) ([]EssaySummaryDoc, error) {
|
|
opts := options.Find().
|
|
SetSort(bson.D{{Key: "group", Value: 1}, {Key: "order", Value: 1}}).
|
|
SetProjection(bson.M{"slug": 1, "title": 1, "year": 1, "group": 1})
|
|
cursor, err := r.col.Find(ctx, bson.M{}, opts)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
defer cursor.Close(ctx)
|
|
var results []EssaySummaryDoc
|
|
if err := cursor.All(ctx, &results); err != nil {
|
|
return nil, err
|
|
}
|
|
return results, nil
|
|
}
|
|
|
|
func (r *EssayRepo) GetBySlug(ctx context.Context, slug string) (*EssayDoc, error) {
|
|
var doc EssayDoc
|
|
err := r.col.FindOne(ctx, bson.M{"slug": slug}).Decode(&doc)
|
|
if err != nil {
|
|
if err == mongo.ErrNoDocuments {
|
|
return nil, nil
|
|
}
|
|
return nil, err
|
|
}
|
|
return &doc, nil
|
|
}
|