Refactor GetPost and ListPosts logic to use time.Time for timestamps; convert to Unix milliseconds and improve error handling
All checks were successful
CI - Build and Push / Build and Push Docker Image (push) Successful in 52s

This commit is contained in:
2025-10-26 17:44:49 +08:00
parent 116adb7922
commit 0ae4d1705b
2 changed files with 79 additions and 74 deletions

View File

@@ -31,6 +31,7 @@ func NewGetPostLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetPostLo
func (l *GetPostLogic) GetPost(req *types.GetPostReq) (resp *types.GetPostResp, err error) {
var post types.GetPostResp
var coverID sql.NullInt64
var createdAt, updatedAt time.Time
// Query post with cover image
query := `
@@ -39,7 +40,7 @@ func (l *GetPostLogic) GetPost(req *types.GetPostReq) (resp *types.GetPostResp,
WHERE p.id = $1
`
err = l.svcCtx.DB.QueryRowContext(l.ctx, query, req.PostId).Scan(
&post.PostId, &post.Title, &post.Content, &post.CreatedAt, &post.UpdatedAt, &coverID,
&post.PostId, &post.Title, &post.Content, &createdAt, &updatedAt, &coverID,
)
if err != nil {
if err == sql.ErrNoRows {
@@ -50,6 +51,14 @@ func (l *GetPostLogic) GetPost(req *types.GetPostReq) (resp *types.GetPostResp,
return nil, err
}
// Convert timestamps to Unix milliseconds
post.CreatedAt = createdAt.UnixMilli()
post.UpdatedAt = updatedAt.UnixMilli()
// Convert timestamps to Unix milliseconds
post.CreatedAt = createdAt.UnixMilli()
post.UpdatedAt = updatedAt.UnixMilli()
// If cover image exists, get its URL
if coverID.Valid {
coverQuery := `SELECT file_key FROM files WHERE id = $1`
@@ -72,9 +81,5 @@ func (l *GetPostLogic) GetPost(req *types.GetPostReq) (resp *types.GetPostResp,
}
}
// Convert timestamps to Unix
post.CreatedAt = post.CreatedAt * 1000 // Convert to milliseconds if needed
post.UpdatedAt = post.UpdatedAt * 1000
return &post, nil
}