@@ -4,25 +4,25 @@ import { Article } from './Article'
44import { ArticlesRepository } from './ArticlesRepository'
55
66export class SanityArticlesRepository implements ArticlesRepository {
7- async findMany ( ) : Promise < Article [ ] > {
8- const articleResponseSchema = z . array (
9- z . object ( {
10- title : z . string ( ) ,
11- description : z . string ( ) ,
12- author : z . object ( {
13- name : z . string ( ) ,
14- } ) ,
15- mainImage : z . object ( {
16- asset : z . object ( {
17- path : z . string ( ) ,
18- } ) ,
19- } ) ,
20- slug : z . object ( {
21- current : z . string ( ) ,
22- } ) ,
23- publishedAt : z . string ( ) ,
7+ private readonly articleSchema = z . object ( {
8+ title : z . string ( ) ,
9+ description : z . string ( ) ,
10+ author : z . object ( {
11+ name : z . string ( ) ,
12+ } ) ,
13+ mainImage : z . object ( {
14+ asset : z . object ( {
15+ path : z . string ( ) ,
2416 } ) ,
25- )
17+ } ) ,
18+ slug : z . object ( {
19+ current : z . string ( ) ,
20+ } ) ,
21+ publishedAt : z . string ( ) ,
22+ } )
23+
24+ async findMany ( ) : Promise < Article [ ] > {
25+ const articleResponseSchema = z . array ( this . articleSchema )
2626 const CONTENT_QUERY = `*[_type == "post"] {
2727 ...,
2828 author->,
@@ -52,4 +52,42 @@ export class SanityArticlesRepository implements ArticlesRepository {
5252 } as Article
5353 } )
5454 }
55+
56+ async findBySlug ( slug : string ) {
57+ const query = `*[_type == "post" && slug.current == $slug][0] {
58+ ...,
59+ author->,
60+ mainImage {
61+ ...,
62+ asset->
63+ },
64+ categories[]->,
65+ body
66+ }`
67+
68+ const params = { slug }
69+
70+ try {
71+ const contentResponse = await client . fetch ( query , params )
72+ console . log ( 'Artigo:' , contentResponse )
73+ const article = this . articleSchema . parse ( contentResponse )
74+ return {
75+ id : article . slug . current ,
76+ title : article . title ,
77+ description :
78+ article . description . length > 120
79+ ? article . description . substring ( 0 , 120 ) . concat ( '...' )
80+ : article . description ,
81+ author : article . author . name ,
82+ createdAt : article . publishedAt ,
83+ imageUrl : 'https://cdn.sanity.io/' . concat ( article . mainImage . asset . path ) ,
84+ slug : article . slug . current ,
85+ } as Article
86+ } catch ( error ) {
87+ console . error ( 'Erro ao buscar artigo:' , error )
88+ return null
89+ }
90+ }
5591}
92+
93+ export const articlesRepository = new SanityArticlesRepository ( )
0 commit comments