@@ -37,9 +37,39 @@ export async function getWorkBook(workBookId: number): Promise<WorkBook | null>
3737 return workBook ;
3838}
3939
40+ /**
41+ * Retrieves a WorkBook from the database by its URL slug.
42+ *
43+ * @param urlSlug - The URL slug identifier for the WorkBook to retrieve (e.g., 'bfs', 'dfs', 'union-find', '2-sat').
44+ * @returns A Promise that resolves to the found WorkBook (with included workBookTasks
45+ * ordered by priority) or null if no WorkBook with the given slug exists
46+ */
47+ export async function getWorkBookByUrlSlug ( urlSlug : string ) : Promise < WorkBook | null > {
48+ const workBook = await db . workBook . findUnique ( {
49+ where : {
50+ urlSlug : urlSlug ,
51+ } ,
52+ include : {
53+ workBookTasks : {
54+ orderBy : {
55+ priority : 'asc' ,
56+ } ,
57+ } ,
58+ } ,
59+ } ) ;
60+
61+ return workBook ;
62+ }
63+
4064// See:
4165// https://www.prisma.io/docs/orm/prisma-schema/data-model/relations#create-a-record-and-nested-records
4266export async function createWorkBook ( workBook : WorkBook ) : Promise < void > {
67+ const slug = workBook . urlSlug ;
68+
69+ if ( slug && ( await isExistingUrlSlug ( slug ) ) ) {
70+ throw new Error ( `WorkBook slug ${ slug } has already existed` ) ;
71+ }
72+
4373 const sanitizedUrl = sanitizeUrl ( workBook . editorialUrl ) ;
4474 const newWorkBookTasks : WorkBookTasksBase = await getWorkBookTasks ( workBook ) ;
4575
@@ -53,6 +83,7 @@ export async function createWorkBook(workBook: WorkBook): Promise<void> {
5383 isOfficial : workBook . isOfficial ,
5484 isReplenished : workBook . isReplenished ,
5585 workBookType : workBook . workBookType as WorkBookType ,
86+ urlSlug : workBook . urlSlug ,
5687 workBookTasks : {
5788 create : newWorkBookTasks ,
5889 } ,
@@ -65,6 +96,10 @@ export async function createWorkBook(workBook: WorkBook): Promise<void> {
6596 console . log ( `Created workbook with title: ${ newWorkBook . title } ` ) ;
6697}
6798
99+ async function isExistingUrlSlug ( slug : string ) : Promise < boolean > {
100+ return ! ! ( await getWorkBookByUrlSlug ( slug ) ) ;
101+ }
102+
68103async function isExistingWorkBook ( workBookId : number ) : Promise < boolean > {
69104 const workBook = await getWorkBook ( workBookId ) ;
70105
0 commit comments