Skip to content

Commit

Permalink
feat(master): update api
Browse files Browse the repository at this point in the history
  • Loading branch information
thaisonenouvo committed Nov 25, 2023
1 parent c14fb29 commit b016704
Show file tree
Hide file tree
Showing 23 changed files with 170 additions and 267 deletions.
9 changes: 3 additions & 6 deletions apps/api/helpers/pagination.go
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ func setRequestDefaultValue(request *models.BasePaginationRequest) {
type PaginateResult struct {
CurrentPage int
Count int
TotalPages int
TotalPage int
}

func ConstructPaginateRequest(c *gin.Context) *models.BasePaginationRequest {
Expand Down Expand Up @@ -64,14 +64,11 @@ func Paginate(model interface{}, query *gorm.DB, request *models.BasePaginationR
var totalItems int64
db.DB.Model(&model).Count(&totalItems)

totalPages := int(math.Ceil(float64(totalItems) / float64(limit)))

fmt.Println("totalItems", totalItems)
fmt.Println("totalPages", totalPages)
totalPage := int(math.Ceil(float64(totalItems) / float64(limit)))

return &PaginateResult{
CurrentPage: page,
Count: int(result.RowsAffected),
TotalPages: int(totalPages),
TotalPage: int(totalPage),
}
}
12 changes: 6 additions & 6 deletions apps/api/models/base.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,20 +4,20 @@ import "time"

type Base struct {
ID uint `gorm:"primary_key" json:"id"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
DeletedAt *time.Time `sql:"index" json:"deleted_at"`
CreatedAt time.Time `json:"createdAt"`
UpdatedAt time.Time `json:"updatedAt"`
DeletedAt *time.Time `sql:"index" json:"deletedAt"`
}

type BasePaginationRequest struct {
Page int `json:"page"`
Limit int `json:"limit"`
OrderBy string `json:"order_by"`
OrderBy string `json:"orderBy"`
}

type BasePaginationResponse[T any] struct {
Items []T `json:"items"`
CurrentPage int `json:"current_page"`
CurrentPage int `json:"currentPage"`
Count int `json:"count"`
TotalPages int `json:"total_pages"`
TotalPage int `json:"totalPage"`
}
6 changes: 3 additions & 3 deletions apps/api/models/chat.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,14 @@ type Chat struct {
Base
Name string `gorm:"not null;type:varchar(255)" json:"name"`
Members []*User `gorm:"many2many:chat_users;" json:"members"`
OwnerID uint `gorm:"not null" json:"owner_id"`
LastMessage Message `gorm:"foreignKey:ChatID" json:"last_message"`
OwnerID uint `gorm:"not null" json:"ownerId"`
LastMessage Message `gorm:"foreignKey:ChatID" json:"lastMessage"`
}

type CreateChatRequest struct {
Name string `json:"name" validate:"required"`
}

type AddMemberToChatRequest struct {
UserID uint `json:"user_id" validate:"required"`
UserID uint `json:"userId" validate:"required"`
}
2 changes: 1 addition & 1 deletion apps/api/models/community.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ type Community struct {
Base
Name string `gorm:"not null;type:varchar(255)" json:"name"`
Logo string `gorm:"not null;type:text;" json:"logo"`
OwnerID uint `gorm:"not null" json:"owner_id"`
OwnerID uint `gorm:"not null" json:"ownerId"`
Users []User `gorm:"many2many:user_communities;" json:"users"`
}

Expand Down
8 changes: 4 additions & 4 deletions apps/api/models/friend-request.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,13 @@ package models

type FriendRequest struct {
Base
UserID uint `json:"user_id"`
FriendID uint `json:"friend_id"`
UserID uint `json:"userId"`
FriendID uint `json:"friendId"`
}

type AddFriendRequest struct {
UserID uint `json:"user_id" validate:"required"`
FriendID uint `json:"friend_id" validate:"required"`
UserID uint `json:"userId" validate:"required"`
FriendID uint `json:"friendId" validate:"required"`
}

type AcceptFriendRequest struct {
Expand Down
4 changes: 2 additions & 2 deletions apps/api/models/message.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,8 @@ package models
type Message struct {
Base
Content string `gorm:"not null;type:varchar(255)" json:"content"`
ChatID uint64 `gorm:"not null" json:"chat_id"`
OwnerID uint `gorm:"not null" json:"owner_id"`
ChatID uint64 `gorm:"not null" json:"chatId"`
OwnerID uint `gorm:"not null" json:"ownerId"`
}

type MessageRequest struct {
Expand Down
18 changes: 9 additions & 9 deletions apps/api/models/user.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,8 @@ import (

type User struct {
Base
FirstName string `gorm:"type:varchar(255)" json:"first_name"`
LastName string `gorm:"type:varchar(255)" json:"last_name"`
FirstName string `gorm:"type:varchar(255)" json:"firstName"`
LastName string `gorm:"type:varchar(255)" json:"lastName"`
Email string `gorm:"uniqueIndex;not null;type:varchar(255)" json:"email"`
Salt string `gorm:"not null" json:"-"`
Avatar string `gorm:"type:text" json:"avatar"`
Expand All @@ -17,13 +17,13 @@ type User struct {
Chats []*Chat `gorm:"many2many:chat_users;" json:"chats"`
Communities []Community `gorm:"many2many:user_communities;" json:"communities"`
Friends []*User `gorm:"many2many:user_friends" json:"friends"`
FriendRequests []FriendRequest `json:"friend_requests"`
FriendRequests []FriendRequest `json:"friendRequests"`
}

type UserFriend struct {
Base
UserID string `gorm:"not null" json:"user_id"`
FriendID string `gorm:"not null" json:"friend_id"`
UserID string `gorm:"not null" json:"userId"`
FriendID string `gorm:"not null" json:"friendId"`
}

type SignInRequest struct {
Expand All @@ -40,17 +40,17 @@ type SignUpRequest struct {
}

type GetUserFriendRequest struct {
UserID uint `json:"user_id" validate:"required"`
UserID uint `json:"userId" validate:"required"`
}

type GetUserResponse struct {
User
FriendStatus string `json:"friend_status"`
FriendStatus string `json:"friendStatus"`
}

type UpdateUserRequest struct {
FirstName string `json:"first_name"`
LastName string `json:"last_name"`
FirstName string `json:"firstName"`
LastName string `json:"lastName"`
Avatar string `json:"avatar"`
Gender string `json:"gender" enum:"male,female"`
}
Expand Down
2 changes: 0 additions & 2 deletions apps/api/router/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -43,8 +43,6 @@ func initRoutes(r *gin.Engine) {
auth.POST("/communities", handlers.CreateCommunity)
auth.GET("/chats/:chatID/messages", handlers.GetMessages)
auth.POST("/chats/:chatID/messages", handlers.SendMessage)

// User
auth.POST("/users/add-friend", handlers.AddFriend)
auth.POST("/users/accept-friend", handlers.AcceptFriend)
auth.GET("/users/:userID/friends", handlers.GetUserFriends)
Expand Down
17 changes: 6 additions & 11 deletions apps/api/services/user.go
Original file line number Diff line number Diff line change
@@ -1,8 +1,6 @@
package services

import (
"fmt"

"github.com/jinzhu/copier"
"github.com/pkg/errors"
h "github.com/tranthaison1231/meta-clone/api/helpers"
Expand Down Expand Up @@ -54,7 +52,7 @@ func GetUsers(request *models.BasePaginationRequest, currentUser *models.User) (

var userFriend models.UserFriend

query := db.DB.Raw("SELECT * FROM user_friends WHERE user_id = ? AND friend_id = ?", user.ID, currentUser.ID).Scan(&userFriend)
query := db.DB.Raw("SELECT * FROM user_friends WHERE userId = ? AND friendId = ?", user.ID, currentUser.ID).Scan(&userFriend)

if query.RowsAffected == 1 {
response.FriendStatus = "Friend"
Expand All @@ -67,7 +65,7 @@ func GetUsers(request *models.BasePaginationRequest, currentUser *models.User) (
Items: getUserResponse,
CurrentPage: pagination.CurrentPage,
Count: pagination.Count,
TotalPages: pagination.TotalPages,
TotalPage: pagination.TotalPage,
}, nil
}

Expand All @@ -86,7 +84,7 @@ func AddFriend(userId uint, friendId uint) (*models.FriendRequest, error) {
var friendRequest models.FriendRequest
var user models.User

result := db.DB.Where("user_id = ? AND friend_id = ? OR user_id = ? AND friend_id = ?", userId, friendId, friendId, userId).Find(&friendRequest)
result := db.DB.Where("user_id = ? AND friend_id = ? OR userId = ? AND friendId = ?", userId, friendId, friendId, userId).Find(&friendRequest)

if err := result.Error; err != nil {
return nil, err
Expand All @@ -108,19 +106,19 @@ func AddFriend(userId uint, friendId uint) (*models.FriendRequest, error) {
}
}

new_friend_request := models.FriendRequest{
newFriendRequest := models.FriendRequest{
UserID: userId,
FriendID: friendId,
}

err := db.DB.Create(&new_friend_request).Error
err := db.DB.Create(&newFriendRequest).Error

if err != nil {
return nil, err

}

return &new_friend_request, nil
return &newFriendRequest, nil
}

func AcceptFriend(userId uint, friendId uint) (string, error) {
Expand All @@ -130,8 +128,6 @@ func AcceptFriend(userId uint, friendId uint) (string, error) {

result := db.DB.Where("user_id = ? AND friend_id = ?", userId, friendId).First(&friendRequest)

fmt.Println("=======", userId, friendId)

if err := result.Error; err != nil {
return "", err
}
Expand Down Expand Up @@ -162,7 +158,6 @@ func AcceptFriend(userId uint, friendId uint) (string, error) {
return "Added Friend", nil
}

// func DenyFriend(userId uint, friendId uint)
func GetUserByID(id uint) (*models.User, error) {
var user models.User
result := db.DB.Where("id = ?", id).First(&user)
Expand Down
11 changes: 4 additions & 7 deletions apps/messenger-web/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -25,10 +25,10 @@
"prettier": "^3.1.0",
"prettier-plugin-organize-attributes": "^1.0.0",
"prettier-plugin-organize-imports": "^3.2.4",
"prettier-plugin-svelte": "^3.1.1",
"prettier-plugin-svelte": "^3.1.2",
"prettier-plugin-tailwindcss": "^0.5.7",
"svelte": "latest",
"svelte-check": "^3.6.1",
"svelte-check": "^3.6.2",
"sveltekit-superforms": "^1.10.2",
"tailwindcss": "^3.3.5",
"tslib": "^2.6.2",
Expand All @@ -40,16 +40,13 @@
"@emoji-mart/data": "^1.1.2",
"@meta-clone/utils": "workspace:*",
"@sveltestack/svelte-query": "^1.6.0",
"axios": "^1.6.2",
"bits-ui": "^0.9.8",
"clsx": "^2.0.0",
"emoji-mart": "^5.5.2",
"linkify-html": "^4.1.3",
"lodash-es": "^4.17.21",
"lucide-svelte": "^0.292.0",
"lucide-svelte": "^0.293.0",
"open-graph-scraper": "^6.3.2",
"stream": "^0.0.2",
"tailwind-merge": "^2.0.0",
"tailwind-variants": "^0.1.18"
}
}
}
22 changes: 9 additions & 13 deletions apps/messenger-web/src/lib/apis/auth.ts
Original file line number Diff line number Diff line change
@@ -1,32 +1,28 @@
import { BASE_URL } from '$lib/services/request';
import { request } from '$lib/services/request';
import type { SignInRequest, SignUpRequest, User } from '$lib/types';
import type { BaseResponseType } from '$lib/types/response';

export interface GetMeResponse {
user: User
user: User;
}

export const authApi = {
login: async ({ email, password }: SignInRequest) => {
const rest = await fetch(`${BASE_URL}/sign-in`, {
const data = await request(`/sign-in`, {
method: 'POST',
body: JSON.stringify({
email: email,
password: password
})
});
return rest.json();
return data;
},
getMe: async () => {
const rest = await fetch(`${BASE_URL}/me`, {
headers: {
Authorization: `Bearer ${localStorage.getItem('token')}`
}
});
return await rest.json() as BaseResponseType<GetMeResponse>;
const data: BaseResponseType<GetMeResponse> = await request(`/me`);
return data;
},
signUp: async ({email, gender, password, avatar }: SignUpRequest) => {
const rest = await fetch(`${BASE_URL}/sign-up`, {
signUp: async ({ email, gender, password, avatar }: SignUpRequest) => {
const data = await request('/sign-up', {
method: 'POST',
body: JSON.stringify({
email,
Expand All @@ -35,6 +31,6 @@ export const authApi = {
avatar
})
});
return rest.json();
return data;
}
};
10 changes: 3 additions & 7 deletions apps/messenger-web/src/lib/apis/chats.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,8 @@
import { BASE_URL } from '$lib/services/request';
import { request } from '$lib/services/request';

export const chatsApi = {
getAll: async () => {
const rest = await fetch(`${BASE_URL}/chats`, {
headers: {
Authorization: `Bearer ${localStorage.getItem('token')}`
}
});
return rest.json();
const data = await request(`/chats`);
return data;
}
};
10 changes: 3 additions & 7 deletions apps/messenger-web/src/lib/apis/communities.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,8 @@
import { BASE_URL } from '$lib/services/request';
import { request } from '$lib/services/request';

export const communitiesApi = {
getAll: async () => {
const rest = await fetch(`${BASE_URL}/communities`, {
headers: {
Authorization: `Bearer ${localStorage.getItem('token')}`
}
});
return rest.json();
const data = await request(`/communities`);
return data;
}
};
Loading

1 comment on commit b016704

@vercel
Copy link

@vercel vercel bot commented on b016704 Nov 25, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please sign in to comment.