90 lines
2.5 KiB
Go
90 lines
2.5 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 OtherDocumentRepo struct {
|
|
meta *mongo.Collection
|
|
chapters *mongo.Collection
|
|
}
|
|
|
|
func NewOtherDocumentRepo(db *MongoDB) *OtherDocumentRepo {
|
|
return &OtherDocumentRepo{
|
|
meta: db.Collection("other_document_meta"),
|
|
chapters: db.Collection("other_document_chapters"),
|
|
}
|
|
}
|
|
|
|
type OtherDocumentMetaDoc struct {
|
|
ID bson.ObjectID `bson:"_id" json:"id"`
|
|
Book string `bson:"book" json:"book"`
|
|
Data interface{} `bson:"data" json:"data"`
|
|
}
|
|
|
|
type OtherDocumentChapterDoc struct {
|
|
ID bson.ObjectID `bson:"_id" json:"id"`
|
|
Book string `bson:"book" json:"book"`
|
|
Chapter int `bson:"chapter" json:"chapter"`
|
|
Title string `bson:"title" json:"title"`
|
|
Type string `bson:"type" json:"type"`
|
|
Slug string `bson:"slug" json:"slug"`
|
|
Order int `bson:"order" json:"order"`
|
|
Paragraphs []string `bson:"paragraphs" json:"paragraphs"`
|
|
}
|
|
|
|
func (r *OtherDocumentRepo) GetAllMetas(ctx context.Context) ([]OtherDocumentMetaDoc, error) {
|
|
cursor, err := r.meta.Find(ctx, bson.M{})
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
defer cursor.Close(ctx)
|
|
var results []OtherDocumentMetaDoc
|
|
if err := cursor.All(ctx, &results); err != nil {
|
|
return nil, err
|
|
}
|
|
return results, nil
|
|
}
|
|
|
|
func (r *OtherDocumentRepo) GetMeta(ctx context.Context, book string) (*OtherDocumentMetaDoc, error) {
|
|
var doc OtherDocumentMetaDoc
|
|
err := r.meta.FindOne(ctx, bson.M{"book": book}).Decode(&doc)
|
|
if err != nil {
|
|
if err == mongo.ErrNoDocuments {
|
|
return nil, nil
|
|
}
|
|
return nil, err
|
|
}
|
|
return &doc, nil
|
|
}
|
|
|
|
func (r *OtherDocumentRepo) GetChapters(ctx context.Context, book string) ([]OtherDocumentChapterDoc, error) {
|
|
opts := options.Find().SetSort(bson.M{"order": 1})
|
|
cursor, err := r.chapters.Find(ctx, bson.M{"book": book}, opts)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
defer cursor.Close(ctx)
|
|
var results []OtherDocumentChapterDoc
|
|
if err := cursor.All(ctx, &results); err != nil {
|
|
return nil, err
|
|
}
|
|
return results, nil
|
|
}
|
|
|
|
func (r *OtherDocumentRepo) GetChapter(ctx context.Context, book, slug string) (*OtherDocumentChapterDoc, error) {
|
|
var doc OtherDocumentChapterDoc
|
|
err := r.chapters.FindOne(ctx, bson.M{"book": book, "slug": slug}).Decode(&doc)
|
|
if err != nil {
|
|
if err == mongo.ErrNoDocuments {
|
|
return nil, nil
|
|
}
|
|
return nil, err
|
|
}
|
|
return &doc, nil
|
|
}
|