From 0b34dbe3bd499c71014f21daf756657a82ebf249 Mon Sep 17 00:00:00 2001 From: "Laisky.Cai" Date: Wed, 13 Nov 2024 03:07:17 +0000 Subject: [PATCH] feat: Update Post and LegacyPost models to support omitempty for optional fields --- internal/web/blog/model/posts.go | 12 ++++++++---- internal/web/blog/service/posts.go | 7 ++++--- 2 files changed, 12 insertions(+), 7 deletions(-) diff --git a/internal/web/blog/model/posts.go b/internal/web/blog/model/posts.go index 22155c1..f5fb899 100644 --- a/internal/web/blog/model/posts.go +++ b/internal/web/blog/model/posts.go @@ -40,9 +40,9 @@ type Post struct { // Hidden whether the post is hidden or not Hidden bool `bson:"hidden" json:"hidden"` // I18N internationalization of the post - I18N PostI18N `bson:"i18n" json:"i18n"` + I18N PostI18N `bson:"i18n" json:"i18n,omitempty"` // Language language of the post content or markdown - Language string `bson:"-" json:"language"` + Language string `bson:"-" json:"language,omitempty"` // ArweaveId arweave id of the post ArweaveId []ArweaveHistoryItem `bson:"arweave_id" json:"arweave_id"` } @@ -60,6 +60,10 @@ type legacyTime struct { } func (t legacyTime) Time() (time.Time, error) { + if t.Date == "" { + return time.Time{}, nil + } + return time.Parse(time.RFC3339, t.Date) } @@ -115,9 +119,9 @@ type LegacyPost struct { // Hidden whether the post is hidden or not Hidden bool `bson:"hidden" json:"hidden"` // I18N internationalization of the post - I18N legacyI18N `bson:"i18n" json:"i18n"` + I18N legacyI18N `bson:"i18n" json:"i18n,omitempty"` // Language language of the post content or markdown - Language string `bson:"-" json:"language"` + Language string `bson:"-" json:"language,omitempty"` // ArweaveId arweave id of the post ArweaveId []ArweaveHistoryItem `bson:"arweave_id" json:"arweave_id"` } diff --git a/internal/web/blog/service/posts.go b/internal/web/blog/service/posts.go index 89f909f..6a5415a 100644 --- a/internal/web/blog/service/posts.go +++ b/internal/web/blog/service/posts.go @@ -193,7 +193,8 @@ func (s *Blog) LoadPostHistory(ctx context.Context, fileID string, language mode } post := new(model.Post) - if err = json.NewDecoder(reader).Decode(post); err != nil { + err = json.NewDecoder(reader).Decode(post) + if err != nil || post.Content == "" { // try legacy struct reader, err := makeReader(cnt) if err != nil { @@ -201,8 +202,8 @@ func (s *Blog) LoadPostHistory(ctx context.Context, fileID string, language mode } legacyPost := new(model.LegacyPost) - if err2 := json.NewDecoder(reader).Decode(legacyPost); err2 != nil { - return nil, errors.Wrap(errors.Join(err, err2), "cannot decode post by legacy struct") + if err = json.NewDecoder(reader).Decode(legacyPost); err != nil { + return nil, errors.Wrap(err, "cannot decode post by legacy struct") } if post, err = legacyPost.Post(); err != nil {