Skip to content

Commit

Permalink
fix bugs
Browse files Browse the repository at this point in the history
  • Loading branch information
shreeharsha-factly committed Jul 9, 2024
1 parent 6907b02 commit ac5ed52
Show file tree
Hide file tree
Showing 9 changed files with 84 additions and 98 deletions.
5 changes: 5 additions & 0 deletions api/config/database.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import (
"gorm.io/driver/sqlite"
"gorm.io/gorm"
"gorm.io/gorm/logger"
"gorm.io/gorm/schema"
)

// DB - gorm DB
Expand Down Expand Up @@ -42,6 +43,10 @@ func SetupDB() {
LogLevel: logger.Info,
Colorful: true,
}),
NamingStrategy: schema.NamingStrategy{
TablePrefix: "de_",
SingularTable: true,
},
})

if err != nil {
Expand Down
6 changes: 3 additions & 3 deletions api/graph/resolvers/post.go
Original file line number Diff line number Diff line change
Expand Up @@ -234,7 +234,7 @@ func (r *queryResolver) Posts(ctx context.Context, formats *models.PostFilter, c
pageSortBy = *sortBy
}

order := "posts." + pageSortBy + " " + pageSortOrder
order := "de_post." + pageSortBy + " " + pageSortOrder

result := &models.PostsPaging{}
result.Nodes = make([]*models.Post, 0)
Expand Down Expand Up @@ -287,12 +287,12 @@ func (r *queryResolver) Posts(ctx context.Context, formats *models.PostFilter, c
}
}

tx.Group("posts.id")
tx.Group("de_post.id")
filterStr = strings.Trim(filterStr, " AND")
var total int64
tx.Where(&models.Post{
SpaceID: sID,
}).Where(filterStr).Count(&total).Offset(offset).Limit(pageLimit).Order(order).Select("posts.*").Find(&result.Nodes)
}).Where(filterStr).Count(&total).Offset(offset).Limit(pageLimit).Order(order).Select("de_post.*").Find(&result.Nodes)

tx.Commit()

Expand Down
5 changes: 3 additions & 2 deletions api/graph/validator/space.go
Original file line number Diff line number Diff line change
Expand Up @@ -56,8 +56,9 @@ func CheckSpace() func(http.Handler) http.Handler {

spaceToken := &models.SpaceToken{}

err = config.DB.Model(&models.SpaceToken{}).Where(&models.Space{
ID: sID,
err = config.DB.Model(&models.SpaceToken{}).Where(&models.SpaceToken{
SpaceID: sID,
Token: authHeader,
}).First(&spaceToken).Error

if err != nil {
Expand Down
113 changes: 59 additions & 54 deletions server/service/core/action/post/list.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import (
"github.com/factly/dega-server/config"
"github.com/factly/dega-server/service/core/model"
factCheckModel "github.com/factly/dega-server/service/fact-check/model"
"github.com/factly/dega-server/test/models"
"github.com/factly/dega-server/util"
"github.com/factly/dega-server/util/arrays"
"github.com/factly/dega-server/util/meilisearch"
Expand All @@ -17,7 +18,6 @@ import (
"github.com/factly/x/paginationx"
"github.com/factly/x/renderx"
"github.com/google/uuid"
"github.com/spf13/viper"
"gorm.io/gorm"
)

Expand Down Expand Up @@ -233,9 +233,6 @@ func PublicList(w http.ResponseWriter, r *http.Request) {

sortBy := r.URL.Query().Get("sort_by")
sortOrder := r.URL.Query().Get("sort_order")
ids := r.URL.Query()["ids"]
isFeatured := r.URL.Query().Get("is_featured")
isFeaturedBool := false
formatIDs := r.URL.Query()["format_ids"]

formatUUIDs, err := arrays.StrToUUID(formatIDs)
Expand All @@ -261,28 +258,8 @@ func PublicList(w http.ResponseWriter, r *http.Request) {
}

categorySlugs := r.URL.Query()["category_slugs"]
authorIds := r.URL.Query()["author_ids"]
isPage := r.URL.Query().Get("is_page")
isPageBool := false
status := r.URL.Query().Get("status")

if isFeatured == "true" {
isFeaturedBool = true
}

if isPage == "true" {
isPageBool = true
}

uuids := make([]uuid.UUID, 0)

if len(ids) > 0 {
uuids, err = arrays.StrToUUID(ids)
if err != nil {
errorx.Render(w, errorx.Parser(errorx.InvalidID()))
return
}
}
status := r.URL.Query().Get("status")

if len(tagSlugs) > 0 {
tags := make([]model.Tag, 0)
Expand Down Expand Up @@ -331,42 +308,70 @@ func PublicList(w http.ResponseWriter, r *http.Request) {
Nodes: make([]postData, 0),
}

posts := make([]model.Post, 0)

order := "de_post." + pageSortBy + " " + pageSortOrder

tx := config.DB.Model(&model.Post{})

tx.Preload("Tags").
Preload("Categories").
Preload("Medium").
Preload("Format").
Joins("JOIN de_post_tags ON de_post_tags.post_id = de_post.id").
Joins("JOIN de_post_categories ON de_post_categories.post_id = de_post.id").
Joins("JOIN de_post_author ON de_post_author.post_id = de_post.id").
Where("de_post.space_id = ?", authCtx.SpaceID).
Where("de_post_tags.tag_id IN ?", tagUUIDs).
Where("de_post_categories.category_id IN ?", categoryUUIDs).
Where("de_post_author.author_id IN ?", authorIds).
Where("de_post.format_id IN ?", formatUUIDs).
Where("de_post.id IN ?", uuids).
Where("de_post.is_page = ?", isPageBool).
Where("de_post.status = ?", status).
Where("de_post.is_featured = ?", isFeaturedBool).
Count(&result.Total).
Limit(limit).
Offset(offset).
Order(order).
Find(&posts)
tx := config.DB.Model(&models.Post{}).Where("is_page = ?", false)

for _, post := range posts {
postList := &postData{}
postList.Post = post
result.Nodes = append(result.Nodes, *postList)
if status != "" {
tx.Where("status = ?", status)
} else {
tx.Where("status = ?", "publish")
}

userIDs := make([]string, 0)
// get user ids if slugs provided

filterStr := ""
if len(categoryIds) > 0 || len(categorySlugs) > 0 {
tx.Joins("INNER JOIN de_post_categories ON de_post_categories.post_id = posts.id")
if len(categoryIds) > 0 {
filterStr = filterStr + fmt.Sprint("de_post_categories.category_id IN (", strings.Trim(strings.Replace(fmt.Sprint(categoryIds), " ", ",", -1), "[]"), ") AND ")
} else if len(categorySlugs) > 0 {
tx.Joins("INNER JOIN de_category ON de_post_categories.category_id = categories.id")
filterStr = filterStr + fmt.Sprint("de_category.slug IN (", createFilters(categorySlugs), ") AND ")
}
}

if len(userIDs) > 0 {
tx.Joins("INNER JOIN de_post_author ON de_post_author.post_id = de_post.id")
filterStr = filterStr + fmt.Sprint("de_post_author.author_id IN (", strings.Trim(strings.Replace(fmt.Sprint(userIDs), " ", ",", -1), "[]"), ") AND ")
}

if len(tagIds) > 0 || len(tagSlugs) > 0 {
tx.Joins("INNER JOIN de_post_tags ON de_post_tags.post_id = posts.id")
if len(tagIds) > 0 {
filterStr = filterStr + fmt.Sprint("de_post_tags.tag_id IN (", strings.Trim(strings.Replace(fmt.Sprint(tagIds), " ", ",", -1), "[]"), ") AND ")
} else if len(tagSlugs) > 0 {
tx.Joins("INNER JOIN de_tags ON de_post_tags.tag_id = tags.id")
filterStr = filterStr + fmt.Sprint("de_tags.slug IN (", createFilters(tagSlugs), ") AND ")
}
}

if len(formatIDs) > 0 || len(formatSlugs) > 0 {
if len(formatIDs) > 0 {
filterStr = filterStr + fmt.Sprint("de_post.format_id IN (", strings.Trim(strings.Replace(fmt.Sprint(formatIDs), " ", ",", -1), "[]"), ") AND ")
} else if len(formatSlugs) > 0 {
tx.Joins("INNER JOIN de_format ON de_post.format_id = de_format.id")
filterStr = filterStr + fmt.Sprint("de_format.slug IN (", createFilters(formatSlugs), ") AND ")
}
}

tx.Group("de_post.id")
filterStr = strings.Trim(filterStr, " AND")
tx.Where(&model.Post{
SpaceID: authCtx.SpaceID,
}).Where(filterStr).Count(&result.Total).Offset(offset).Limit(limit).Order(order).Select("de_post.*").Find(&result.Nodes)

tx.Commit()

renderx.JSON(w, http.StatusOK, result)

}

func createFilters(arr []string) string {
filter := strings.Trim(strings.Replace(fmt.Sprint(arr), " ", "','", -1), "[]")
filter = "'" + filter + "'"
return filter
}

func generateFilters(tagIDs, categoryIDs, authorIDs, status []string) string {
Expand Down
15 changes: 8 additions & 7 deletions server/service/core/action/post/update.go
Original file line number Diff line number Diff line change
Expand Up @@ -84,13 +84,6 @@ func update(w http.ResponseWriter, r *http.Request) {
result.Claims = make([]factCheckModel.Claim, 0)

// fetch all authors
authors, err := util.GetAuthors(r.Header.Get("Authorization"), authCtx.OrganisationID, post.AuthorIDs)

if err != nil {
loggerx.Error(err)
errorx.Render(w, errorx.Parser(errorx.InternalServerError()))
return
}

// check record exists or not
err = config.DB.Where(&model.Post{
Expand Down Expand Up @@ -359,6 +352,14 @@ func update(w http.ResponseWriter, r *http.Request) {
PostID: id,
}).Find(&updatedPostAuthors)

authors, err := util.GetAuthors(r.Header.Get("Authorization"), authCtx.OrganisationID, toCreateIDs)

if err != nil {
loggerx.Error(err)
errorx.Render(w, errorx.Parser(errorx.InternalServerError()))
return
}

// appending previous post authors to result
for _, postAuthor := range updatedPostAuthors {
aID := fmt.Sprint(postAuthor.AuthorID)
Expand Down
5 changes: 4 additions & 1 deletion server/util/authors.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,10 @@ import (
)

func GetAuthors(token, orgID string, ids []string) (map[string]model.Author, error) {
zitadelUsers, err := zitadel.GetOrganisationUsers(viper.GetString("ZITADEL_PERSONAL_ACCESS_TOKEN"), orgID, ids)
if token == "" {
token = viper.GetString("ZITADEL_PERSONAL_ACCESS_TOKEN")
}
zitadelUsers, err := zitadel.GetOrganisationUsers(token, orgID, ids)

if err != nil {
return nil, err
Expand Down
24 changes: 0 additions & 24 deletions studio/src/App.js
Original file line number Diff line number Diff line change
Expand Up @@ -70,30 +70,6 @@ function App() {
}, [zitadel]);

useEffect(() => {
if (
window.localStorage.getItem(
'oidc.user:' +
window.REACT_APP_ZITADEL_AUTHORITY +
':' +
window.REACT_APP_ZITADEL_CLIENT_ID,
)
) {
const userInfo = JSON.parse(
window.localStorage.getItem(
'oidc.user:' +
window.REACT_APP_ZITADEL_AUTHORITY +
':' +
window.REACT_APP_ZITADEL_CLIENT_ID,
),
);
if (userInfo.expires_at) {
const expiryTime = new Date(userInfo.expires_at * 1000);
if (expiryTime < Date.now()) {
window.localStorage.setItem('return_to', window.location.href);
login();
}
}
}
if (
!authenticated &&
!window.location.href.includes('redirect') &&
Expand Down
2 changes: 1 addition & 1 deletion studio/src/components/FormItems/DescriptionInput.js
Original file line number Diff line number Diff line change
Expand Up @@ -104,7 +104,7 @@ const DescriptionInput = ({
onFileAdded={(file) => {
const data = file.data;
const url = data.thumbnail ? data.thumbnail : URL.createObjectURL(data);
const image = new Image();
const image = document.createElement('img');
image.src = url;
image.onload = () => {
// uppy.setFileMeta(file.id, { width: image.width, height: image.height });
Expand Down
7 changes: 1 addition & 6 deletions studio/src/components/GlobalNav/AccountMenu.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,20 +2,15 @@ import { UserOutlined } from '@ant-design/icons';
import { Menu, Dropdown, Button, Avatar } from 'antd';
import React from 'react';
import { LogoutOutlined, DownOutlined } from '@ant-design/icons';
import { useDispatch, useSelector } from 'react-redux';
import { getUserProfile } from '../../actions/profile';
import { useSelector } from 'react-redux';

const AccountMenu = () => {
const dispatch = useDispatch();
const { profile, loading } = useSelector((state) => {
return {
profile: state.profile.details ? state.profile.details : null,
loading: state.profile.loading,
};
});
React.useEffect(() => {
dispatch(getUserProfile());
}, [dispatch]);

const handleLogout = () => {
// clear all local storage and cookies
Expand Down

0 comments on commit ac5ed52

Please sign in to comment.