Skip to content

Commit

Permalink
better folder structure and some optimizations
Browse files Browse the repository at this point in the history
  • Loading branch information
Tanish2002 committed Nov 28, 2023
1 parent 8592d05 commit fe9cc0d
Show file tree
Hide file tree
Showing 26 changed files with 187 additions and 159 deletions.
5 changes: 4 additions & 1 deletion src/utils/fetchAreas.ts → src/api/areas.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,11 @@
import { LatLng } from "react-native-maps";

import { Marker } from "@/types";
import { axios_ as axios } from "@/utils/axios";

import { axios_ as axios } from "./axios";
export const areasKeys = {
heatmap: ["heatMap"] as const
};

export async function fetchAreas(): Promise<LatLng[]> {
try {
Expand Down
10 changes: 9 additions & 1 deletion src/utils/signUpUser.ts → src/api/auth.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,14 @@
import { User } from "@/types";
import { axios_ as axios } from "@/utils/axios";

import { axios_ as axios } from "./axios";
export const loginUser = async (userData: User) => {
try {
const { data } = await axios.post<User>("/auth/login", userData);
return data;
} catch (error) {
throw new Error(`Incorrect Credentials, Retry!\nError: ${error}`);
}
};

export const signUp = async (userData: User) => {
delete userData.cfg_password;
Expand Down
5 changes: 4 additions & 1 deletion src/utils/fetchMessages.ts → src/api/chat.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,11 @@
import { IMessage } from "react-native-gifted-chat";

import { Message } from "@/types";
import { axios_ } from "@/utils/axios";

import { axios_ } from "./axios";
export const chatKeys = {
community_chat: ["messages"] as const
};

export async function fetchMessages(): Promise<IMessage[]> {
try {
Expand Down
3 changes: 1 addition & 2 deletions src/utils/sendBotMessage.ts → src/api/chatbot.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,7 @@
import { IMessage } from "react-native-gifted-chat";

import { HelpBotMsg } from "@/types";

import { axios_ } from "./axios";
import { axios_ } from "@/utils/axios";

export const sendBotMessage = async (msg: IMessage[]) => {
try {
Expand Down
48 changes: 48 additions & 0 deletions src/api/sos.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
import * as Location from "expo-location";

import { SOS } from "@/types";
import { axios_ as axios } from "@/utils/axios";

export const sosKeys = {
sos: (user_id: number) => [user_id, "sos"] as const
};

export const closeSOS = async (user_id: number) => {
console.log(`Closing SOS for user_id: ${user_id}.`);
try {
await axios.patch(`/sos/close/${user_id}`);
} catch (error) {
console.error("Error closing SOS:", error);
throw new Error(`Error closing SOS: ${error}`);
}
};

export const createSOS = async ({
user_id,
location
}: {
user_id: number;
location: Location.LocationObject;
}) => {
console.log(`Creating SOS for user_id: ${user_id}. Location: ${location}`);
try {
await axios.post("/sos/create", {
user_id: user_id,
lat: location.coords.latitude,
long: location.coords.longitude
});
return;
} catch (error) {
console.error("Error creating SOS:", error);
throw new Error(`Error creating SOS: ${error}`);
}
};

export const fetchNotifications = async () => {
try {
const { data: notifications } = await axios.get<SOS[]>("/sos/");
return notifications;
} catch (error) {
throw new Error("Error fetching notifications");
}
};
63 changes: 63 additions & 0 deletions src/api/ticket.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
import { IMessage } from "react-native-gifted-chat";

import { Ticket } from "@/types";
import { TicketMsg } from "@/types";
import { axios_ as axios } from "@/utils/axios";

export const ticketKeys = {
tickets: (user_id: number) => [user_id, "tickets"] as const,
ticket_msgs: (user_id: number, ticket_id: string) =>
[...ticketKeys.tickets(user_id), ticket_id, "ticket_msgs"] as const
};

export const createTicket = async (user_id: number, ticket: Ticket) => {
delete ticket.rating;

try {
const { data } = await axios.post<Ticket>("/tickets/create/", {
...ticket,
user_id: user_id
});
return data;
} catch (error) {
throw new Error(`Error Creating ticket`);
}
};

export const fetchTickets = async (user_id: number) => {
try {
const { data: tickets } = await axios.get<Ticket[]>(`/tickets/${user_id}`);
return tickets;
} catch (error) {
throw new Error(`Error fetching tickets`);
}
};
export const closeTicket = async (ticketId: string) => {
try {
await axios.patch(`/tickets/close/${ticketId}`);
} catch (error) {
throw new Error(`Error closing ticket: ${ticketId}`);
}
};

export const fetchTicketMsgs = async (ticketId: string) => {
try {
const { data } = await axios.get<TicketMsg[]>(
`/tickets/messages/${ticketId}`
);

const messages: IMessage[] = data.map((message: TicketMsg) => ({
_id: message.message_id,
createdAt: new Date(message.created_at),
text: message.message_text,
user: {
_id: message.user_id,
name: `User ${message.user_id}`
}
}));

return messages;
} catch (error) {
throw new Error(`Error fetching ticket: ${ticketId} messages`);
}
};
2 changes: 1 addition & 1 deletion src/app/(app)/(stack)/Help.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,8 @@ import { useMutation } from "@tanstack/react-query";
import { useState } from "react";
import { IMessage } from "react-native-gifted-chat";

import { sendBotMessage } from "@/api/chatbot";
import { ChatRoom } from "@/components";
import { sendBotMessage } from "@/utils/sendBotMessage";

const Help = () => {
const [messages, setMessages] = useState<IMessage[]>([]);
Expand Down
9 changes: 7 additions & 2 deletions src/app/(app)/(stack)/Notification.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,17 +2,22 @@ import { Bell, BellOff } from "@tamagui/lucide-icons";
import { useQuery } from "@tanstack/react-query";
import { H6, ListItem, ScrollView } from "tamagui";

import { fetchNotifications, sosKeys } from "@/api/sos";
import { MyStack } from "@/components";
import { useUser } from "@/hooks/useUser";
import { SOS } from "@/types";
import { fetchNotifications } from "@/utils/fetchNotifications";

const Notifications = () => {
const { user } = useUser();
const {
data: notifications,
isLoading,
isError,
error
} = useQuery({ queryKey: ["notifications"], queryFn: fetchNotifications });
} = useQuery({
queryKey: sosKeys.sos(user?.user_id!),
queryFn: fetchNotifications
});
return (
<ScrollView bg="$backgroundStrong">
<MyStack>
Expand Down
19 changes: 15 additions & 4 deletions src/app/(app)/(stack)/Ticket/Chat.tsx
Original file line number Diff line number Diff line change
@@ -1,25 +1,36 @@
import { useQuery } from "@tanstack/react-query";
import { useLocalSearchParams } from "expo-router";
import React from "react";
import { H6 } from "tamagui";

import { fetchTicketMsgs, ticketKeys } from "@/api/ticket";
import { ChatRoom } from "@/components";
import { useWebSocket } from "@/hooks";
import { type TicketParams } from "@/types";
import { fetchTicketMsgs } from "@/utils/fetchTicketMessages";

const Chat = () => {
const { ticketId, userId } = useLocalSearchParams<TicketParams>();
const query = useQuery({
queryKey: ["ticket_msgs", ticketId],
queryKey: ticketKeys.ticket_msgs(Number(userId!), ticketId!),
queryFn: async () => await fetchTicketMsgs(ticketId!)
});

const sendMessage = useWebSocket({
queryKey: ["ticket_msgs", ticketId!],
queryKey: ticketKeys.ticket_msgs(Number(userId!), ticketId!),
url: `/${ticketId}/${userId}`
});

return <ChatRoom messages={query.data!} onSend={sendMessage} />;
return (
<>
{query.isError ? (
<H6>Error... {query.error.message}</H6>
) : query.isLoading ? (
<H6>Loading Ticket Chat...</H6>
) : (
<ChatRoom messages={query.data!} onSend={sendMessage} />
)}
</>
);
};

export default Chat;
8 changes: 6 additions & 2 deletions src/app/(app)/(stack)/Ticket/_layout.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,21 +2,25 @@ import { Trash } from "@tamagui/lucide-icons";
import { useMutation, useQueryClient } from "@tanstack/react-query";
import { Stack } from "expo-router";

import { closeTicket, ticketKeys } from "@/api/ticket";
import { MyHeader, PopupMenuItem } from "@/components";
import { useUser } from "@/hooks/useUser";
import { TicketParams } from "@/types";
import { closeTicket } from "@/utils/closeTicket";

interface RouteProps {
name: string;
params: TicketParams;
}

const TicketLayout = () => {
const { user } = useUser();
const queryClient = useQueryClient();
const closeTicketQuery = useMutation({
mutationFn: closeTicket,
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ["tickets"] });
queryClient.invalidateQueries({
queryKey: ticketKeys.tickets(user?.user_id!)
});
}
});

Expand Down
4 changes: 2 additions & 2 deletions src/app/(app)/(stack)/Ticket/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,10 @@ import { Link, router } from "expo-router";
import React from "react";
import { Button, H6, ListItem, ScrollView } from "tamagui";

import { fetchTickets, ticketKeys } from "@/api/ticket";
import { MyStack } from "@/components";
import { useUser } from "@/hooks/useUser";
import { TicketParams } from "@/types";
import { fetchTickets } from "@/utils/fetchTickets";

const TicketList = () => {
const { user } = useUser();
Expand All @@ -17,7 +17,7 @@ const TicketList = () => {
isError,
error
} = useQuery({
queryKey: ["tickets"],
queryKey: ticketKeys.tickets(user?.user_id!),
queryFn: async () => await fetchTickets(user!.user_id!)
});

Expand Down
9 changes: 6 additions & 3 deletions src/app/(app)/(tabs)/Chat.tsx
Original file line number Diff line number Diff line change
@@ -1,17 +1,20 @@
import { useQuery } from "@tanstack/react-query";
import { H6 } from "tamagui";

import { chatKeys, fetchMessages } from "@/api/chat";
import { ChatRoom } from "@/components";
import { useWebSocket } from "@/hooks";
import { useUser } from "@/hooks/useUser";
import { fetchMessages } from "@/utils/fetchMessages";

const Chat = () => {
const query = useQuery({ queryKey: ["messages"], queryFn: fetchMessages });
const query = useQuery({
queryKey: chatKeys.community_chat,
queryFn: fetchMessages
});
const { user } = useUser();

const sendMessage = useWebSocket({
queryKey: ["messages"],
queryKey: chatKeys.community_chat,
url: `/community_chat/${user?.user_id}`
});

Expand Down
4 changes: 2 additions & 2 deletions src/app/(app)/(tabs)/Heatmap.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,11 @@ import { useQuery } from "@tanstack/react-query";
import { Heatmap } from "react-native-maps";
import { H2, H6, Sheet, Text } from "tamagui";

import { areasKeys, fetchAreas } from "@/api/areas";
import { MapWrapper, MyStack } from "@/components";
import { fetchAreas } from "@/utils/fetchAreas";

const MyHeatmap = () => {
const query = useQuery({ queryKey: ["heatMap"], queryFn: fetchAreas });
const query = useQuery({ queryKey: areasKeys.heatmap, queryFn: fetchAreas });

return (
<>
Expand Down
2 changes: 1 addition & 1 deletion src/components/Form/Login.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,8 @@ import { router } from "expo-router";
import React, { Dispatch, FC, SetStateAction } from "react";
import { Button, Form, H2, XStack, YStack } from "tamagui";

import { loginUser } from "@/api/auth";
import { useUser } from "@/hooks/useUser";
import { loginUser } from "@/utils/loginUser";

import MySheet from "../common/MySheet";

Expand Down
2 changes: 1 addition & 1 deletion src/components/Form/Signup.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,9 @@ import { router } from "expo-router";
import React, { Dispatch, FC, SetStateAction } from "react";
import { Button, Form, H2, XStack, YStack } from "tamagui";

import { signUp } from "@/api/auth";
import { useUser } from "@/hooks/useUser";
import { User } from "@/types";
import { signUp } from "@/utils/signUpUser";

import MySheet from "../common/MySheet";

Expand Down
16 changes: 11 additions & 5 deletions src/hooks/useSos.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,9 @@
import { useMutation } from "@tanstack/react-query";
import { useMutation, useQueryClient } from "@tanstack/react-query";
import * as Location from "expo-location";
import { useEffect, useState } from "react";

import { closeSOS, createSOS, sosKeys } from "@/api/sos";
import { useUser } from "@/hooks/useUser";
import { closeSOS } from "@/utils/closeSOS";
import { createSOS } from "@/utils/createSOS";

interface SOSHook {
location: Location.LocationObject | null;
Expand All @@ -19,11 +18,18 @@ export const useSOS = (): SOSHook => {
const [isSosOn, setIsSosOn] = useState<boolean>(false);
const { user } = useUser();

const queryClient = useQueryClient();
const { mutate: createSOSMutation, isError: creationError } = useMutation({
mutationFn: createSOS
mutationFn: createSOS,
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: sosKeys.sos(user?.user_id!) });
}
});
const { mutate: closeSOSMutation, isError: closingError } = useMutation({
mutationFn: closeSOS
mutationFn: closeSOS,
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: sosKeys.sos(user?.user_id!) });
}
});

useEffect(() => {
Expand Down
Loading

0 comments on commit fe9cc0d

Please sign in to comment.