mirror of
https://github.com/neynarxyz/create-farcaster-mini-app.git
synced 2025-12-09 19:02:34 -05:00
Add notification savings + webhook validation
This commit is contained in:
committed by
lucas-neynar
parent
af451b12a1
commit
8acf07b03e
65
src/lib/notifs.ts
Normal file
65
src/lib/notifs.ts
Normal file
@@ -0,0 +1,65 @@
|
||||
import {
|
||||
SendNotificationRequest,
|
||||
sendNotificationResponseSchema,
|
||||
} from "@farcaster/frame-sdk";
|
||||
import { getUserNotificationDetails } from "~/lib/kv";
|
||||
|
||||
const appUrl = process.env.NEXT_PUBLIC_URL || "";
|
||||
|
||||
type SendFrameNotificationResult =
|
||||
| {
|
||||
state: "error";
|
||||
error: unknown;
|
||||
}
|
||||
| { state: "no_token" }
|
||||
| { state: "rate_limit" }
|
||||
| { state: "success" };
|
||||
|
||||
export async function sendFrameNotification({
|
||||
fid,
|
||||
title,
|
||||
body,
|
||||
}: {
|
||||
fid: number;
|
||||
title: string;
|
||||
body: string;
|
||||
}): Promise<SendFrameNotificationResult> {
|
||||
const notificationDetails = await getUserNotificationDetails(fid);
|
||||
if (!notificationDetails) {
|
||||
return { state: "no_token" };
|
||||
}
|
||||
|
||||
const response = await fetch(notificationDetails.url, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify({
|
||||
notificationId: crypto.randomUUID(),
|
||||
title,
|
||||
body,
|
||||
targetUrl: appUrl,
|
||||
tokens: [notificationDetails.token],
|
||||
} satisfies SendNotificationRequest),
|
||||
});
|
||||
|
||||
const responseJson = await response.json();
|
||||
|
||||
if (response.status === 200) {
|
||||
const responseBody = sendNotificationResponseSchema.safeParse(responseJson);
|
||||
if (responseBody.success === false) {
|
||||
// Malformed response
|
||||
return { state: "error", error: responseBody.error.errors };
|
||||
}
|
||||
|
||||
if (responseBody.data.result.rateLimitedTokens.length) {
|
||||
// Rate limited
|
||||
return { state: "rate_limit" };
|
||||
}
|
||||
|
||||
return { state: "success" };
|
||||
} else {
|
||||
// Error response
|
||||
return { state: "error", error: responseJson };
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user