feat: add books APIs
This commit is contained in:
@@ -0,0 +1,89 @@
|
||||
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 JournalRepo struct {
|
||||
meta *mongo.Collection
|
||||
chapters *mongo.Collection
|
||||
}
|
||||
|
||||
func NewJournalRepo(db *MongoDB) *JournalRepo {
|
||||
return &JournalRepo{
|
||||
meta: db.Collection("journal_meta"),
|
||||
chapters: db.Collection("journal_chapters"),
|
||||
}
|
||||
}
|
||||
|
||||
type JournalMetaDoc struct {
|
||||
ID bson.ObjectID `bson:"_id" json:"id"`
|
||||
Book string `bson:"book" json:"book"`
|
||||
Data interface{} `bson:"data" json:"data"`
|
||||
}
|
||||
|
||||
type JournalChapterDoc 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 *JournalRepo) GetAllMetas(ctx context.Context) ([]JournalMetaDoc, error) {
|
||||
cursor, err := r.meta.Find(ctx, bson.M{})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer cursor.Close(ctx)
|
||||
var results []JournalMetaDoc
|
||||
if err := cursor.All(ctx, &results); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return results, nil
|
||||
}
|
||||
|
||||
func (r *JournalRepo) GetMeta(ctx context.Context, book string) (*JournalMetaDoc, error) {
|
||||
var doc JournalMetaDoc
|
||||
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 *JournalRepo) GetChapters(ctx context.Context, book string) ([]JournalChapterDoc, 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 []JournalChapterDoc
|
||||
if err := cursor.All(ctx, &results); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return results, nil
|
||||
}
|
||||
|
||||
func (r *JournalRepo) GetChapter(ctx context.Context, book, slug string) (*JournalChapterDoc, error) {
|
||||
var doc JournalChapterDoc
|
||||
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
|
||||
}
|
||||
Reference in New Issue
Block a user