Skip to content

Commit

Permalink
tasksのリクエストを変更
Browse files Browse the repository at this point in the history
  • Loading branch information
MurakawaTakuya committed Jan 9, 2025
1 parent 0ae2731 commit 3db72ef
Show file tree
Hide file tree
Showing 5 changed files with 3,563 additions and 172 deletions.
7 changes: 6 additions & 1 deletion functions/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,12 @@ const verifyAppCheckToken = async (
// Postmanを使うためにCloud FunctionsのApp Checkは開発環境では使用しない
if (process.env.NODE_ENV === "production") {
app.use((req, res, next) => {
verifyAppCheckToken(req, res, next);
if (req.headers.token === process.env.NOTIFICATION_KEY) {
// tasksからの/notificationの場合はスキップ
next();
} else {
verifyAppCheckToken(req, res, next);
}
});
}

Expand Down
18 changes: 14 additions & 4 deletions functions/src/routers/notificationRouter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,14 @@ const db = admin.firestore();

// POST: 通知を送信
router.post("/", async (req: Request, res: Response) => {
const token = req.headers.token;
if (!token) {
return res.status(401).json({ message: "Unauthorized" });
}
if (token !== process.env.NOTIFICATION_KEY) {
return res.status(401).json({ message: "Unauthorized" });
}

let goalId: string;
let marginTime: number;

Expand Down Expand Up @@ -69,7 +77,12 @@ router.post("/", async (req: Request, res: Response) => {
"Content-Type": "application/json",
Authorization: `Bearer ${accessToken}`,
};
logger.info("Sending notification:", goalData.text);
logger.info("Sending notification:", {
goalId: goalId,
userId: goalData.userId,
text: goalData.text,
fcmToken: userData.fcmToken,
});

// 通知を送信
const response = await fetch(url, {
Expand Down Expand Up @@ -99,6 +112,3 @@ router.post("/", async (req: Request, res: Response) => {
});

export default router;

// logger
// auth
43 changes: 6 additions & 37 deletions functions/src/tasks.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,10 @@
import { CloudTasksClient } from "@google-cloud/tasks";
import * as admin from "firebase-admin";
import { Buffer } from "buffer";
import { logger } from "firebase-functions";
import {
onDocumentCreated,
onDocumentDeleted,
} from "firebase-functions/v2/firestore";
import { GoogleAuth } from "google-auth-library";

const tasksClient = new CloudTasksClient();
const projectId = process.env.GCP_PROJECT_ID;
Expand Down Expand Up @@ -38,33 +37,23 @@ export const createTasksOnGoalCreate = onDocumentCreated(
goalData.deadline.toDate().getTime() - marginTime * 60 * 1000
);
const goalId = event.params.goalId;
const fcmToken = await getUserFcmToken(goalData.userId);
const postData = {
message: {
token: fcmToken, // 通知を受信する端末のトークン
data: {
title: `${marginTime}分以内に目標を完了し写真をアップロードしましょう!`,
body: goalData.text,
icon: "https://todo-real-c28fa.web.app/appIcon.svg",
},
},
goalId,
marginTime,
};
const queuePath = tasksClient.queuePath(projectId, region, queue);
const auth = new GoogleAuth({
scopes: ["https://www.googleapis.com/auth/cloud-platform"],
});
const accessToken = await auth.getAccessToken();
const accessToken = process.env.NOTIFICATION_KEY;

await tasksClient.createTask({
parent: queuePath,
task: {
name: `${queuePath}/tasks/${goalId}`, // タスクの名前をgoalIdに設定
httpRequest: {
httpMethod: "POST",
url: `https://fcm.googleapis.com//v1/projects/${projectId}/messages:send`,
url: "https://firestore-okdtj725ta-an.a.run.app/notification",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${accessToken}`,
token: `${accessToken}`,
},
body: Buffer.from(JSON.stringify(postData)).toString("base64"),
},
Expand Down Expand Up @@ -138,23 +127,3 @@ export const deleteTasksOnPostCreate = onDocumentCreated(
}
}
);

const getUserFcmToken = async (userId: string) => {
const userData = await admin
.firestore()
.collection("user")
.doc(userId)
.get()
.then((doc) => doc.data());

if (!userData) {
throw new Error(`No user data found for userId:, ${userId}`);
}
if (!userData.fcmToken) {
throw new Error(`No FCM token found for userId:, ${userId}`);
}
if (userData.fcmToken === "") {
throw new Error(`FCM token is not stored for userId:, ${userId}`);
}
return userData.fcmToken;
};
Loading

0 comments on commit 3db72ef

Please sign in to comment.