Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Send and Receive Cloud Messages Function #210

Merged
merged 6 commits into from
Nov 1, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 1 addition & 4 deletions .vscode/launch.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,4 @@
{
// Use IntelliSense to learn about possible attributes.
// Hover to view descriptions of existing attributes.
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
{
Expand All @@ -22,7 +19,7 @@
"request": "launch",
"command": "npm run dev",
"serverReadyAction": {
"pattern": "started server on .+, url: (https?://.+)",
"pattern": "- Local:.+(https?://.+)",
"uriFormat": "%s",
"action": "debugWithChrome"
}
Expand Down
8 changes: 5 additions & 3 deletions components/sections/group/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -58,9 +58,11 @@ const Group = (props: IGroupSectionProps) => {
Online
</h1>
) : (
<h1 className="text-sm md:text-md font-bold text-black">
{getRelativeTime(group.lastMessage?.createdOn)}
</h1>
group.lastMessage && (
<h1 className="text-sm md:text-md font-bold text-black">
{getRelativeTime(group.lastMessage.createdOn)}
</h1>
)
)}
</div>
</div>
Expand Down
46 changes: 35 additions & 11 deletions pages/api/message.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,15 +9,39 @@ export default async function handler(
res: NextApiResponse<object>
) {
if (req.method === 'POST') {
const createdFor = req.body,
messageData = await getUsersCombined([{ createdFor }]);
const { action } = req.body;

if (!messageData) {
res.status(500).json({ error: 'Bad parameters' });
if (action === restContext.getUsersMerged) {
const { createdFor } = req.body,
messageData = await getUsersCombined([{ createdFor }]);

if (!messageData) {
res.status(500).json({ error: 'Bad parameters' });
return;
}

res.status(200).json(messageData[0].createdFor);
} else if (action === restContext.createMessage) {
const { message } = req.body,
{ toId, fromId, groupId, referenceId, content, readBy } = message;

const { data, error } = await supabaseUtil.createMessage(
referenceId,
fromId,
groupId,
toId,
content,
readBy
);

if (error) {
res.status(500).json({ error: 'Bad parameters' });
return;
}

res.status(201).json({ data });
return;
}

res.status(200).json(messageData[0].createdFor);
} else if (req.method === 'DELETE') {
const { referenceId, groupId } = req.query;
const { error } = await supabaseUtil.deleteMessages(referenceId);
Expand Down Expand Up @@ -67,11 +91,11 @@ export default async function handler(
return;
}
} else if (context === restContext.updateMessage) {
const { referenceId, content } = req.body;
const { error } = await supabaseUtil.updateMessageContent(
referenceId,
content
);
const { referenceId, content } = req.body,
{ error } = await supabaseUtil.updateMessageContent(
referenceId,
content
);

if (error) {
res.status(500).json({ error: 'Internal error' });
Expand Down
20 changes: 14 additions & 6 deletions pages/cloud/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ import LayoutSwitch from '@/components/layout';
import Spinner from '@/components/svgs/spinner';
import SectionSwitch from '@/components/sections';
import {
createMessage,
createSocket,
deleteMessage,
getGroups,
Expand Down Expand Up @@ -166,7 +167,7 @@ const Messages = () => {
type: messageWays.RECEIVED,
content: output.content,
fromId: output.fromId,
createdOn: output.createdOn,
createdOn: output.timestamp,
groupId: tempGroup.id,
status: true,
toId: output.toId,
Expand Down Expand Up @@ -351,7 +352,7 @@ const Messages = () => {
setFriend(Object.assign(body, { createdFor: data }));
});
} else if (body?.messageType === messageTypes.DEFAULT) {
console.log('new message (inserted)', payload);
setOutput(body);
}
} else if (eventType === eventTypes.update) {
console.log('updated', payload);
Expand Down Expand Up @@ -591,7 +592,7 @@ const Messages = () => {
newMessage: IMessageProps,
isForward: boolean = false
) => {
if (newMessage?.content && socket) {
if (newMessage?.content) {
const tempGroup: IGroupProps = isForward
? groups?.find((g) => g.id === newMessage.groupId)
: group,
Expand All @@ -613,9 +614,16 @@ const Messages = () => {
if (textInputRef?.current) {
textInputRef.current.focus();
}

socket?.emit('new-message', newMessage);

(async () => {
await createMessage(
Object.assign(newMessage, {
readBy: [
{ id: newMessage.toId, value: false },
{ id: newMessage.fromId, value: true },
],
})
);
})();
if (!isForward) {
const tempGroupIndex = groups.findIndex((g) => g.id === group.id);
groups.splice(tempGroupIndex, 1);
Expand Down
4 changes: 1 addition & 3 deletions pages/local/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -528,7 +528,7 @@ const Messages = () => {
newMessage: IMessageProps,
isforwardModal: boolean = false
) => {
if (newMessage?.content && socket) {
if (newMessage?.content) {
const tempGroup: IGroupProps = isforwardModal
? groups?.find((g) => g.id === newMessage.groupId)
: group,
Expand All @@ -550,9 +550,7 @@ const Messages = () => {
if (textInputRef?.current) {
textInputRef.current.focus();
}

socket?.emit('new-message', newMessage);

if (!isforwardModal) {
const tempGroupIndex = groups.findIndex((g) => g.id === group.id);
groups.splice(tempGroupIndex, 1);
Expand Down
7 changes: 4 additions & 3 deletions utils/enums.ts
Original file line number Diff line number Diff line change
Expand Up @@ -89,9 +89,10 @@ export enum messagingType {
}

export enum restContext {
updateRead = 'UPDATE_READ',
updateMessage = 'UPDATE_MESSAGE',
markAsUnread = 'MARK_AS_UNREAD',
updateRead = 1,
updateMessage = 2,
getUsersMerged = 3,
createMessage = 4,
}

export enum eventTypes {
Expand Down
16 changes: 14 additions & 2 deletions utils/http.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { IMessageDataProps } from '@/types';
import { IMessageDataProps, IMessageProps } from '@/types';
import { apiUrls, restContext } from './enums';

export const getFeeds = async (userId: string) => {
Expand Down Expand Up @@ -58,6 +58,18 @@ export const markAsUnread = async (message: IMessageDataProps) => {
.then((data) => data);
};

export const createMessage = async (message: IMessageProps) => {
return await fetch(apiUrls.message, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ action: restContext.createMessage, message }),
})
.then((response) => response.json())
.then((data) => data);
};

export const updateMessage = async (content: string, referenceId: string) => {
return await fetch(apiUrls.message, {
method: 'PUT',
Expand Down Expand Up @@ -93,7 +105,7 @@ export const getUsersMerged = async (createdFor: string[]) => {
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(createdFor),
body: JSON.stringify({ action: restContext.getUsersMerged, createdFor }),
})
.then((response) => response.json())
.then((data) => data);
Expand Down