Skip to content

Commit f87ebf8

Browse files
feat: catalog module
- feat: add slug generator from submissions title
1 parent c897c47 commit f87ebf8

6 files changed

Lines changed: 307 additions & 1 deletion

File tree

‎apps/api-elysia/src/app.ts‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@ import {
1414
} from "./common/middleware/rate-limiter";
1515
import { requestLogger } from "./common/middleware/request-logger";
1616
import { errorHandler } from "./common/middleware/error-handler";
17+
import { catalogModule } from "./modules/catalog";
1718

1819
export const createApp = () => {
1920
const app = new Elysia()
@@ -54,7 +55,8 @@ export const createApp = () => {
5455

5556
.use(healthModule)
5657
.use(postsModule)
57-
.use(submissionsModule);
58+
.use(submissionsModule)
59+
.use(catalogModule);
5860

5961
if (env.ENABLE_AUTH) {
6062
app.use(authRateLimit);
Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
// src/common/utils/slugify.ts
2+
export function generateSlug(text: string): string {
3+
return text
4+
.toLowerCase()
5+
.trim()
6+
.replace(/[^\w\s-]/g, "")
7+
.replace(/[\s_-]+/g, "-")
8+
.replace(/^-+|-+$/g, "");
9+
}
Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
import { Elysia } from "elysia";
2+
import * as service from "./service";
3+
import * as schemas from "./schemas";
4+
5+
export const catalogModule = new Elysia({ prefix: "/catalog" })
6+
.get(
7+
"/",
8+
async ({ query }) => {
9+
return await service.catalogService.fetchPublicCatalog(query);
10+
},
11+
{
12+
query: schemas.getCatalogQuerySchema,
13+
detail: {
14+
tags: ["Catalog"],
15+
summary: "Get public catalog list with pagination and filter",
16+
},
17+
},
18+
)
19+
.get(
20+
"/:slug",
21+
async ({ params, set }) => {
22+
try {
23+
return await service.catalogService.fetchCatalogDetail(params.slug);
24+
} catch (error) {
25+
set.status = 404;
26+
return {
27+
success: false,
28+
error: error instanceof Error ? error.message : "Catalog not found",
29+
};
30+
}
31+
},
32+
{
33+
params: schemas.catalogSlugParamSchema,
34+
detail: {
35+
tags: ["Catalog"],
36+
summary: "Get catalog detail by slug",
37+
},
38+
},
39+
);
Lines changed: 147 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,147 @@
1+
import {
2+
bookDetail,
3+
catalogEntry,
4+
essayDetail,
5+
submission,
6+
} from "@/common/db/schema";
7+
import { db } from "@common/db";
8+
import { eq, and, sql } from "drizzle-orm";
9+
10+
export const catalogRepository = {
11+
async getPublicCatalog(options: {
12+
type?: "BOOK" | "ESSAY";
13+
limit: number;
14+
offset: number;
15+
}) {
16+
const { type, limit, offset } = options;
17+
18+
const items = await db
19+
.select({
20+
id: catalogEntry.id,
21+
slug: catalogEntry.slug,
22+
coverImageUrl: catalogEntry.coverImageUrl,
23+
publishedAt: catalogEntry.publishedAt,
24+
submissionId: submission.id,
25+
title: submission.title,
26+
description: submission.description,
27+
type: submission.type,
28+
// Detail Buku (akan null jika tipe ESSAY)
29+
bookDetail: {
30+
genre: bookDetail.genre,
31+
pageCount: bookDetail.pageCount,
32+
language: bookDetail.language,
33+
isbn: bookDetail.isbn,
34+
},
35+
// Detail Esai (akan null jika tipe BOOK)
36+
essayDetail: {
37+
topic: essayDetail.topic,
38+
wordCount: essayDetail.wordCount,
39+
},
40+
})
41+
.from(catalogEntry)
42+
.innerJoin(submission, eq(catalogEntry.submissionId, submission.id))
43+
.leftJoin(bookDetail, eq(submission.id, bookDetail.submissionId))
44+
.leftJoin(essayDetail, eq(submission.id, essayDetail.submissionId))
45+
.where(
46+
and(
47+
eq(catalogEntry.isPublished, true),
48+
eq(submission.status, "APPROVED"),
49+
type ? eq(submission.type, type) : undefined,
50+
),
51+
)
52+
.limit(limit)
53+
.offset(offset);
54+
55+
const totalResult = await db
56+
.select({ count: sql<number>`count(*)` })
57+
.from(catalogEntry)
58+
.innerJoin(submission, eq(catalogEntry.submissionId, submission.id))
59+
.where(
60+
and(
61+
eq(catalogEntry.isPublished, true),
62+
eq(submission.status, "APPROVED"),
63+
type ? eq(submission.type, type) : undefined,
64+
),
65+
);
66+
67+
const total = Number(totalResult[0]?.count || 0);
68+
69+
return { items, total };
70+
},
71+
72+
async getCatalogBySlug(slug: string) {
73+
const result = await db
74+
.select({
75+
id: catalogEntry.id,
76+
slug: catalogEntry.slug,
77+
coverImageUrl: catalogEntry.coverImageUrl,
78+
publishedAt: catalogEntry.publishedAt,
79+
submissionId: submission.id,
80+
title: submission.title,
81+
description: submission.description,
82+
type: submission.type,
83+
bookDetail: {
84+
genre: bookDetail.genre,
85+
pageCount: bookDetail.pageCount,
86+
language: bookDetail.language,
87+
isbn: bookDetail.isbn,
88+
},
89+
essayDetail: {
90+
topic: essayDetail.topic,
91+
wordCount: essayDetail.wordCount,
92+
},
93+
})
94+
.from(catalogEntry)
95+
.innerJoin(submission, eq(catalogEntry.submissionId, submission.id))
96+
.leftJoin(bookDetail, eq(submission.id, bookDetail.submissionId))
97+
.leftJoin(essayDetail, eq(submission.id, essayDetail.submissionId))
98+
.where(
99+
and(
100+
eq(catalogEntry.slug, slug),
101+
eq(catalogEntry.isPublished, true),
102+
eq(submission.status, "APPROVED"),
103+
),
104+
)
105+
.limit(1);
106+
107+
return result[0] || null;
108+
},
109+
110+
async findSubmissionTitle(submissionId: string) {
111+
const result = await db
112+
.select({ title: submission.title })
113+
.from(submission)
114+
.where(eq(submission.id, submissionId))
115+
.limit(1);
116+
117+
return result[0] || null;
118+
},
119+
120+
async findCatalogBySlug(slug: string) {
121+
const result = await db
122+
.select()
123+
.from(catalogEntry)
124+
.where(eq(catalogEntry.slug, slug))
125+
.limit(1);
126+
127+
return result[0] || null;
128+
},
129+
130+
async insertCatalogEntry(data: {
131+
submissionId: string;
132+
slug: string;
133+
publishedById: string;
134+
}) {
135+
const result = await db
136+
.insert(catalogEntry)
137+
.values({
138+
submissionId: data.submissionId,
139+
slug: data.slug,
140+
isPublished: false,
141+
publishedById: data.publishedById,
142+
})
143+
.returning();
144+
145+
return result[0];
146+
},
147+
};
Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
// src/modules/catalog/catalog.schema.ts
2+
import { t } from "elysia";
3+
import { createInsertSchema, createSelectSchema } from "drizzle-typebox";
4+
import { catalogEntry } from "@/common/db/schema/catalog";
5+
6+
export const selectCatalogEntrySchema = createSelectSchema(catalogEntry, {
7+
coverImageUrl: t.Union([t.String({ format: "uri" }), t.Null()]),
8+
publishedAt: t.Union([t.String({ format: "date-time" }), t.Null()]),
9+
});
10+
11+
const rawInsertSchema = createInsertSchema(catalogEntry, {
12+
slug: t.String({ minLength: 3 }),
13+
coverImageUrl: t.Optional(t.String({ format: "uri" })),
14+
});
15+
16+
export const insertCatalogEntrySchema = t.Omit(rawInsertSchema, [
17+
"id",
18+
"createdAt",
19+
"updatedAt",
20+
"publishedAt",
21+
"publishedById",
22+
]);
23+
24+
export const updatePublishStatusSchema = t.Object({
25+
isPublished: t.Boolean(),
26+
coverImageUrl: t.Optional(t.String({ format: "uri" })),
27+
});
28+
29+
export const getCatalogQuerySchema = t.Object({
30+
page: t.Optional(t.String()),
31+
limit: t.Optional(t.String()),
32+
type: t.Optional(t.Union([t.Literal("BOOK"), t.Literal("ESSAY")])),
33+
});
34+
35+
export const catalogSlugParamSchema = t.Object({
36+
slug: t.String(),
37+
});
Lines changed: 72 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,72 @@
1+
import { generateSlug } from "@/common/utils/slugify";
2+
import { catalogRepository } from "./repository";
3+
4+
export const catalogService = {
5+
async fetchPublicCatalog(query: {
6+
page?: string;
7+
limit?: string;
8+
type?: "BOOK" | "ESSAY";
9+
}) {
10+
const page = Number(query.page) || 1;
11+
const limit = Number(query.limit) || 10;
12+
const offset = (page - 1) * limit;
13+
14+
const { items, total } = await catalogRepository.getPublicCatalog({
15+
type: query.type,
16+
limit,
17+
offset,
18+
});
19+
return {
20+
success: true,
21+
data: items,
22+
count: items.length,
23+
pagination: {
24+
page,
25+
limit,
26+
totalItems: total,
27+
totalPages: Math.ceil(total / limit),
28+
},
29+
};
30+
},
31+
32+
async fetchCatalogDetail(slug: string) {
33+
const item = await catalogRepository.getCatalogBySlug(slug);
34+
35+
if (!item) {
36+
throw new Error("Catalog item not found or not published");
37+
}
38+
39+
return {
40+
success: true,
41+
data: item,
42+
};
43+
},
44+
45+
async createCatalogEntryFromSubmission(submissionId: string, userId: string) {
46+
const sub = await catalogRepository.findSubmissionTitle(submissionId);
47+
48+
if (!sub) {
49+
throw new Error("Submission not found");
50+
}
51+
52+
let baseSlug = generateSlug(sub.title);
53+
let finalSlug = baseSlug;
54+
55+
// Cek duplikasi slug di database
56+
const existing = await catalogRepository.findCatalogBySlug(finalSlug);
57+
if (existing) {
58+
finalSlug = `${baseSlug}-${Date.now().toString().slice(-4)}`;
59+
}
60+
61+
const newCatalog = await catalogRepository.insertCatalogEntry({
62+
submissionId,
63+
slug: finalSlug,
64+
publishedById: userId,
65+
});
66+
67+
return {
68+
success: true,
69+
data: newCatalog,
70+
};
71+
},
72+
};

0 commit comments

Comments
 (0)