Skip to content

Commit

Permalink
Added realtime DB deletion on post delete
Browse files Browse the repository at this point in the history
  • Loading branch information
nidhish-nayak committed Mar 13, 2024
1 parent 17c226d commit 67990bc
Show file tree
Hide file tree
Showing 18 changed files with 241 additions and 201 deletions.
19 changes: 1 addition & 18 deletions client/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -2,24 +2,7 @@
<html lang="en">
<head>
<meta charset="UTF-8" />
<link
rel="icon"
type="image/png"
href="/title-logo-8x8.png"
sizes="8x8"
/>
<link
rel="icon"
type="image/png"
href="/title-logo-16x16.png"
sizes="16x16"
/>
<link
rel="icon"
type="image/png"
href="/title-logo-32x32.png"
sizes="32x32"
/>
<link rel="icon" type="image/png" href="/logo.png" sizes="16x16" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Trendz.</title>
</head>
Expand Down
Binary file added client/public/logo.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file removed client/public/title-logo-16x16.png
Binary file not shown.
Binary file removed client/public/title-logo-32x32.png
Binary file not shown.
Binary file removed client/public/title-logo-8x8.png
Binary file not shown.
2 changes: 1 addition & 1 deletion client/src/components/logout/logout.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ const Logout: React.FC<LogoutProps> = (props) => {
try {
const res = await axios.post(API_URL);
if (res.status === 200) {
sessionStorage.removeItem("user");
localStorage.removeItem("user");
navigate("/login");
} else {
console.log(res.data);
Expand Down
2 changes: 1 addition & 1 deletion client/src/components/posts/posts.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ const Posts = () => {

if (error) {
console.error(error.message);
sessionStorage.removeItem("user");
localStorage.removeItem("user");
navigate("/login");
alert("Please login again!");
return <PostsError />;
Expand Down
57 changes: 49 additions & 8 deletions client/src/components/rightbar/activity/activity.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -38,12 +38,24 @@ const Activity = () => {
},
});

const activityDeleteMutation = useMutation({
mutationFn: (table_id: number) =>
axiosRequest.delete(`/activities/${table_id}`),
onSuccess: () => {
setActivity(null);
return queryClient.invalidateQueries({ queryKey: ["activities"] });
},
onError(error) {
console.error("Activity deletion failed: ", error);
},
});

// Subscribe to INSERT events for posts table
useEffect(() => {
let postChannel: RealtimeChannel;
let postAddChannel: RealtimeChannel;

if (isRealtime === true) {
postChannel = supabase
postAddChannel = supabase
.channel("inserted-post")
.on(
"postgres_changes",
Expand All @@ -59,12 +71,30 @@ const Activity = () => {
});
}
)
.on(
"postgres_changes",
{
event: "DELETE",
schema: "public",
table: "posts",
},
(payload) => {
setPrevActivity(activity);
setActivity(payload);
queryClient.invalidateQueries({
queryKey: ["activities"],
});
queryClient.invalidateQueries({
queryKey: ["posts"],
});
}
)
.subscribe();
}

return () => {
if (postChannel) {
postChannel.unsubscribe();
if (postAddChannel) {
postAddChannel.unsubscribe();
}
};
// eslint-disable-next-line react-hooks/exhaustive-deps
Expand All @@ -74,12 +104,13 @@ const Activity = () => {
if (
activity &&
activityMutation.isPending === false &&
prevActivity !== activity
prevActivity !== activity &&
activity.eventType === "INSERT"
) {
const table_name: string = activity.table;
const table_id: number = activity.new.id;
const message = "Added a new post";
const activity_created_at: string = activity.commit_timestamp;
const table_id: number = activity.new.id;
const user_id: number = activity.new.userId;

if (user_id !== currentUser?.id) {
Expand All @@ -96,16 +127,26 @@ const Activity = () => {
});
}
}

if (
activity &&
activityMutation.isPending === false &&
prevActivity !== activity &&
activity.eventType === "DELETE"
) {
const table_id: number = activity.old.id;

return activityDeleteMutation.mutate(table_id);
}
}, [
activity,
activityDeleteMutation,
activityMutation,
currentUser?.id,
prevActivity,
queryClient,
]);

console.log(activity);

const getActivities = async (): Promise<ACTIVITY_GET_TYPES[]> => {
const res = await axiosRequest.get("/activities");
return res.data;
Expand Down
18 changes: 13 additions & 5 deletions client/src/components/rightbar/activity/activity.types.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,17 @@
import { RealtimePostgresInsertPayload } from "@supabase/supabase-js";
import {
RealtimePostgresDeletePayload,
RealtimePostgresInsertPayload,
} from "@supabase/supabase-js";

export type REALTIME_TYPE = RealtimePostgresInsertPayload<{
// eslint-disable-next-line @typescript-eslint/no-explicit-any
[key: string]: any;
}>;
export type REALTIME_TYPE =
| RealtimePostgresInsertPayload<{
// eslint-disable-next-line @typescript-eslint/no-explicit-any
[key: string]: any;
}>
| RealtimePostgresDeletePayload<{
// eslint-disable-next-line @typescript-eslint/no-explicit-any
[key: string]: any;
}>;

export type ACTIVITY_POST_TYPES = {
table_name: string;
Expand Down
50 changes: 50 additions & 0 deletions client/src/components/rightbar/online/online.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
import "../rightbar.scss";

const Online = () => {
return (
<div className="item">
<div className="item-container">
<div className="item-title-realtime">Online Friends</div>
<div
className="item-realtime"
title="Show your online status to others - Heavy server load!"
>
<p className="realtime-title">Realtime</p>
<div className="realtime-circle" />
</div>
</div>
<div className="user">
<div className="userInfo">
<img
src="https://images.pexels.com/photos/4881619/pexels-photo-4881619.jpeg?auto=compress&cs=tinysrgb&w=1600"
alt="user-image"
/>
<div className="online" />
<span>Jane Doe</span>
</div>
</div>
<div className="user">
<div className="userInfo">
<img
src="https://images.pexels.com/photos/4881619/pexels-photo-4881619.jpeg?auto=compress&cs=tinysrgb&w=1600"
alt="user-image"
/>
<div className="online" />
<span>Jane Doe</span>
</div>
</div>
<div className="user">
<div className="userInfo">
<img
src="https://images.pexels.com/photos/4881619/pexels-photo-4881619.jpeg?auto=compress&cs=tinysrgb&w=1600"
alt="user-image"
/>
<div className="online" />
<span>Jane Doe</span>
</div>
</div>
</div>
);
};

export default Online;
46 changes: 2 additions & 44 deletions client/src/components/rightbar/rightbar.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import Activity from "./activity/activity";
import Online from "./online/online";
import "./rightbar.scss";
import Suggested from "./suggested/suggested";

Expand All @@ -8,50 +9,7 @@ const Rightbar = () => {
<div className="container">
<Suggested />
<Activity />
<div className="item">
<div className="item-container">
<div className="item-title-realtime">
Online Friends
</div>
<div
className="item-realtime"
title="Realtime updates cause heavy load on servers. Default state is set to disabled."
>
<p className="realtime-title">Realtime</p>
<div className="realtime-circle" />
</div>
</div>
<div className="user">
<div className="userInfo">
<img
src="https://images.pexels.com/photos/4881619/pexels-photo-4881619.jpeg?auto=compress&cs=tinysrgb&w=1600"
alt="user-image"
/>
<div className="online" />
<span>Jane Doe</span>
</div>
</div>
<div className="user">
<div className="userInfo">
<img
src="https://images.pexels.com/photos/4881619/pexels-photo-4881619.jpeg?auto=compress&cs=tinysrgb&w=1600"
alt="user-image"
/>
<div className="online" />
<span>Jane Doe</span>
</div>
</div>
<div className="user">
<div className="userInfo">
<img
src="https://images.pexels.com/photos/4881619/pexels-photo-4881619.jpeg?auto=compress&cs=tinysrgb&w=1600"
alt="user-image"
/>
<div className="online" />
<span>Jane Doe</span>
</div>
</div>
</div>
<Online />
</div>
</div>
);
Expand Down
3 changes: 1 addition & 2 deletions client/src/components/stories/stories.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ import { GROUPED_STORIES_TYPE, formatStories } from "./stories.util";
const Stories = () => {
const { currentUser } = useContext(AuthContext);
const queryClient = useQueryClient();
if (!currentUser) throw Error("User not found!");

const [isPostOpen, setIsPostOpen] = useState(false);
const [localStory, setLocalStory] = useState<string | null>(null);
Expand Down Expand Up @@ -116,8 +117,6 @@ const Stories = () => {
if (getStoryError || !getStoryData)
throw Error("get_stories fetch failed from server!");

if (!currentUser) return <div>User not found!</div>;

const { profilePic } = currentUser;
const unformattedStories: GET_STORIES_TYPE = getStoryData;
const formattedStories: GROUPED_STORIES_TYPE = formatStories(getStoryData);
Expand Down
4 changes: 2 additions & 2 deletions client/src/context/authContext.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -25,12 +25,12 @@ export const AuthContext = createContext<AuthContextTypes>({

export const AuthProvider = ({ children }: { children: ReactNode }) => {
const [currentUser, setCurrentUser] = useState(() => {
const storedUser = sessionStorage.getItem("user");
const storedUser = localStorage.getItem("user");
return JSON.parse(storedUser!);
});

useEffect(() => {
sessionStorage.setItem("user", JSON.stringify(currentUser));
localStorage.setItem("user", JSON.stringify(currentUser));
}, [currentUser]);

const login = async (inputs: LoginTypes): Promise<LoginResponseTypes> => {
Expand Down
4 changes: 2 additions & 2 deletions client/src/context/darkModeContext.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -12,13 +12,13 @@ export const DarkModeContext = createContext<DarkModeContextTypes>({

export const DarkModeProvider = ({ children }: { children: ReactNode }) => {
const [darkMode, setDarkMode] = useState(() => {
const storedDarkMode = sessionStorage.getItem("darkMode");
const storedDarkMode = localStorage.getItem("darkMode");
// Set default mode = dark
return storedDarkMode ? JSON.parse(storedDarkMode) : true;
});

useEffect(() => {
sessionStorage.setItem("darkMode", darkMode);
localStorage.setItem("darkMode", darkMode);
}, [darkMode]);

const toggleTheme = () => {
Expand Down
2 changes: 1 addition & 1 deletion client/src/pages/profile/components/editProfile.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ const EditProfile = ({ closeModal }: { closeModal: () => void }) => {
axiosRequest.put("/users", formData),
onSuccess: () => {
if (formData === null) return alert("Null formData sent to server");
sessionStorage.setItem("user", JSON.stringify(formData));
localStorage.setItem("user", JSON.stringify(formData));
queryClient.invalidateQueries({ queryKey: ["users", id] });

closeModal();
Expand Down
Loading

0 comments on commit 67990bc

Please sign in to comment.