-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathroutes.ts
More file actions
1124 lines (990 loc) · 43.4 KB
/
routes.ts
File metadata and controls
1124 lines (990 loc) · 43.4 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
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// server/routes.ts - FIXED VERSION WITH DEBUG COLLECTION POST
import type { Express, Request, Response, NextFunction, RequestHandler } from "express";
import { createServer, type Server } from "http";
import admin from "firebase-admin";
import type { DecodedIdToken } from "firebase-admin/auth";
import { pool } from "./db";
import { storage } from "./storage";
import { simpleStorage } from "./simple-storage";
import logger from "./logger";
import {
insertSnippetSchema,
insertCollectionSchema,
insertCollectionItemSchema,
insertCommentSchema,
insertUserSchema
} from "@shared/schema";
import { z } from "zod";
/** ─── 1) Debug DB connection on startup ───────────────────────────────── */
;(async () => {
try {
const client = await pool.connect();
logger.info(`✅ DATABASE CONNECTION TEST: OK — ${(await client.query("SELECT NOW()")).rows[0].now}`);
client.release();
} catch (e) {
logger.error("❌ DATABASE CONNECTION TEST: FAILED", e);
}
})();
/** ─── 2) Auth middleware (verifies Firebase ID Token in Authorization header) ── */
export const authMiddleware: RequestHandler = async (req, res, next) => {
try {
const authHeader = req.headers.authorization;
if (!authHeader?.startsWith("Bearer ")) {
return res.status(401).json({ message: "Unauthorized: No token" });
}
const idToken = authHeader.split(" ")[1];
const decoded = await admin.auth().verifyIdToken(idToken);
const user = await storage.getUser(decoded.uid);
if (!user) {
return res.status(404).json({ message: "User not found" });
}
;(req as any).user = user;
next();
} catch (err: any) {
console.error("Auth middleware error:", err);
res.status(401).json({ message: "Unauthorized: Invalid token", error: err.message });
}
};
/** ─── 3) Register all routes ─────────────────────────────────────────────── */
export async function registerRoutes(app: Express): Promise<Server> {
// ─── 3.0) Health Check Endpoint ──────────────────────────────────
app.get("/api/health", async (req: Request, res: Response) => {
try {
// Test database connection
const client = await pool.connect();
const dbResult = await client.query("SELECT NOW() as current_time");
client.release();
res.json({
status: "healthy",
timestamp: new Date().toISOString(),
database: "connected",
dbTime: dbResult.rows[0].current_time,
server: "running"
});
} catch (error: any) {
console.error("Health check failed:", error);
res.status(503).json({
status: "unhealthy",
timestamp: new Date().toISOString(),
database: "disconnected",
error: error.message,
server: "running"
});
}
});
// ─── 3.1) Firebase Auth endpoints ──────────────────────────────────
app.post("/api/auth/user", async (req: Request, res: Response) => {
const { idToken, uid, email, displayName, photoURL } = req.body as any;
if (!idToken && !uid) {
return res
.status(400)
.json({ message: "Missing idToken or uid in request body" });
}
try {
let userRecord: {
id: string;
email: string | null;
displayName: string | null;
photoURL: string | null;
};
if (idToken) {
const decoded = await admin.auth().verifyIdToken(idToken);
userRecord = {
id: decoded.uid,
email: decoded.email ?? null,
displayName: decoded.name ?? null,
photoURL: decoded.picture ?? null,
};
} else {
userRecord = {
id: uid,
email: email ?? null,
displayName: displayName ?? null,
photoURL: photoURL ?? null,
};
}
const user = await storage.upsertUser(userRecord);
return res.status(201).json(user);
} catch (err: any) {
console.error("/api/auth/user error:", err);
return res.status(500).json({
message: "Auth + upsert failed",
error: err.message,
});
}
});
app.get("/api/auth/me", authMiddleware, (_req, res) => {
res.json(( _req as any ).user);
});
// ────────────────────────────────────────────────────────────────
// ─── 3.2) Snippets endpoints ─────────────────────────────────────
// ────────────────────────────────────────────────────────────────
// GET all snippets (requires authentication)
app.get("/api/snippets", authMiddleware, async (req, res) => {
try {
console.log("[GET_ALL] Get all snippets request received");
const userId = (req as any).user.id;
const filters: any = { userId }; // Add userId to filters
if (req.query.search) filters.search = String(req.query.search);
if (req.query.language) filters.language = req.query.language;
if (req.query.tag) filters.tag = req.query.tag;
if (req.query.favorites === "true") filters.favorites = true;
try {
// Assuming simpleStorage.getSnippets is updated or we prioritize storage
const list = await simpleStorage.getSnippets(filters);
console.log(`[GET_ALL] Found ${list.length} snippets using simpleStorage`);
return res.json(list);
} catch (simpleError) {
console.log("[GET_ALL] SimpleStorage failed, falling back to storage", simpleError);
try {
const list = await storage.getSnippets(filters);
console.log(`[GET_ALL] Found ${list.length} snippets using storage`);
return res.json(list);
} catch (storageError) {
console.error("[GET_ALL] Storage also failed:", storageError);
const client = await pool.connect();
try {
let query = `
SELECT id, title, code, language, description, tags, userid, createdat, updatedat,
isfavorite, ispublic, shareid, viewcount
FROM snippets
WHERE userid = $1
`;
const params: any[] = [userId];
if (filters.search) {
query += ` AND (title ILIKE $${params.length + 1} OR description ILIKE $${params.length + 1})`;
params.push(`%${filters.search}%`);
}
if (filters.language) {
query += ` AND language = $${params.length + 1}`;
params.push(filters.language);
}
if (filters.tag) {
query += ` AND $${params.length + 1} = ANY(tags)`;
params.push(filters.tag);
}
if (filters.favorites) {
query += ` AND isfavorite = true`;
}
query += ` ORDER BY updatedat DESC`;
const result = await client.query(query, params);
console.log(`[GET_ALL] Found ${result.rows.length} snippets directly from DB`);
const snippets = result.rows.map(row => ({
id: row.id,
title: row.title,
code: row.code,
language: row.language,
description: row.description,
tags: row.tags || [],
userId: row.userid,
createdAt: row.createdat,
updatedAt: row.updatedat,
isFavorite: row.isfavorite,
isPublic: row.ispublic,
shareId: row.shareid,
viewCount: row.viewcount
}));
return res.json(snippets);
} catch (dbError) {
console.error("[GET_ALL] Database error:", dbError);
throw dbError;
} finally {
client.release();
}
}
}
} catch (err: any) {
console.error("[GET_ALL] GET /api/snippets error:", err);
res.status(500).json({
message: "Failed to get snippets",
error: err.message
});
}
});
// GET single snippet by ID (public access)
app.get("/api/snippets/:id", async (req, res) => {
try {
console.log(`[GET_ONE] Get snippet request received for ID: ${req.params.id}`);
const id = Number(req.params.id);
try {
const snippet = await simpleStorage.getSnippet(id);
console.log(`[GET_ONE] Found snippet with ID: ${id} using simpleStorage`);
await storage.incrementSnippetViewCount(id);
return res.json(snippet);
} catch (simpleError) {
console.log("[GET_ONE] SimpleStorage failed, trying storage", simpleError);
try {
const snippet = await storage.getSnippet(id);
if (!snippet) {
console.log(`[GET_ONE] Snippet not found with ID: ${id}`);
return res.status(404).json({ message: "Snippet not found" });
}
console.log(`[GET_ONE] Found snippet with ID: ${id} using storage`);
await storage.incrementSnippetViewCount(id);
return res.json(snippet);
} catch (storageError) {
console.error("[GET_ONE] Storage also failed:", storageError);
const client = await pool.connect();
try {
const result = await client.query(
`SELECT id, title, code, language, description, tags, userid, createdat, updatedat,
isfavorite, ispublic, shareid, viewcount
FROM snippets
WHERE id = $1`,
[id]
);
if (result.rows.length === 0) {
console.log(`[GET_ONE] Snippet not found with ID: ${id}`);
return res.status(404).json({ message: "Snippet not found" });
}
const row = result.rows[0];
console.log(`[GET_ONE] Found snippet with ID: ${row.id} directly from DB`);
const snippet = {
id: row.id,
title: row.title,
code: row.code,
language: row.language,
description: row.description,
tags: row.tags || [],
userId: row.userid,
createdAt: row.createdat,
updatedAt: row.updatedat,
isFavorite: row.isfavorite,
isPublic: row.ispublic,
shareId: row.shareid,
viewCount: row.viewcount
};
await client.query(
`UPDATE snippets SET viewcount = viewcount + 1 WHERE id = $1`,
[id]
);
return res.json(snippet);
} catch (dbError) {
console.error(`[GET_ONE] Database error for ID ${id}:`, dbError);
throw dbError;
} finally {
client.release();
}
}
}
} catch (err: any) {
console.error(`[GET_ONE] GET /api/snippets/${req.params.id} error:`, err);
res.status(500).json({
message: "Failed to get snippet",
error: err.message
});
}
});
// CREATE new snippet (requires authentication)
app.post("/api/snippets", authMiddleware, async (req, res) => {
try {
console.log("[CREATE] Create snippet request received");
const userId = (req as any).user?.id;
console.log("[CREATE] Auth user ID:", userId);
if (!userId) {
console.error("[CREATE] No user ID found in request");
return res.status(401).json({ message: "Authentication required" });
}
console.log("[CREATE] Request body:", JSON.stringify({
title: req.body.title,
language: req.body.language,
codeLength: req.body.code ? req.body.code.length : 0,
hasDescription: !!req.body.description,
tagsCount: Array.isArray(req.body.tags) ? req.body.tags.length : 0
}));
if (!req.body.title || !req.body.code) {
console.error("[CREATE] Missing required fields:",
JSON.stringify({
hasTitle: !!req.body.title,
hasCode: !!req.body.code
})
);
return res.status(400).json({
message: "Title and code are required"
});
}
const client = await pool.connect();
try {
const result = await client.query(
`INSERT INTO snippets (
title, code, language, description, userid,
createdat, updatedat, tags, isfavorite, ispublic
) VALUES ($1, $2, $3, $4, $5, NOW(), NOW(), $6, $7, $8)
RETURNING id, title, code, language, description, tags, isfavorite, ispublic, createdat, updatedat`,
[
req.body.title,
req.body.code,
req.body.language || null,
req.body.description || null,
userId,
Array.isArray(req.body.tags) ? req.body.tags : (req.body.tags ? [req.body.tags] : null),
req.body.isFavorite === true,
req.body.isPublic === true
]
);
if (result.rows.length === 0) {
throw new Error("Failed to create snippet");
}
const createdSnippet = result.rows[0];
console.log("[CREATE] Snippet created successfully with ID:", createdSnippet.id);
const responseSnippet = {
id: createdSnippet.id,
title: createdSnippet.title,
code: createdSnippet.code,
language: createdSnippet.language,
description: createdSnippet.description,
tags: createdSnippet.tags,
userId: userId,
isFavorite: createdSnippet.isfavorite,
isPublic: createdSnippet.ispublic,
createdAt: createdSnippet.createdat,
updatedAt: createdSnippet.updatedat
};
res.status(201).json(responseSnippet);
} catch (dbError: any) {
console.error("[CREATE] Database error:", dbError);
res.status(500).json({ message: "Database error", error: dbError.message });
} finally {
client.release();
}
} catch (err: any) {
console.error("[CREATE] POST /api/snippets error:", err);
res.status(500).json({
message: "Failed to create snippet",
error: err.message
});
}
});
// UPDATE snippet (requires authentication)
app.put("/api/snippets/:id", authMiddleware, async (req, res) => {
try {
const id = Number(req.params.id);
const dto = insertSnippetSchema.parse(req.body);
const existing = await storage.getSnippet(id);
if (!existing) return res.status(404).json({ message: "Not found" });
if (existing.userId !== (req as any).user.id) {
return res.status(403).json({ message: "Forbidden" });
}
const updated = await storage.updateSnippet(id, dto);
res.json(updated);
} catch (err: any) {
if (err instanceof z.ZodError) {
return res.status(400).json({ message: "Invalid data", errors: err.errors });
}
console.error("[SNIPPETS] PUT /api/snippets/:id error:", err);
res.status(500).json({ message: "Failed to update snippet" });
}
});
// DELETE snippet (requires authentication)
app.delete("/api/snippets/:id", authMiddleware, async (req, res) => {
try {
console.log(`[DELETE] Delete snippet request received for ID: ${req.params.id}`);
const userId = (req as any).user?.id;
console.log("[DELETE] Auth user ID:", userId);
if (!userId) {
console.error("[DELETE] No user ID found in request");
return res.status(401).json({ message: "Authentication required" });
}
const id = Number(req.params.id);
const client = await pool.connect();
try {
const checkResult = await client.query(
`SELECT id, userid FROM snippets WHERE id = $1`,
[id]
);
if (checkResult.rows.length === 0) {
console.log(`[DELETE] Snippet not found with ID: ${id}`);
return res.status(404).json({ message: "Snippet not found" });
}
const snippet = checkResult.rows[0];
if (snippet.userid !== userId) {
console.log(`[DELETE] Forbidden - snippet ${id} belongs to ${snippet.userid}, not ${userId}`);
return res.status(403).json({ message: "Forbidden: you don't own this snippet" });
}
await client.query(
`DELETE FROM snippets WHERE id = $1`,
[id]
);
console.log(`[DELETE] Snippet ${id} successfully deleted`);
res.status(204).send();
} catch (dbError: any) {
console.error(`[DELETE] Database error for ID ${id}:`, dbError);
res.status(500).json({ message: "Database error", error: dbError.message });
} finally {
client.release();
}
} catch (err: any) {
console.error(`[DELETE] DELETE /api/snippets/${req.params.id} error:`, err);
res.status(500).json({
message: "Failed to delete snippet",
error: err.message
});
}
});
// ────────────────────────────────────────────────────────────────
// ─── 3.2.1) PUBLIC Snippets endpoints ──────────────────────────
// ────────────────────────────────────────────────────────────────
// GET all public snippets
app.get("/api/public/snippets", async (req, res) => {
try {
const filters: any = { isPublic: true };
if (req.query.search) filters.search = String(req.query.search);
if (req.query.language) filters.language = req.query.language;
if (req.query.tag) filters.tag = req.query.tag;
const snippets = await storage.getSnippets(filters);
res.json(snippets);
} catch (err: any) {
console.error("GET /api/public/snippets error:", err);
res.status(500).json({ message: "Failed to get public snippets", error: err.message });
}
});
// GET single public snippet by ID
app.get("/api/public/snippets/:id", async (req, res) => {
try {
const id = Number(req.params.id);
const snippet = await storage.getSnippet(id);
if (snippet && snippet.isPublic) {
// Optionally increment view count for public views as well
// await storage.incrementSnippetViewCount(id);
res.json(snippet);
} else {
res.status(404).json({ message: "Snippet not found or not public" });
}
} catch (err: any) {
console.error(`GET /api/public/snippets/${req.params.id} error:`, err);
res.status(500).json({ message: "Failed to get public snippet", error: err.message });
}
});
// TOGGLE FAVORITE (requires authentication)
app.post("/api/snippets/:id/favorite", authMiddleware, async (req, res) => {
try {
console.log(`[FAVORITE] Toggle favorite request received for ID: ${req.params.id}`);
const userId = (req as any).user?.id;
console.log("[FAVORITE] Auth user ID:", userId);
if (!userId) {
console.error("[FAVORITE] No user ID found in request");
return res.status(401).json({ message: "Authentication required" });
}
const id = Number(req.params.id);
const client = await pool.connect();
try {
const checkResult = await client.query(
`SELECT id, userid, isfavorite FROM snippets WHERE id = $1`,
[id]
);
if (checkResult.rows.length === 0) {
console.log(`[FAVORITE] Snippet not found with ID: ${id}`);
return res.status(404).json({ message: "Snippet not found" });
}
const snippet = checkResult.rows[0];
if (snippet.userid !== userId) {
console.log(`[FAVORITE] Forbidden - snippet ${id} belongs to ${snippet.userid}, not ${userId}`);
return res.status(403).json({ message: "Forbidden: you don't own this snippet" });
}
const newFavoriteStatus = !snippet.isfavorite;
const updateResult = await client.query(
`UPDATE snippets
SET isfavorite = $1, updatedat = NOW()
WHERE id = $2
RETURNING id, title, code, language, description, tags, userid, createdat, updatedat, isfavorite, ispublic, shareid, viewcount`,
[newFavoriteStatus, id]
);
const updatedSnippet = updateResult.rows[0];
console.log(`[FAVORITE] Snippet ${id} favorite status toggled to ${newFavoriteStatus}`);
const responseSnippet = {
id: updatedSnippet.id,
title: updatedSnippet.title,
code: updatedSnippet.code,
language: updatedSnippet.language,
description: updatedSnippet.description,
tags: updatedSnippet.tags || [],
userId: updatedSnippet.userid,
createdAt: updatedSnippet.createdat,
updatedAt: updatedSnippet.updatedat,
isFavorite: updatedSnippet.isfavorite,
isPublic: updatedSnippet.ispublic,
shareId: updatedSnippet.shareid,
viewCount: updatedSnippet.viewcount
};
res.json(responseSnippet);
} catch (dbError: any) {
console.error(`[FAVORITE] Database error for ID ${id}:`, dbError);
res.status(500).json({ message: "Database error", error: dbError.message });
} finally {
client.release();
}
} catch (err: any) {
console.error(`[FAVORITE] POST /api/snippets/${req.params.id}/favorite error:`, err);
res.status(500).json({
message: "Failed to toggle favorite status",
error: err.message
});
}
});
// IMPORT SNIPPETS (requires authentication)
app.post("/api/snippets/import", authMiddleware, async (req, res) => {
try {
console.log("[IMPORT] Import request received");
const userId = (req as any).user?.id;
console.log("[IMPORT] Auth user ID:", userId);
if (!userId) {
console.error("[IMPORT] No user ID found in request");
return res.status(401).json({ message: "Authentication required" });
}
console.log("[IMPORT] Request body structure:", JSON.stringify({
snippetsArrayLength: Array.isArray(req.body.snippets) ? req.body.snippets.length : 'not an array',
firstSnippetSample: Array.isArray(req.body.snippets) && req.body.snippets.length > 0
? { title: req.body.snippets[0].title, language: req.body.snippets[0].language }
: 'no snippets'
}));
const { snippets } = req.body;
if (!Array.isArray(snippets)) {
console.error("[IMPORT] Invalid input: snippets is not an array");
return res.status(400).json({
message: "Invalid input: snippets must be an array"
});
}
console.log(`[IMPORT] Processing ${snippets.length} snippets for import`);
const importResults = {
success: [],
failed: []
};
const client = await pool.connect();
for (let i = 0; i < snippets.length; i++) {
try {
const snippetData = snippets[i];
console.log(`[IMPORT] Processing snippet ${i+1}/${snippets.length}:`,
JSON.stringify({
title: snippetData.title || 'untitled',
language: snippetData.language || 'unknown',
codeLength: snippetData.code ? snippetData.code.length : 0,
hasDescription: !!snippetData.description,
tagsCount: Array.isArray(snippetData.tags) ? snippetData.tags.length : 0
})
);
if (!snippetData.title || !snippetData.code) {
console.error(`[IMPORT] Snippet ${i+1} missing required fields:`,
JSON.stringify({
hasTitle: !!snippetData.title,
hasCode: !!snippetData.code
})
);
importResults.failed.push({
index: i,
title: snippetData.title || 'untitled',
reason: "Missing required fields"
});
continue;
}
try {
const result = await client.query(
`INSERT INTO snippets (
title, code, language, description, userid,
createdat, updatedat, tags, isfavorite, ispublic
) VALUES ($1, $2, $3, $4, $5, NOW(), NOW(), $6, $7, $8)
RETURNING id, title`,
[
snippetData.title,
snippetData.code,
snippetData.language || null,
snippetData.description || null,
userId,
Array.isArray(snippetData.tags) ? snippetData.tags : null,
typeof snippetData.isFavorite === 'boolean' ? snippetData.isFavorite : false,
typeof snippetData.isPublic === 'boolean' ? snippetData.isPublic : false
]
);
console.log(`[IMPORT] Snippet ${i+1} created successfully with ID:`, result.rows[0].id);
importResults.success.push(result.rows[0]);
} catch (dbError: any) {
console.error(`[IMPORT] Database error for snippet ${i+1}:`, dbError);
importResults.failed.push({
index: i,
title: snippetData.title,
reason: dbError.message
});
continue;
}
} catch (snippetError: any) {
console.error(`[IMPORT] Error processing snippet ${i+1}:`, snippetError);
importResults.failed.push({
index: i,
title: snippets[i]?.title || 'unknown',
reason: snippetError.message
});
}
}
client.release();
console.log("[IMPORT] Import completed. Results:", JSON.stringify({
successCount: importResults.success.length,
failedCount: importResults.failed.length
}));
res.status(201).json({
message: `Successfully imported ${importResults.success.length} snippets. ${importResults.failed.length > 0 ? `Failed to import ${importResults.failed.length} snippets.` : ''}`,
success: importResults.success.map(s => ({ id: s.id, title: s.title })),
failed: importResults.failed
});
} catch (err: any) {
console.error("[IMPORT] POST /api/snippets/import error:", err);
res.status(500).json({
message: "Failed to import snippets",
error: err.message
});
}
});
// TEST IMPORT ENDPOINT (no auth required - for testing only)
app.post("/api/test-import", async (req, res) => {
console.log("TEST IMPORT ENDPOINT HIT");
try {
console.log("Request body:", JSON.stringify(req.body));
const { snippets } = req.body;
if (!Array.isArray(snippets)) {
console.error("Invalid input: snippets is not an array");
return res.status(400).json({
message: "Invalid input: snippets must be an array"
});
}
console.log(`Processing ${snippets.length} snippets for import`);
const testSnippet = snippets[0];
if (!testSnippet) {
return res.status(400).json({ message: "No snippets provided" });
}
const client = await pool.connect();
try {
const result = await client.query(
`INSERT INTO snippets (title, code, language, userid, createdat, updatedat, tags, isfavorite, ispublic)
VALUES ($1, $2, $3, $4, NOW(), NOW(), $5, $6, $7) RETURNING id, title`,
[
testSnippet.title,
testSnippet.code,
testSnippet.language || null,
'test-user-id',
Array.isArray(testSnippet.tags) ? testSnippet.tags : null,
false,
false
]
);
console.log("Direct DB insert result:", result.rows[0]);
res.status(201).json({
message: "Test import successful",
snippet: result.rows[0]
});
} catch (dbError: any) {
console.error("Database error:", dbError);
res.status(500).json({ message: "Database error", error: dbError.message });
} finally {
client.release();
}
} catch (err: any) {
console.error("TEST IMPORT error:", err);
res.status(500).json({
message: "Test import failed",
error: err.message
});
}
});
// ────────────────────────────────────────────────────────────────
// ─── 3.3) Languages & Tags ─────────────────────────────────────────
// ────────────────────────────────────────────────────────────────
app.get("/api/languages", async (req, res) => {
try {
let langs;
try {
langs = await simpleStorage.getLanguages();
} catch {
langs = await storage.getLanguages();
}
res.json(langs);
} catch (err: any) {
console.error("[LANGUAGES] GET /api/languages error:", err);
res.status(500).json({ message: "Failed to fetch languages" });
}
});
app.get("/api/tags", async (req, res) => {
try {
let tags;
try {
tags = await simpleStorage.getTags();
} catch {
tags = await storage.getTags();
}
res.json(tags);
} catch (err: any) {
console.error("[TAGS] GET /api/tags error:", err);
res.status(500).json({ message: "Failed to fetch tags" });
}
});
// ────────────────────────────────────────────────────────────────
// ─── 3.4) Collections ────────────────────────────────────────────
// ────────────────────────────────────────────────────────────────
app.get("/api/collections", async (req, res) => {
try {
let cols;
try {
cols = await simpleStorage.getCollections();
} catch {
cols = await storage.getCollections();
}
res.json(cols);
} catch (err: any) {
console.error("[COLLECTIONS] GET /api/collections error:", err);
res.status(500).json({ message: "Failed to fetch collections" });
}
});
app.get("/api/collections/:id", async (req, res) => {
try {
const id = Number(req.params.id);
const col = await storage.getCollection(id);
if (!col) return res.status(404).json({ message: "Not found" });
res.json(col);
} catch (err: any) {
console.error("[COLLECTIONS] GET /api/collections/:id error:", err);
res.status(500).json({ message: "Failed to fetch collection" });
}
});
app.get("/api/collections/:id/snippets", async (req, res) => {
try {
const id = Number(req.params.id);
const list = await storage.getCollectionSnippets(id);
res.json(list);
} catch (err: any) {
console.error("[COLLECTIONS] GET /api/collections/:id/snippets error:", err);
res.status(500).json({ message: "Failed to fetch collection snippets" });
}
});
// DEBUG COLLECTION POST ENDPOINT
app.post("/api/collections", authMiddleware, async (req, res) => {
try {
console.log("🔥 COLLECTION CREATE: Request received");
console.log("🔥 COLLECTION CREATE: User ID:", (req as any).user?.id);
console.log("🔥 COLLECTION CREATE: Request body:", JSON.stringify(req.body));
const dto = insertCollectionSchema.parse({
...req.body,
userId: (req as any).user.id
});
console.log("🔥 COLLECTION CREATE: Parsed DTO:", JSON.stringify(dto));
console.log("🔥 COLLECTION CREATE: About to call storage.createCollection");
const created = await storage.createCollection(dto);
console.log("🔥 COLLECTION CREATE: Success! Created collection:", JSON.stringify(created));
res.status(201).json(created);
} catch (err: any) {
console.error("🔥 COLLECTION CREATE: Caught error:", err);
console.error("🔥 COLLECTION CREATE: Error name:", err.name);
console.error("🔥 COLLECTION CREATE: Error message:", err.message);
console.error("🔥 COLLECTION CREATE: Error stack:", err.stack);
if (err instanceof z.ZodError) {
console.error("🔥 COLLECTION CREATE: Zod validation error:", err.errors);
return res.status(400).json({ message: "Invalid data", errors: err.errors });
}
console.error("[COLLECTIONS] POST /api/collections error:", err);
res.status(500).json({
message: "Failed to create collection",
error: err.message,
details: err.stack
});
}
});
app.put("/api/collections/:id", authMiddleware, async (req, res) => {
try {
const id = Number(req.params.id);
const dto = insertCollectionSchema.parse(req.body);
const existing = await storage.getCollection(id);
if (!existing) return res.status(404).json({ message: "Not found" });
if (existing.userId !== (req as any).user.id) {
return res.status(403).json({ message: "Forbidden" });
}
const updated = await storage.updateCollection(id, dto);
res.json(updated);
} catch (err: any) {
if (err instanceof z.ZodError) {
return res.status(400).json({ message: "Invalid data", errors: err.errors });
}
console.error("[COLLECTIONS] PUT /api/collections/:id error:", err);
res.status(500).json({ message: "Failed to update collection" });
}
});
app.delete("/api/collections/:id", authMiddleware, async (req, res) => {
try {
const id = Number(req.params.id);
const existing = await storage.getCollection(id);
if (!existing) return res.status(404).json({ message: "Not found" });
if (existing.userId !== (req as any).user.id) {
return res.status(403).json({ message: "Forbidden" });
}
await storage.deleteCollection(id);
res.status(204).send();
} catch (err: any) {
console.error("[COLLECTIONS] DELETE /api/collections/:id error:", err);
res.status(500).json({ message: "Failed to delete collection" });
}
});
app.post(
"/api/collections/:collectionId/snippets/:snippetId",
authMiddleware,
async (req, res) => {
try {
const collectionId = Number(req.params.collectionId);
const snippetId = Number(req.params.snippetId);
const existing = await storage.getCollection(collectionId);
if (!existing) return res.status(404).json({ message: "Not found" });
if (existing.userId !== (req as any).user.id) {
return res.status(403).json({ message: "Forbidden" });
}
const dto = insertCollectionItemSchema.parse({ collectionId, snippetId });
const created = await storage.addSnippetToCollection(dto);
res.status(201).json(created);
} catch (err: any) {
if (err instanceof z.ZodError) {
return res.status(400).json({ message: "Invalid data", errors: err.errors });
}
console.error(
"[COLLECTION ITEMS] POST /api/collections/:collectionId/snippets/:snippetId error:",
err
);
res.status(500).json({ message: "Failed to add snippet to collection" });
}
}
);
app.delete(
"/api/collections/:collectionId/snippets/:snippetId",
authMiddleware,
async (req, res) => {
try {
const collectionId = Number(req.params.collectionId);
const snippetId = Number(req.params.snippetId);
const existing = await storage.getCollection(collectionId);
if (!existing) return res.status(404).json({ message: "Not found" });
if (existing.userId !== (req as any).user.id) {
return res.status(403).json({ message: "Forbidden" });
}
await storage.removeSnippetFromCollection(collectionId, snippetId);
res.status(204).send();
} catch (err: any) {
console.error(
"[COLLECTION ITEMS] DELETE /api/collections/:collectionId/snippets/:snippetId error:",
err
);
res.status(500).json({ message: "Failed to remove snippet from collection" });
}
}
);
// ────────────────────────────────────────────────────────────────
// ─── 3.5) Sharing & Publishing ─────────────────────────────────────
// ────────────────────────────────────────────────────────────────
app.get("/api/shared/:shareId", async (req, res) => {