Skip to content

Commit

Permalink
3- getMyConversations query added
Browse files Browse the repository at this point in the history
  • Loading branch information
burakorkmez committed Mar 30, 2024
1 parent 9b39574 commit 19df891
Show file tree
Hide file tree
Showing 4 changed files with 72 additions and 8 deletions.
54 changes: 53 additions & 1 deletion convex/conversations.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { ConvexError, v } from "convex/values";
import { mutation } from "./_generated/server";
import { mutation, query } from "./_generated/server";

export const createConversation = mutation({
args: {
Expand Down Expand Up @@ -49,6 +49,58 @@ export const createConversation = mutation({
},
});

export const getMyConversations = query({
args: {},
handler: async (ctx, args) => {
const identity = await ctx.auth.getUserIdentity();
if (!identity) throw new ConvexError("Unauthorized");

const user = await ctx.db
.query("users")
.withIndex("by_tokenIdentifier", (q) => q.eq("tokenIdentifier", identity.tokenIdentifier))
.unique();

if (!user) throw new ConvexError("User not found");

const conversations = await ctx.db.query("conversations").collect();

const myConversations = conversations.filter((conversation) => {
return conversation.participants.includes(user._id);
});

const conversationsWithDetails = await Promise.all(
myConversations.map(async (conversation) => {
let userDetails = {};

if (!conversation.isGroup) {
const otherUserId = conversation.participants.find((id) => id !== user._id);
const userProfile = await ctx.db
.query("users")
.filter((q) => q.eq(q.field("_id"), otherUserId))
.take(1);

userDetails = userProfile[0];
}

const lastMessage = await ctx.db
.query("messages")
.filter((q) => q.eq(q.field("conversation"), conversation._id))
.order("desc")
.take(1);

// return should be in this order, otherwise _id field will be overwritten
return {
...userDetails,
...conversation,
lastMessage: lastMessage[0] || null,
};
})
);

return conversationsWithDetails;
},
});

export const generateUploadUrl = mutation(async (ctx) => {
return await ctx.storage.generateUploadUrl();
});
7 changes: 7 additions & 0 deletions convex/schema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,4 +17,11 @@ export default defineSchema({
groupImage: v.optional(v.string()),
admin: v.optional(v.id("users")),
}),

messages: defineTable({
conversation: v.id("conversations"),
sender: v.string(), // should be string so that it doesn't throw errors in openai part ("ChatGPT")
content: v.string(),
messageType: v.union(v.literal("text"), v.literal("image"), v.literal("video")),
}).index("by_conversation", ["conversation"]),
});
10 changes: 6 additions & 4 deletions src/components/home/conversation.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,16 @@ import { formatDate } from "@/lib/utils";
import { Avatar, AvatarFallback, AvatarImage } from "../ui/avatar";
import { MessageSeenSvg } from "@/lib/svgs";
import { ImageIcon, Users, VideoIcon } from "lucide-react";
import { useQuery } from "convex/react";
import { api } from "../../../convex/_generated/api";

const Conversation = ({ conversation }: { conversation: any }) => {
const conversationImage = conversation.groupImage;
const conversationName = conversation.groupName || "Private Chat";
const conversationImage = conversation.groupImage || conversation.image;
const conversationName = conversation.groupName || conversation.name;
const lastMessage = conversation.lastMessage;
const lastMessageType = lastMessage?.messageType;
const me = useQuery(api.users.getMe);
//
const authUser = { _id: "user1" };

return (
<>
Expand All @@ -31,7 +33,7 @@ const Conversation = ({ conversation }: { conversation: any }) => {
</span>
</div>
<p className='text-[12px] mt-1 text-gray-500 flex items-center gap-1 '>
{lastMessage?.sender === authUser?._id ? <MessageSeenSvg /> : ""}
{lastMessage?.sender === me?._id ? <MessageSeenSvg /> : ""}
{conversation.isGroup && <Users size={16} />}
{!lastMessage && "Say Hi!"}
{lastMessageType === "text" ? (
Expand Down
9 changes: 6 additions & 3 deletions src/components/home/left-panel.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,15 +2,18 @@
import { ListFilter, Search } from "lucide-react";
import { Input } from "../ui/input";
import ThemeSwitch from "./theme-switch";
import { conversations } from "@/dummy-data/db";
import Conversation from "./conversation";
import { UserButton } from "@clerk/nextjs";

import UserListDialog from "./user-list-dialog";
import { useConvexAuth } from "convex/react";
import { useConvexAuth, useQuery } from "convex/react";
import { api } from "../../../convex/_generated/api";

const LeftPanel = () => {
const { isAuthenticated } = useConvexAuth();
const conversations = useQuery(api.conversations.getMyConversations, isAuthenticated ? undefined : "skip");

console.log(conversations);
return (
<div className='w-1/4 border-gray-600 border-r'>
<div className='sticky top-0 bg-left-panel z-10'>
Expand Down Expand Up @@ -43,7 +46,7 @@ const LeftPanel = () => {
{/* Chat List */}
<div className='my-3 flex flex-col gap-0 max-h-[80%] overflow-auto'>
{/* Conversations will go here*/}
{conversations.map((conversation) => (
{conversations?.map((conversation) => (
<Conversation key={conversation._id} conversation={conversation} />
))}

Expand Down

0 comments on commit 19df891

Please sign in to comment.