From 03fc9c9c1ebcc3bd0df5915e75fd581e017610e4 Mon Sep 17 00:00:00 2001 From: gibbyb Date: Thu, 12 Sep 2024 17:36:58 -0500 Subject: [PATCH] Add push notif support --- package.json | 2 +- src/app/api/setCountdown/route.ts | 2 +- src/app/api/updatePushToken/route.ts | 27 ++++++++++++ src/server/db/schema.ts | 1 + src/server/functions.ts | 61 ++++++++++++++++++++++++++++ 5 files changed, 91 insertions(+), 2 deletions(-) create mode 100644 src/app/api/updatePushToken/route.ts diff --git a/package.json b/package.json index 6533f98..5562344 100755 --- a/package.json +++ b/package.json @@ -12,7 +12,7 @@ "dev": "next dev", "lint": "next lint", "start": "next start", - "go": "git pull && next build && next start" + "go": "next build && next start" }, "dependencies": { "@t3-oss/env-nextjs": "^0.10.1", diff --git a/src/app/api/setCountdown/route.ts b/src/app/api/setCountdown/route.ts index 8767dc6..d82bcd0 100755 --- a/src/app/api/setCountdown/route.ts +++ b/src/app/api/setCountdown/route.ts @@ -20,4 +20,4 @@ export const POST = async (request: NextRequest) => { return NextResponse.json({ message: "Error" }, { status: 500 }); } }; -// localhost:3000/api/setCountdown?apiKey=I_Love_Madeline&countdown=2023-01-01T00:00:00.000Z +// localhost:3000/api/setCountdown?apiKey=I_Love_Madeline&countdown=2024-09-20T12:00:00.000Z diff --git a/src/app/api/updatePushToken/route.ts b/src/app/api/updatePushToken/route.ts new file mode 100644 index 0000000..7cdcf31 --- /dev/null +++ b/src/app/api/updatePushToken/route.ts @@ -0,0 +1,27 @@ +import { NextResponse } from 'next/server'; +import { updateUserPushToken } from '~/server/functions'; + +type Data = { + apiKey: string; + userId: string; + pushToken: string; +}; + +export const POST = async (request: Request) => { + try { + const { apiKey, userId, pushToken } = await request.json() as Data; + + // Validate API key (optional, but since you do it, let's continue) + if (apiKey !== process.env.API_KEY) { + return NextResponse.json({ message: "Invalid API Key" }, { status: 401 }); + } + + // Update push token in the database + await updateUserPushToken(parseInt(userId), pushToken); + + return NextResponse.json({ message: "Push token updated successfully" }); + } catch (error) { + console.error(error); + return NextResponse.json({ message: "Error updating push token" }, { status: 500 }); + } +}; diff --git a/src/server/db/schema.ts b/src/server/db/schema.ts index 3058c06..853a4d1 100755 --- a/src/server/db/schema.ts +++ b/src/server/db/schema.ts @@ -14,6 +14,7 @@ export const users = createTable( id: serial("id").primaryKey(), name: varchar("name", { length: 256 }), message: varchar("message", { length: 256 }), + pushToken: varchar("push_token", { length: 256 }), createdAt: timestamp("created_at", { withTimezone: true }) .default(sql`CURRENT_TIMESTAMP`) .notNull(), diff --git a/src/server/functions.ts b/src/server/functions.ts index d0d8dc7..40a265e 100755 --- a/src/server/functions.ts +++ b/src/server/functions.ts @@ -17,6 +17,22 @@ export const getUsers = async () => { } }; +export const getUser = async (userId: number) => { + try { + const result = await db.select({ + id: schema.users.id, + name: schema.users.name, + message: schema.users.message, + pushToken: schema.users.pushToken, + }).from(schema.users) + .where(eq(schema.users.id, userId)); + return result; + } catch (error) { + console.error("Error fetching user", error); + throw new Error("Failed to fetch user"); + } +}; + export const getMessage = async (userId: number) => { try { let message = 1; @@ -38,6 +54,14 @@ export const setMessage = async (userId: number, message: string) => { await db.update(schema.users) .set({ message: message }) .where(eq(schema.users.id, userId)); + const otherUserId = userId === 1 ? 2 : 1; + const otherUser = await getUser(otherUserId); + + if (otherUser?.[0]?.pushToken) { + await sendPushNotification(otherUser[0].pushToken, message); + } else { + console.log(`Other user with id ${otherUserId} does not have a push token`); + } } catch (error) { console.error("Error setting message", error); throw new Error("Failed to set message"); @@ -67,3 +91,40 @@ export const setCountdown = async (date: Date) => { throw new Error("Failed to set countdown"); } }; + +export const updateUserPushToken = async (userId: number, pushToken: string) => { + try { + await db.update(schema.users) + .set({ pushToken: pushToken }) + .where(eq(schema.users.id, userId)); + console.log(`Push token updated for userId ${userId}`); + } catch (error) { + console.error("Error updating push token", error); + throw new Error("Failed to update push token"); + } +}; + +export const sendPushNotification = async (expoPushToken: string, message: string) => { + const notificationMessage = { + to: expoPushToken, + sound: 'default', + title: 'New message!', + body: message, + data: { message }, // Extra data you might want to send + }; + + try { + await fetch('https://exp.host/--/api/v2/push/send', { + method: 'POST', + headers: { + Accept: 'application/json', + 'Accept-Encoding': 'gzip, deflate', + 'Content-Type': 'application/json', + }, + body: JSON.stringify(notificationMessage), + }); + console.log('Push notification sent successfully'); + } catch (error) { + console.error('Error sending push notification', error); + } +};