forked from Priyanshu-byte-coder/devtrack
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathroute.ts
More file actions
212 lines (177 loc) · 6.21 KB
/
Copy pathroute.ts
File metadata and controls
212 lines (177 loc) · 6.21 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
import { getServerSession } from "next-auth";
import { authOptions } from "@/lib/auth";
import { supabaseAdmin } from "@/lib/supabase";
import { resolveAppUser } from "@/lib/resolve-user";
import { dispatchToAllWebhooks } from "@/lib/webhooks";
import { stripHtml } from "@/lib/sanitize";
export const dynamic = "force-dynamic";
interface Goal {
id: string;
user_id: string;
title: string;
target: number;
current: number;
unit: string;
recurrence: string;
deadline: string | null;
period_start: string | null;
created_at: string;
}
type Recurrence = "none" | "weekly" | "monthly";
const VALID_RECURRENCES = ["none", "weekly", "monthly"] as const;
const MAX_TITLE_LEN = 100;
const MAX_UNIT_LEN = 30;
const MIN_TARGET = 1;
const MAX_TARGET = 10_000;
// Hard cap to prevent storage exhaustion and catastrophic Promise.all execution
const MAX_GOALS_PER_USER = 5;
function getPeriodStart(recurrence: Recurrence): string {
const now = new Date();
if (recurrence === "weekly") {
const day = now.getUTCDay();
const diff = day === 0 ? -6 : 1 - day; // Monday
const monday = new Date(now);
monday.setUTCDate(now.getUTCDate() + diff);
monday.setUTCHours(0, 0, 0, 0);
return monday.toISOString();
}
if (recurrence === "monthly") {
return new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), 1)).toISOString();
}
return new Date(0).toISOString(); // 'none' never resets
}
export async function GET() {
const session = await getServerSession(authOptions);
if (!session?.githubId) {
return Response.json({ error: "Unauthorized" }, { status: 401 });
}
const user = await resolveAppUser(session.githubId, session.githubLogin);
if (!user) return Response.json({ error: "User not found" }, { status: 404 });
// Added .limit() to bound the database payload and the subsequent Promise.all loop
const { data: goals, error } = await supabaseAdmin
.from("goals")
.select("*")
.eq("user_id", user.id)
.order("created_at", { ascending: false })
.limit(MAX_GOALS_PER_USER);
if (error) {
console.error("Failed to fetch goals:", error);
return Response.json({ error: "Failed to fetch goals" }, { status: 500 });
}
// Reset progress if we're in a new period
const processedGoals = await Promise.all(
(goals ?? []).map(async (goal: Goal) => {
if (goal.recurrence === "none") return goal;
const periodStart = new Date(getPeriodStart(goal.recurrence as Recurrence));
const storedPeriodStart = goal.period_start
? new Date(goal.period_start)
: new Date(0);
if (storedPeriodStart < periodStart) {
const { data: updated } = await supabaseAdmin
.from("goals")
.update({ current: 0, period_start: periodStart.toISOString() })
.eq("id", goal.id)
.lt("period_start", periodStart.toISOString())
.select()
.single();
if (updated) return updated;
const { data: current } = await supabaseAdmin
.from("goals")
.select("*")
.eq("id", goal.id)
.single();
return current ?? goal;
}
return goal;
})
);
return Response.json({ goals: processedGoals });
}
export async function POST(req: Request) {
const session = await getServerSession(authOptions);
if (!session?.githubId) {
return Response.json({ error: "Unauthorized" }, { status: 401 });
}
let body: unknown;
try {
body = await req.json();
} catch (e) {
return Response.json({ error: "Invalid JSON" }, { status: 400 });
}
if (typeof body !== "object" || body === null) {
return Response.json({ error: "Invalid request body" }, { status: 400 });
}
const { title, target, unit, recurrence, deadline } = body as Record<string, unknown>;
if (typeof title !== "string" || title.trim().length === 0) {
return Response.json({ error: "title must be a non-empty string" }, { status: 400 });
}
const sanitizedTitle = stripHtml(title);
if (sanitizedTitle.length === 0) {
return Response.json({ error: "title must not be empty" }, { status: 400 });
}
if (sanitizedTitle.length > MAX_TITLE_LEN) {
return Response.json({ error: `title must be ${MAX_TITLE_LEN} characters or fewer` }, { status: 400 });
}
if (
typeof target !== "number" ||
!Number.isInteger(target) ||
target < MIN_TARGET ||
target > MAX_TARGET
) {
return Response.json(
{ error: `target must be an integer between ${MIN_TARGET} and ${MAX_TARGET}` },
{ status: 400 }
);
}
const safeUnit = typeof unit === "string" ? unit.slice(0, MAX_UNIT_LEN) : "commits";
const safeRecurrence: Recurrence = VALID_RECURRENCES.includes(recurrence as Recurrence)
? (recurrence as Recurrence)
: "none";
let safeDeadline: string | null = null;
if (typeof deadline === "string") {
const d = new Date(deadline);
if (!isNaN(d.getTime())) {
d.setUTCHours(23, 59, 59, 999);
safeDeadline = d.toISOString();
}
}
const user = await resolveAppUser(session.githubId, session.githubLogin);
if (!user) return Response.json({ error: "User not found" }, { status: 404 });
// Pre-check count query using head option for peak performance
const { count, error: countError } = await supabaseAdmin
.from("goals")
.select("*", { count: "exact", head: true })
.eq("user_id", user.id);
if (countError) {
return Response.json({ error: "Failed to verify goal limits" }, { status: 500 });
}
if ((count ?? 0) >= MAX_GOALS_PER_USER) {
return Response.json(
{ error: `You can have at most ${MAX_GOALS_PER_USER} goals.` },
{ status: 400 }
);
}
const { data: goal, error } = await supabaseAdmin
.from("goals")
.insert({
user_id: user.id,
title: sanitizedTitle,
target,
unit: safeUnit,
recurrence: safeRecurrence,
period_start: getPeriodStart(safeRecurrence),
deadline: safeDeadline,
current: 0,
})
.select()
.single();
if (error) return Response.json({ error: error.message }, { status: 500 });
dispatchToAllWebhooks(user.id, "goal.created", {
goalId: goal.id,
title: goal.title,
target: goal.target,
unit: goal.unit,
recurrence: goal.recurrence,
}).catch(() => {});
return Response.json({ goal }, { status: 201 });
}