Add push notif support

This commit is contained in:
Gabriel Brown 2024-09-12 17:36:58 -05:00
parent c8cb5d16d1
commit 03fc9c9c1e
5 changed files with 91 additions and 2 deletions

View File

@ -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",

View File

@ -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

View File

@ -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 });
}
};

View File

@ -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(),

View File

@ -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);
}
};