-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathnotification.ts
More file actions
227 lines (201 loc) · 7.37 KB
/
Copy pathnotification.ts
File metadata and controls
227 lines (201 loc) · 7.37 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
import { onTaskDispatched } from "firebase-functions/v2/tasks";
import * as admin from "firebase-admin";
import * as logger from "firebase-functions/logger";
import { resolveTimeZone } from "./shared";
type TaskPayload = {
userId: string;
todoId: string;
todoKind: string;
dueDateKey: string;
title: string;
body: string;
};
type FirestoreErrorLike = {
code?: unknown;
};
// Cloud Tasks에 의해 트리거되는 함수
export const sendPushNotification = onTaskDispatched({
region: "asia-northeast3",
retryConfig: { maxAttempts: 3, minBackoffSeconds: 5 },
rateLimits: { maxDispatchesPerSecond: 200 },
},
async (req) => {
const taskId = req.data?.taskId;
if (!isValidTaskId(taskId)) {
logger.warn("유효하지 않은 푸시 알림 payload", req.data);
return;
}
const taskDocRef = admin.firestore().collection("notificationTasks").doc(taskId);
try {
const taskDoc = await taskDocRef.get();
if (!taskDoc.exists) {
logger.warn("notificationTask 문서를 찾을 수 없습니다.", { taskId });
return;
}
const parsed = parseTaskPayload(taskDoc.data());
if (!parsed) {
logger.warn("notificationTask 문서 형식이 올바르지 않습니다.", { taskId });
return;
}
const { userId, todoId, todoKind, dueDateKey, title, body } = parsed;
const settingsDocRef = admin.firestore().doc(`users/${userId}/userData/settings`);
const todoDocRef = admin.firestore().doc(`users/${userId}/todoLists/${todoId}`);
const [settingsDoc, todoDoc] = await Promise.all([
settingsDocRef.get(),
todoDocRef.get()
]);
const settingsData = settingsDoc.data();
const allowPushNotification = settingsData?.allowPushNotification ?? true;
if (!allowPushNotification) { return; }
const todoData = todoDoc.data();
if (!todoDoc.exists || !todoData || todoData.isCompleted === true) { return; }
const timeZone = resolveTimeZone(settingsData);
const dueDateValue = todoData.dueDate;
const currentDueDate = dueDateValue instanceof admin.firestore.Timestamp ?
dueDateValue.toDate() :
dueDateValue instanceof Date ?
dueDateValue :
null;
if (!currentDueDate) { return; }
if (formatDateKey(currentDueDate, timeZone) !== dueDateKey) { return; }
const id = `${todoId}_${dueDateKey}`;
const receiptDocRef = admin.firestore().doc(
`users/${userId}/notificationReceipts/${id}`
);
const notificationDocRef = admin.firestore().doc(`users/${userId}/notifications/${id}`);
try {
await receiptDocRef.create({
todoId,
dueDateKey,
createdAt: admin.firestore.FieldValue.serverTimestamp()
});
} catch (error) {
if (isAlreadyExistsError(error)) {
return;
}
throw error;
}
const notificationData = {
title: "Todo 알림",
body,
receivedAt: admin.firestore.FieldValue.serverTimestamp(),
isRead: false,
todoId: todoId,
todoKind: todoKind
};
await notificationDocRef.set(notificationData, { merge: true });
// 1. 사용자 FCM 토큰과 읽지 않은 알림 수 가져오기
const unreadCountPromise = admin.firestore()
.collection(`users/${userId}/notifications`)
.where("isRead", "==", false)
.count()
.get();
const tokenDocPromise = admin.firestore().doc(`users/${userId}/userData/tokens`).get();
const [tokenDoc, unreadCountSnapshot] = await Promise.all([
tokenDocPromise,
unreadCountPromise
]);
const fcmToken = tokenDoc.data()?.fcmToken;
const unreadNotificationCount = unreadCountSnapshot.data().count;
if (!fcmToken) {
logger.warn(`사용자 ${userId}의 fcmToken이 없어 푸시 발송은 건너뜁니다. Firestore에는 기록했습니다.`);
return;
}
// 2. 푸시 알림 발송
const message = {
notification: { title, body },
data: {
todoId: todoId,
todoKind: todoKind
},
apns: {
payload: {
aps: {
sound: "default",
badge: unreadNotificationCount
}
}
},
token: fcmToken,
};
try {
await admin.messaging().send(message);
} catch (sendError) {
logger.warn(`[${userId}] 푸시 발송 실패. Firestore 기록은 유지됩니다.`, sendError);
return;
}
} catch (error) {
logger.error("알림 발송 중 오류 발생", {
taskId,
error
});
} finally {
try {
await taskDocRef.delete();
} catch (cleanupError) {
logger.warn("notificationTask 정리 실패", {
taskId,
cleanupError
});
}
}
}
);
function isValidTaskId(value: unknown): value is string {
return typeof value === "string" && /^[A-Za-z0-9_-]{1,128}$/.test(value);
}
function parseTaskPayload(data: FirebaseFirestore.DocumentData | undefined): TaskPayload | null {
const {
userId,
todoId,
todoKind,
dueDateKey,
title,
body
} = data ?? {};
if (
typeof userId !== "string" ||
typeof todoId !== "string" ||
typeof todoKind !== "string" ||
typeof dueDateKey !== "string" ||
typeof title !== "string" ||
typeof body !== "string"
) {
return null;
}
if (userId.includes("/") || todoId.includes("/")) {
return null;
}
return {
userId,
todoId,
todoKind,
dueDateKey,
title,
body
};
}
function isAlreadyExistsError(error: unknown): boolean {
const code = (error as FirestoreErrorLike)?.code;
return code === 6 || code === "6" || code === "already-exists";
}
function formatDateKey(date: Date, timeZone: string): string {
const parts = new Intl.DateTimeFormat("en-US", {
timeZone,
year: "numeric",
month: "2-digit",
day: "2-digit"
}).formatToParts(date);
const partMap = new Map(parts.map(p => [p.type, p.value]));
const year = partMap.get("year");
const month = partMap.get("month");
const day = partMap.get("day");
if (!year || !month || !day) {
logger.warn("formatDateKey 파트 추출 실패", {
date: date.toISOString(),
timeZone,
parts
});
}
return `${year ?? "1970"}-${month ?? "01"}-${day ?? "01"}`;
}