@@ -4,8 +4,20 @@ import redis from "@/cache";
44import db from "@/db/index" ;
55import { articles } from "@/db/schema" ;
66
7- export async function getArticles ( ) {
8- const cached = await redis . get ( "articles:all" ) ;
7+ // The list view selects only a subset of Article fields and adds the author's
8+ // resolved name. Use a dedicated type for the list response.
9+ export type ArticleList = {
10+ id : number ;
11+ title : string ;
12+ createdAt : string ;
13+ summary : string | null ;
14+ content : string ;
15+ author : string | null ;
16+ imageUrl ?: string | null ;
17+ } ;
18+
19+ export async function getArticles ( ) : Promise < ArticleList [ ] > {
20+ const cached = await redis . get < ArticleList [ ] > ( "articles:all" ) ;
921 if ( cached ) {
1022 console . log ( "🎯 Get Articles Cache Hit!" ) ;
1123 return cached ;
@@ -24,12 +36,26 @@ export async function getArticles() {
2436 . leftJoin ( usersSync , eq ( articles . authorId , usersSync . id ) ) ;
2537
2638 console . log ( "🙅♂️ Get Articles Cache Miss!" ) ;
27- redis . set ( "articles:all" , response , {
28- ex : 60 ,
29- } ) ;
30- return response ;
39+ // Store cache as JSON so we can retrieve a typed array later
40+ try {
41+ await redis . set ( "articles:all" , JSON . stringify ( response ) , {
42+ ex : 60 ,
43+ } ) ;
44+ } catch ( err ) {
45+ console . warn ( "Failed to set articles cache" , err ) ;
46+ }
47+ return response as unknown as ArticleList [ ] ;
3148}
3249
50+ export type ArticleWithAuthor = {
51+ id : number ;
52+ title : string ;
53+ content : string ;
54+ createdAt : string ;
55+ imageUrl ?: string | null ;
56+ author : string | null ;
57+ } ;
58+
3359export async function getArticleById ( id : number ) {
3460 const response = await db
3561 . select ( {
@@ -43,5 +69,6 @@ export async function getArticleById(id: number) {
4369 . from ( articles )
4470 . where ( eq ( articles . id , id ) )
4571 . leftJoin ( usersSync , eq ( articles . authorId , usersSync . id ) ) ;
46- return response [ 0 ] ? response [ 0 ] : null ;
72+ // Cast the DB response to the shape we selected above.
73+ return response [ 0 ] ? ( response [ 0 ] as unknown as ArticleWithAuthor ) : null ;
4774}
0 commit comments