-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy patharticle.actions.ts
More file actions
730 lines (656 loc) · 19.8 KB
/
article.actions.ts
File metadata and controls
730 lines (656 loc) · 19.8 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
"use server";
import { cacheTag, revalidateTag } from "next/cache";
import { pgClient } from "@/backend/persistence/clients";
import { slugify } from "@/lib/slug-helper.util";
import {
removeMarkdownSyntax,
removeUndefinedFromObject,
generateRandomString,
resolveArticleExcerpt,
} from "@/lib/utils";
import { addDays } from "date-fns";
import * as sk from "sqlkit";
import { and, asc, desc, eq, isNotNull, isNull, like, neq, or } from "sqlkit";
import { z } from "zod/v4";
import { ActionResponse } from "../models/action-contracts";
import { Article, User } from "../models/domain-models";
import { DatabaseTableName } from "../persistence/persistence-contracts";
import { persistenceRepository } from "../persistence/persistence-repositories";
import { ArticleRepositoryInput } from "./inputs/article.input";
import { ActionException, handleActionException } from "./RepositoryException";
import { deleteArticleById, syncArticleById } from "./search.service";
import { authID } from "./session.actions";
import { syncTagsWithArticles } from "./tag.action";
export async function createMyArticle(
_input: z.infer<typeof ArticleRepositoryInput.createMyArticleInput>
) {
try {
const sessionUserId = await authID();
if (!sessionUserId) {
throw new ActionException("Unauthorized");
}
const input =
await ArticleRepositoryInput.createMyArticleInput.parseAsync(_input);
// Generate title with unique suffix if title is empty or just whitespace
let titleToUse = input.title?.trim();
if (!titleToUse) {
// Generate a unique untitled with 6 character random suffix
const randomSuffix = generateRandomString(6);
titleToUse = `untitled-${randomSuffix}`;
// Ensure this title is unique
let attempts = 0;
const maxAttempts = 10;
while (attempts < maxAttempts) {
const existingArticle = await persistenceRepository.article.find({
where: eq("title", titleToUse),
columns: ["id"],
limit: 1,
});
if (existingArticle.length === 0) {
break; // Title is unique
}
// Generate a new random suffix and try again
const newRandomSuffix = generateRandomString(6);
titleToUse = `untitled-${newRandomSuffix}`;
attempts++;
}
if (attempts >= maxAttempts) {
throw new ActionException("Failed to generate a unique title after multiple attempts");
}
}
// Generate a unique handle based on the title
const handle = await getUniqueArticleHandle(titleToUse);
if (!handle) {
throw new ActionException(
"Failed to generate a unique handle for the article"
);
}
const article = await persistenceRepository.article.insert([
{
title: titleToUse,
handle: handle,
excerpt: input.excerpt ?? null,
body: input.body ?? null,
cover_image: input.cover_image ?? null,
published_at: input.is_published ? new Date() : null,
created_at: new Date(),
author_id: sessionUserId,
approved_at: new Date(), // TODO: manually handle this from seperate dashboard
},
]);
return article?.rows?.[0];
} catch (error) {
console.error("Article creation error:", error);
handleActionException(error);
return null;
}
}
export const getUniqueArticleHandle = async (
title: string,
ignoreArticleId?: string
) => {
try {
// Slugify the title first
const baseHandle = slugify(title);
// If we have an ignoreArticleId, check if this article already exists
if (ignoreArticleId) {
const [existingArticle] = await persistenceRepository.article.find({
where: eq("id", ignoreArticleId),
columns: ["id", "handle"],
limit: 1,
});
// If the article exists and its handle is already the slugified title,
// we can just return that handle (no need to append a number)
if (existingArticle && existingArticle.handle === baseHandle) {
return baseHandle;
}
}
// Find all articles with the same base handle or handles that have numeric suffixes
const handlePattern = `${baseHandle}-%`;
let baseHandleWhereClause: any = eq<Article, keyof Article>(
"handle",
baseHandle
);
let suffixWhereClause: any = like<Article>("handle", handlePattern);
let whereClause: any = or(baseHandleWhereClause, suffixWhereClause);
if (ignoreArticleId) {
whereClause = and(
whereClause,
neq<Article, keyof Article>("id", ignoreArticleId)
);
}
// Get all existing handles that match our patterns
const existingArticles = await persistenceRepository.article.find({
where: whereClause,
columns: ["handle"],
limit: 1,
});
// If no existing handles found, return the base handle
if (existingArticles.length === 0) {
return baseHandle;
}
// Check if the exact base handle exists
const exactBaseExists = existingArticles.some(
(article) => article.handle === baseHandle
);
// If the exact base handle doesn't exist, we can use it
if (!exactBaseExists) {
return baseHandle;
}
// Find the highest numbered suffix
let highestNumber = 1;
const regex = new RegExp(`^${baseHandle}-(\\d+)$`);
existingArticles.forEach((article) => {
const match = article.handle.match(regex);
if (match) {
const num = parseInt(match[1], 10);
if (num >= highestNumber) {
highestNumber = num + 1;
}
}
});
// Return with the next number in sequence
return `${baseHandle}-${highestNumber}`;
} catch (error) {
handleActionException(error);
throw error;
}
};
export async function updateMyArticle(
_input: z.infer<typeof ArticleRepositoryInput.updateMyArticleInput>
) {
try {
const sessionUserId = await authID();
if (!sessionUserId) {
throw new ActionException("Unauthorized");
}
const input =
await ArticleRepositoryInput.updateMyArticleInput.parseAsync(_input);
const article = await persistenceRepository.article.update({
where: and(eq("id", input.article_id), eq("author_id", sessionUserId)),
data: removeUndefinedFromObject({
title: input.title,
handle: input.handle,
excerpt: input.excerpt,
body: input.body,
cover_image: input.cover_image,
metadata: input.metadata,
}),
});
revalidateTag(`article-${article.rows[0].handle}`, "max");
if (article.rows[0].published_at) {
syncArticleById(article.rows[0].id);
}
if (input.tag_ids) {
await syncTagsWithArticles({
article_id: input.article_id,
tag_ids: input.tag_ids,
});
}
return {
success: true as const,
data: article?.rows?.[0],
};
} catch (error) {
if (error instanceof Error) {
console.log(JSON.stringify(error.stack));
}
return handleActionException(error);
}
}
export async function scheduleArticleDelete(article_id: string) {
try {
const session_userID = await authID();
if (!session_userID) {
throw new ActionException("Unauthorized");
}
const [permissibleArticle] = await persistenceRepository.article.find({
where: and(eq("id", article_id), eq("author_id", session_userID)),
});
if (!permissibleArticle) {
throw new ActionException("Unauthorized");
}
const updated = await persistenceRepository.article.update({
where: and(eq("id", article_id), eq("author_id", session_userID)),
data: {
delete_scheduled_at: addDays(new Date(), 7),
published_at: null,
},
});
deleteArticleById(article_id);
return {
success: true as const,
data: updated.rows[0],
} satisfies ActionResponse<unknown>;
} catch (error) {
return handleActionException(error);
}
}
export const restoreShceduleDeletedArticle = async (
article_id: string
): Promise<ActionResponse<unknown>> => {
try {
const session_userID = await authID();
if (!session_userID) {
throw new ActionException("Unauthorized");
}
const [permissibleArticle] = await persistenceRepository.article.find({
where: and(eq("id", article_id), eq("author_id", session_userID)),
});
if (!permissibleArticle) {
throw new ActionException("Unauthorized");
}
const updated = await persistenceRepository.article.update({
where: and(eq("id", article_id), eq("author_id", session_userID)),
data: { delete_scheduled_at: null },
});
return {
success: true as const,
data: updated.rows[0],
};
} catch (error) {
return handleActionException(error);
}
};
/**
* Deletes an article from the database.
*
* @param article_id - The unique identifier of the article to delete
* @returns Promise<Article> - The deleted article
* @throws {ActionException} If article deletion fails or article not found
*/
export async function deleteArticle(article_id: string) {
try {
const deletedArticles = await persistenceRepository.article.delete({
where: eq("id", article_id),
});
revalidateTag("tags-list", "max");
return deletedArticles?.rows?.[0];
} catch (error) {
handleActionException(error);
}
}
/**
* Retrieves the most recent published articles.
*
* @param limit - Maximum number of articles to return (default: 5)
* @returns Promise<Article[]> - Array of recent articles with author information
* @throws {ActionException} If query fails
*/
// export async function findRecentArticles(
// limit: number = 5
// ): Promise<Article[]> {
// try {
// return articleRepository.findRows({
// where: and(neq("published_at", null), neq("published_at", null)),
// limit,
// orderBy: [desc("published_at")],
// columns: ["id", "title", "handle"],
// joins: [
// leftJoin<Article, User>({
// as: "user",
// joinTo: "users",
// localField: "author_id",
// foreignField: "id",
// columns: ["id", "name", "username", "profile_photo"],
// }),
// ],
// });
// } catch (error) {
// handleRepositoryException(error);
// return [];
// }
// }
/**
* Retrieves a paginated feed of published articles.
*
* @param _input - Feed parameters including page and limit, validated against ArticleRepositoryInput.feedInput schema
* @returns Promise<{ data: Article[], total: number }> - Paginated articles with total count
* @throws {ActionException} If query fails or validation fails
*/
export async function articleFeed(
_input: z.infer<typeof ArticleRepositoryInput.feedInput>
) {
try {
const input = await ArticleRepositoryInput.feedInput.parseAsync(_input);
const response = await persistenceRepository.article.paginate({
where: and(neq("published_at", null), neq("approved_at", null)),
page: input.page,
limit: input.limit,
orderBy: [desc("published_at")],
columns: [
"id",
"title",
"handle",
"cover_image",
"body",
"created_at",
"published_at",
"excerpt",
],
joins: [
{
as: "user",
table: DatabaseTableName.users,
type: "left",
on: {
foreignField: "id",
localField: "author_id",
},
columns: ["id", "name", "username", "profile_photo", "is_verified"],
} as sk.Join<Article, User>,
],
});
response["nodes"] = response["nodes"].map((article) => {
return {
...article,
excerpt: removeMarkdownSyntax(article.body),
};
});
return response;
} catch (error) {
handleActionException(error);
}
}
export async function userArticleFeed(
_input: z.infer<typeof ArticleRepositoryInput.userFeedInput>,
columns?: (keyof Article)[]
) {
try {
const input = await ArticleRepositoryInput.userFeedInput.parseAsync(_input);
const response = await persistenceRepository.article.paginate({
operationName: "userArticleFeed",
where: and(
neq("published_at", null),
neq("approved_at", null),
eq("author_id", input.user_id)
),
page: input.page,
limit: input.limit,
orderBy: [desc("published_at")],
columns,
joins: [
{
as: "user",
table: DatabaseTableName.users,
type: "left",
on: {
foreignField: "id",
localField: "author_id",
},
columns: ["id", "name", "username", "profile_photo", "is_verified"],
} as sk.Join<Article, User>,
],
});
response["nodes"] = response["nodes"].map((article) => {
return {
...article,
excerpt: resolveArticleExcerpt(article.excerpt, article.body),
};
});
return response;
} catch (error) {
handleActionException(error);
}
}
/**
* Retrieves a paginated feed of published articles filtered by tag ID.
*
* @param _input - Feed parameters including tag_id, page and limit, validated against ArticleRepositoryInput.tagFeedInput schema
* @returns Promise<{ data: Article[], total: number }> - Paginated articles with total count
* @throws {ActionException} If query fails or validation fails
*/
export async function articlesByTag(
_input: z.infer<typeof ArticleRepositoryInput.tagFeedInput>
) {
try {
const input = await ArticleRepositoryInput.tagFeedInput.parseAsync(_input);
const offset = (input.page - 1) * input.limit;
// Single SQL query to get articles by tag with pagination
const sql = String.raw;
const articlesQuery = sql`
SELECT
a.id,
a.title,
a.handle,
a.cover_image,
a.body,
a.created_at,
a.excerpt,
u.id as user_id,
u.name as user_name,
u.username as user_username,
u.profile_photo as user_profile_photo,
u.is_verified as user_is_verified,
t.name as tag_name,
COUNT(*) OVER() as total_count
FROM articles a
INNER JOIN article_tag at ON a.id = at.article_id
INNER JOIN tags t ON at.tag_id = t.id
LEFT JOIN users u ON a.author_id = u.id
WHERE
a.published_at is not null
AND t.id = $1
ORDER BY a.published_at DESC
LIMIT $2 OFFSET $3
`;
const result = await pgClient?.executeSQL<any>(articlesQuery, [
input.tag_id,
input.limit,
offset,
]);
const rows = result?.rows || [];
const totalCount = rows.length > 0 ? parseInt(rows[0].total_count) : 0;
const totalPages = Math.ceil(totalCount / input.limit);
// Transform the data to match the expected format
const nodes = rows.map((row: any) => ({
id: row.id,
title: row.title,
handle: row.handle,
cover_image: row.cover_image,
body: row.body,
created_at: new Date(row.created_at),
excerpt: resolveArticleExcerpt(row.excerpt, row.body),
user: {
id: row.user_id,
name: row.user_name,
username: row.user_username,
profile_photo: row.user_profile_photo,
is_verified: row.user_is_verified,
},
}));
// Get tag name from first row for display purposes
const tagName = rows.length > 0 ? rows[0].tag_name : null;
return {
nodes,
tagName,
meta: {
total: totalCount,
currentPage: input.page,
totalPages,
hasNextPage: input.page < totalPages,
hasPreviousPage: input.page > 1,
},
};
} catch (error) {
handleActionException(error);
}
}
export async function articleDetailByHandle(article_handle: string) {
"use cache";
cacheTag(`article-${article_handle}`);
try {
const [article] = await persistenceRepository.article.find({
where: eq("handle", article_handle),
columns: [
"id",
"title",
"handle",
"excerpt",
"body",
"cover_image",
"published_at",
"approved_at",
"metadata",
"author_id",
"created_at",
"updated_at",
],
joins: [
{
as: "user",
type: "left",
table: DatabaseTableName.users,
on: {
foreignField: "id",
localField: "author_id",
},
columns: ["id", "name", "username", "profile_photo"],
} as sk.Join<Article, User>,
],
limit: 1,
});
if (!article) {
throw new ActionException("Article not found");
}
// Fetch tags for the article
const sql = String.raw;
const tagsQuery = sql`
SELECT
t.id,
t.name,
t.color,
t.description,
t.created_at,
t.updated_at
FROM tags t
INNER JOIN article_tag at ON t.id = at.tag_id
WHERE at.article_id = $1
ORDER BY t.name ASC
`;
const tagsResult = await pgClient?.executeSQL<{
id: string;
name: string;
color: string | null;
description: string | null;
created_at: Date;
updated_at: Date;
}>(tagsQuery, [article.id]);
const tags = tagsResult?.rows || [];
return {
...article,
tags,
};
} catch (error) {
handleActionException(error);
}
}
export async function articleDetailByUUID(uuid: string) {
try {
const [article] = await persistenceRepository.article.find({
where: eq("id", uuid),
columns: [
"id",
"title",
"handle",
"excerpt",
"body",
"cover_image",
"published_at",
"approved_at",
"metadata",
"author_id",
"created_at",
"updated_at",
],
joins: [
{
as: "user",
table: "users",
on: {
foreignField: "id",
localField: "author_id",
},
type: "left",
columns: ["id", "name", "username", "profile_photo"],
},
],
limit: 1,
});
if (!article) {
throw new ActionException("Article not found");
}
return article;
} catch (error) {
handleActionException(error);
}
}
export async function myArticles(
input: z.infer<typeof ArticleRepositoryInput.myArticleInput>
) {
const sessionUserId = await authID();
if (!sessionUserId) {
throw new ActionException("Unauthorized");
}
try {
const sortFn = input.sort_order === "asc" ? asc : desc;
const statusCondition =
input.status === "published"
? isNotNull<Article>("published_at")
: input.status === "draft"
? isNull<Article>("published_at")
: undefined;
const articles = await persistenceRepository.article.paginate({
where: and(
eq("author_id", sessionUserId!),
...(statusCondition ? [statusCondition] : [])
),
columns: [
"id",
"title",
"handle",
"created_at",
"published_at",
"delete_scheduled_at",
"approved_at",
],
limit: input.limit,
page: input.page,
orderBy: [sortFn(input.sort_by)],
});
return articles;
} catch (error) {
handleActionException(error);
}
}
/**
* Updates the status of an article.
* @param article_id - The unique identifier of the article to update
* @param is_published - The new status of the article
* @returns
*/
export async function setArticlePublished(
article_id: string,
is_published: boolean
) {
const sessionUserId = await authID();
try {
const articles = await persistenceRepository.article.update({
where: and(
eq("id", article_id),
eq("author_id", sessionUserId?.toString()!)
),
data: { published_at: is_published ? new Date() : null },
});
if (articles?.rows?.[0] && is_published) {
syncArticleById(article_id);
}
if (articles?.rows?.[0] && !is_published) {
deleteArticleById(article_id);
}
revalidateTag("tags-list", "max");
return articles?.rows?.[0];
} catch (error) {
return handleActionException(error);
}
}