Skip to content

Commit

Permalink
Made function to assign value in author and post image
Browse files Browse the repository at this point in the history
  • Loading branch information
cp-dharti-r committed Apr 23, 2024
1 parent c970b49 commit 6f2f679
Show file tree
Hide file tree
Showing 13 changed files with 214 additions and 278 deletions.
2 changes: 1 addition & 1 deletion .github/workflows/deploy-backend-dev.yml
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ jobs:
- name: Build backend and copy zip to S3
run: |
secret_value="${{ secrets.RECAPTCHA_CONFIG_JSON_BASE64 }}"
awk -v val="${secret_value}" '{gsub(/{{RECAPTCHA_CONFIG_JSON_BASE64}}/, val)} 1' utils/helper.go > temp.go && mv temp.go utils/helper.go
awk -v val="${secret_value}" '{gsub(/{{RECAPTCHA_CONFIG_JSON_BASE64}}/, val)} 1' utils/helper.go > updated_helper.go && mv updated_helper.go utils/helper.go
apt-get update && apt-get install -y zip
GOOS=linux GOARCH=amd64 CGO_ENABLED=0 go build -o main main.go
zip canopas_serverless_dev_${{ github.sha }}.zip main
Expand Down
2 changes: 1 addition & 1 deletion .github/workflows/deploy-backend-prod.yml
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ jobs:
- name: Build backend and copy zip to S3
run: |
secret_value="${{ secrets.RECAPTCHA_CONFIG_JSON_BASE64 }}"
awk -v val="${secret_value}" '{gsub(/{{RECAPTCHA_CONFIG_JSON_BASE64}}/, val)} 1' utils/helper.go > temp.go && mv temp.go utils/helper.go
awk -v val="${secret_value}" '{gsub(/{{RECAPTCHA_CONFIG_JSON_BASE64}}/, val)} 1' utils/helper.go > updated_helper.go && mv updated_helper.go utils/helper.go
apt-get update && apt-get install -y zip
GOOS=linux GOARCH=amd64 CGO_ENABLED=0 go build -o main main.go
zip canopas_serverless_prod_${{ github.sha }}.zip main
Expand Down
4 changes: 2 additions & 2 deletions db/blog_sql.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ import (
log "github.com/sirupsen/logrus"
)

func NewBlogSql() *sqlx.DB {
func BlogDBInstance() *sqlx.DB {

log.Info("Initializing New Blog Postgres Instance")

Expand Down Expand Up @@ -42,7 +42,7 @@ func NewBlogSql() *sqlx.DB {
}

sslmode := "require"

if os.Getenv("DB_ENV") == "test" {
sslmode = "disable"
}
Expand Down
2 changes: 2 additions & 0 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -71,11 +71,13 @@ require (
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect
github.com/modern-go/reflect2 v1.0.2 // indirect
github.com/pelletier/go-toml/v2 v2.0.9 // indirect
github.com/samber/lo v1.39.0 // indirect
github.com/twitchyliquid64/golang-asm v0.15.1 // indirect
github.com/ugorji/go/codec v1.2.11 // indirect
go.opencensus.io v0.24.0 // indirect
golang.org/x/arch v0.4.0 // indirect
golang.org/x/crypto v0.14.0 // indirect
golang.org/x/exp v0.0.0-20220303212507-bbda1eaf7a17 // indirect
golang.org/x/net v0.17.0 // indirect
golang.org/x/oauth2 v0.11.0 // indirect
golang.org/x/sync v0.3.0 // indirect
Expand Down
4 changes: 4 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -168,6 +168,8 @@ github.com/rogpeppe/fastuuid v1.2.0/go.mod h1:jVj6XXZzXRy/MSR5jhDC/2q6DgLz+nrA6L
github.com/rogpeppe/go-internal v1.6.1/go.mod h1:xXDCJY+GAPziupqXw64V24skbSoqbTEfhy4qGm1nDQc=
github.com/rogpeppe/go-internal v1.8.0 h1:FCbCCtXNOY3UtUuHUYaghJg4y7Fd14rXifAYUAtL9R8=
github.com/rogpeppe/go-internal v1.8.0/go.mod h1:WmiCO8CzOY8rg0OYDC4/i/2WRWAB6poM+XZ2dLUbcbE=
github.com/samber/lo v1.39.0 h1:4gTz1wUhNYLhFSKl6O+8peW0v2F4BCY034GRpU9WnuA=
github.com/samber/lo v1.39.0/go.mod h1:+m/ZKRl6ClXCE2Lgf3MsQlWfh4bn1bz6CXEOxnEXnEA=
github.com/sirupsen/logrus v1.9.3 h1:dueUQJ1C2q9oE3F7wvmSGAaVtTmUizReu6fjN8uqzbQ=
github.com/sirupsen/logrus v1.9.3/go.mod h1:naHLuLoDiP4jHNo9R0sCBMtWGeIprob74mVsIT4qYEQ=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
Expand Down Expand Up @@ -206,6 +208,8 @@ golang.org/x/crypto v0.0.0-20220314234659-1baeb1ce4c0b/go.mod h1:IxCIyHEi3zRg3s0
golang.org/x/crypto v0.14.0 h1:wBqGXzWJW6m1XrIKlAH0Hs1JJ7+9KBwnIO8v66Q9cHc=
golang.org/x/crypto v0.14.0/go.mod h1:MVFd36DqK4CsrnJYDkBA3VC4m2GkXAM0PvzMCn4JQf4=
golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA=
golang.org/x/exp v0.0.0-20220303212507-bbda1eaf7a17 h1:3MTrJm4PyNL9NBqvYDSj3DHl46qQakyfqfWo4jgfaEM=
golang.org/x/exp v0.0.0-20220303212507-bbda1eaf7a17/go.mod h1:lgLbSvA5ygNOMpwM/9anMpWVlVJ7Z+cHWq/eFuinpGE=
golang.org/x/lint v0.0.0-20181026193005-c67002cb31c3/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE=
golang.org/x/lint v0.0.0-20190227174305-5b3e6a55c961/go.mod h1:wehouNa3lNwaWXcvxsM5YxQ5yQlVC4a0KAMCusXpPoU=
golang.org/x/lint v0.0.0-20190313153728-d0100b6bd8b3/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc=
Expand Down
2 changes: 1 addition & 1 deletion infrastructure/backend.yml
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ Parameters:
Description: Postgres database name.
BlogDbName:
Type: String
Description: Postgres blog database name.
Description: Postgres database name for blogs.
RecaptchaSiteKey:
Type: String
Description: Use to verify recpatcha token.
Expand Down
4 changes: 2 additions & 2 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -94,12 +94,12 @@ func setupRouter() *gin.Engine {

router.GET("/api/perksimages", lifePerksImagesRepo.PerksImages)

blogSqlDb := db.NewBlogSql()
blogSqlDb := db.BlogDBInstance()

postRepo := post.New(blogSqlDb)

router.GET("/api/posts", postRepo.Get)
router.GET("/api/posts/:slug", postRepo.GetById)
router.GET("/api/posts/:slug", postRepo.Show)

router.GET("/api/posts/tags/:slug", postRepo.GetPostsByTag)

Expand Down
149 changes: 108 additions & 41 deletions post/author.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,15 +2,22 @@ package post

import (
"encoding/json"
"fmt"
"net/http"
"strconv"
"strings"

"github.com/gin-gonic/gin"
log "github.com/sirupsen/logrus"
)

func (repository *Repository) GetPostsByAuthor(c *gin.Context) {
username := c.Param("username")
if username == "" {
log.Warn("Username not found in query parameter")
c.AbortWithStatus(http.StatusBadRequest)
return
}

skip, err := strconv.Atoi(c.DefaultQuery("skip", "0"))
if err != nil {
Expand Down Expand Up @@ -65,59 +72,119 @@ func (repository *Repository) GetPostsByAuthor(c *gin.Context) {
post.Tag = ""
post.Tags = tags

err = repository.Db.Get(&post.Image, `SELECT f.id, f.name, f.alternative_text, f.caption, f.width, f.height, f.formats as format, f.hash, f.ext, f.mime,
f.size, f.url, f.preview_url, f.provider, f.provider_metadata, f.folder_path, f.created_at, f.updated_at
FROM files f
JOIN files_related_morphs frm ON frm.related_id = $1 AND frm.related_type = 'api::post.post' AND frm.file_id = f.id`, post.Id)
if err != nil {
log.Error("Error while fetching post images: ", err)
c.AbortWithStatus(http.StatusInternalServerError)
return
}
new_posts = append(new_posts, post)
}

var postFormats Formats
new_posts = repository.PreparePosts(new_posts)

if err := json.Unmarshal([]byte(post.Image.Format), &postFormats); err != nil {
log.Error("Error while unmarshal post image formats: ", err)
c.AbortWithStatus(http.StatusInternalServerError)
return
}
c.JSON(http.StatusOK, new_posts)
}

post.Image.Format = ""
post.Image.Formats = postFormats
func (repository *Repository) GetAuthorByPostId(id int) (error, Author) {
author := Author{}

err = repository.Db.Get(&post.Author, `SELECT a.id, a.username, a.name, a.email, a.created_at, a.updated_at, a.bio
err := repository.Db.Get(&author, `SELECT a.id, a.username, a.name, a.email, a.created_at, a.updated_at, a.bio
FROM authors a
JOIN posts_author_links pa ON pa.post_id = $1 AND pa.author_id = a.id`, post.Id)
if err != nil {
log.Error("Error while fetching author: ", err)
c.AbortWithStatus(http.StatusInternalServerError)
return
}
JOIN posts_author_links pa ON pa.post_id = $1 AND pa.author_id = a.id`, id)
if err != nil {
log.Error("Error while fetching author: ", err)
return err, author
}

err = repository.Db.Get(&post.Author.Image, `SELECT f.id, f.name, f.alternative_text, f.caption, f.width, f.height, f.formats as format, f.hash, f.ext, f.mime,
err = repository.Db.Get(&author.Image, `SELECT f.id, f.name, f.alternative_text, f.caption, f.width, f.height, f.formats as format, f.hash, f.ext, f.mime,
f.size, f.url, f.preview_url, f.provider, f.provider_metadata, f.folder_path, f.created_at, f.updated_at
FROM files f
JOIN files_related_morphs frm ON frm.related_id = $1 AND frm.related_type = 'api::author.author' AND frm.file_id = f.id`, post.Author.Id)
if err != nil {
log.Error("Error while fetching author image: ", err)
c.AbortWithStatus(http.StatusInternalServerError)
return
}
JOIN files_related_morphs frm ON frm.related_id = $1 AND frm.related_type = 'api::author.author' AND frm.file_id = f.id`, author.Id)
if err != nil {
log.Error("Error while fetching author image: ", err)
return err, author
}

var authorFormats Formats
var authorFormats Formats

if err := json.Unmarshal([]byte(post.Author.Image.Format), &authorFormats); err != nil {
log.Error("Error while unmarshal author image formats: ", err)
c.AbortWithStatus(http.StatusInternalServerError)
return
}
if err := json.Unmarshal([]byte(author.Image.Format), &authorFormats); err != nil {
log.Error("Error while unmarshal author image formats: ", err)
return err, author
}

post.Author.Image.Format = ""
post.Author.Image.Formats = authorFormats
author.Image.Format = ""
author.Image.Formats = authorFormats

new_posts = append(new_posts, post)
return nil, author
}

func (repository *Repository) SetAuthorWithImageInPosts(posts []Post) []Post {

postIds := []string{}
for _, post := range posts {
postIds = append(postIds, strconv.Itoa(post.Id))
}

c.JSON(http.StatusOK, new_posts)
new_post_ids := strings.Join(postIds, ", ")

authors := []Author{}
authorQuery := fmt.Sprintf(`SELECT a.id, pa.post_id as related_id, a.username, a.name, a.email, a.created_at, a.updated_at, a.bio
FROM authors a
JOIN posts_author_links pa ON pa.post_id IN (%s) AND pa.author_id = a.id`, new_post_ids)

err := repository.Db.Select(&authors, authorQuery)
if err != nil {
log.Error("Error while fetching author: ", err)
return posts
}

authorIds := []string{}
for _, author := range authors {
authorIds = append(authorIds, strconv.Itoa(author.Id))
}

new_author_ids := strings.Join(authorIds, ", ")

images := []Image{}
authorImageQuery := fmt.Sprintf(`SELECT f.id, frm.related_id as related_id, f.name, f.alternative_text, f.caption, f.width, f.height, f.formats as format, f.hash, f.ext, f.mime,
f.size, f.url, f.preview_url, f.provider, f.provider_metadata, f.folder_path, f.created_at, f.updated_at
FROM files f
JOIN files_related_morphs frm ON frm.related_id IN (%s) AND frm.related_type = 'api::author.author' AND frm.file_id = f.id`, new_author_ids)

err = repository.Db.Select(&images, authorImageQuery)
if err != nil {
log.Error("Error while fetching post images: ", err)
return posts
}

// set author image in author
for i, author := range authors {
for _, image := range images {
if author.Id == image.RelatedId {

authors[i].Image = image

// set format of author image if exists
if authors[i].Image.Format != "" {

var authorFormats Formats
if err := json.Unmarshal([]byte(authors[i].Image.Format), &authorFormats); err != nil {
log.Error("Error while unmarshal post image formats: ", err)
return posts
}

authors[i].Image.Format = ""
authors[i].Image.Formats = authorFormats
}
break
}
}
}

// set author with image in post
for i, post := range posts {
for _, author := range authors {
if post.Id == author.RelatedId {
posts[i].Author = author
break
}
}
}

return posts
}
3 changes: 0 additions & 3 deletions post/go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,11 @@ go 1.21.3

replace db => ../db

replace utils => ../utils

require (
github.com/gin-gonic/gin v1.9.1
github.com/jmoiron/sqlx v1.3.5
github.com/sirupsen/logrus v1.9.3
gopkg.in/guregu/null.v3 v3.5.0
utils v0.0.0-00010101000000-000000000000
)

require (
Expand Down
Loading

0 comments on commit 6f2f679

Please sign in to comment.