8000 refactor/ Refatorado a Listagem de Posts. · lostcode-dev/lostcode-blog@db4aec6 · GitHub
[go: up one dir, main page]

Skip to content

Commit db4aec6

Browse files
committed
refactor/ Refatorado a Listagem de Posts.
1 parent 7047361 commit db4aec6

File tree

3 files changed

+171
-78
lines changed

3 files changed

+171
-78
lines changed

src/helpers/util.ts

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
import { RichText } from 'prismic-dom';
2+
3+
export const calcTimeOfRead = (post) => {
4+
const num_words = RichText.asText(post.data.content)?.split(' ').length;
5+
const num_imgs = 1;
6+
let height_imgs = 0;
7+
for (let i = 0; i < num_imgs; i++) {
8+
height_imgs += (i <= 9) ? 12 - i : 3;
9+
}
10+
const seconds = (num_words / 265 * 60) + height_imgs;
11+
return Math.round(seconds / 60);
12+
}
13+
14+
export const dateToPtbr = (date) => {
15+
return new Date(date).toLocaleDateString('pt-BR',
16+
{
17+
day: '2-digit',
18+
month: '2-digit',
19+
year: 'numeric'
20+
})
21+
}
22+
23+
export const getTag = (post) => {
24+
return post.data?.tags ? RichText.asText(post.data.tags) : ''
25+
}
26+
27+
28+
export const getImgUrl = (post) => {
29+
return post.data.image.url ?? ''
30+
}
31+
32+
export const getTitle = (post) => {
33+
return RichText.asText(post.data.title)
34+
}
35+
36+
export const getUid = (post) => {
37+
return post.uid ?? ''
38+
}
39+
40+
export const isToContinue = (text, limit = 200) => {
41+
return text.length > limit;
42+
}
43+
44+
export const getPreviewText = (post, flag = false) => {
45+
const excerpt = post.data.content.find(content => content.type === 'paragraph')?.text ?? '';
46+
const toBeContinue = isToContinue(excerpt, 200) ? '...' : '';
47+
48+
const previewText = flag ? excerpt.slice(0, 600) : excerpt.slice(0, 200);
49+
50+
return `${previewText}${toBeContinue}`;
51+
}

src/pages/posts/index.tsx

Lines changed: 24 additions & 55 deletions
setCurrentPage(currentPage + 1);
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,8 @@
11
import { GetStaticProps } from 'next';
2-
import { getPrismicClient, listPostPrismic } from '../../services/prismic';
2+
import { GET_STATIC_POST, LIST_POST_PRISMIC, PARAMS_DAFAULT_PRISMIC, SEARCH_LIST_POST_PRISMIC } from '../../services/prismic';
33
import { Search, ButtonScrollTop, Tag } from '../../components';
4+
import { calcTimeOfRead, dateToPtbr, getImgUrl, getPreviewText, getTag, getTitle, getUid } from '../../helpers/util';
45
import styles from './styles.module.scss';
5-
import Prismic from '@prismicio/client';
6-
import { RichText } from 'prismic-dom';
76
import { useState } from 'react';
87
import InfiniteScroll from 'react-infinite-scroll-component';
98
import Head from 'next/head';
@@ -24,46 +23,24 @@ interface PostsProps {
2423
allPosts: Post[];
2524
}
2625

27-
const pageSize = 4;
28-
const fetch = 'template-post.title,template-post.content,template-post.image,template-post.tags';
29-
const q = '[at(document.type,"template-post")]';
30-
3126
const handlerPosts = (posts) => {
3227
let countPost = 0;
3328
return posts.map(post => {
3429
countPost++;
35-
const excerpt = post.data.content.find(content => content.type === 'paragraph')?.text ?? '';
36-
const isMultipleFour = countPost % 4 === 0;
37-
const timeOfRead = calcTimeOfRead(post)
38-
const previewText = isMultipleFour ? excerpt.slice(0, 600) : excerpt.slice(0, 200);
30+
const isMultiple = countPost % PARAMS_DAFAULT_PRISMIC.pageSize === 0;
31+
3932
return {
40-
slug: post.uid,
41-
title: RichText.asText(post.data.title),
42-
excerpt: excerpt.length > 200 ? `${previewText}...` : '',
43-
image: post.data.image.url ?? '',
44-
tag: post.data?.tags ? RichText.asText(post.data.tags) : '',
45-
timeOfRead,
46-
updatedAt: new Date(post.last_publication_date).toLocaleDateString('pt-BR',
47-
{
48-
day: '2-digit',
49-
month: '2-digit',
50-
year: 'numeric'
51-
})
33+
slug: getUid(post),
34+
title: getTitle(post),
35+
excerpt: getPreviewText(post, isMultiple),
36+
image: getImgUrl(post),
37+
tag: getTag(post),
38+
timeOfRead: calcTimeOfRead(post),
39+
updatedAt: dateToPtbr(post.last_publication_date),
5240
}
5341
})
5442
}
5543

56-
const calcTimeOfRead = (post) => {
57-
const num_words = RichText.asText(post.data.content)?.split(' ').length;
58-
const num_imgs = 1;
59-
let height_imgs = 0;
60-
for(let i = 0; i < num_imgs; i++) {
61-
height_imgs += (i <= 9) ? 12 - i : 3;
62-
}
63-
const seconds = (num_words / 265 * 60) + height_imgs;
64-
return Math.round(seconds/60);
65-
}
66-
6744
export default function Posts({ allPosts }: PostsProps) {
6845
const [currentPage, setCurrentPage] = useState(2);
6946
const [posts, setPosts] = useState(allPosts);
@@ -73,13 +50,17 @@ export default function Posts({ allPosts }: PostsProps) {
7350

7451
const getMorePost = async () => {
7552
if (loadingSearch) return;
76-
const params = { currentPage, pageSize, fetch, q };
77-
params.q += search ? '[fulltext(document,"' + search + '")]' : '';
7853

79-
const response = await listPostPrismic(params);
54+
let response = null;
55+
if (search) {
56+
response = await SEARCH_LIST_POST_PRISMIC({ currentPage }, search)
57+
} else {
58+
response = await LIST_POST_PRISMIC({ currentPage })
59+
}
60+
8061
const postsResponse = handlerPosts(response.results);
8162

82-
if (!response.results_size) {
63+
if (!response?.results_size) {
8364
setHasMore(false);
8465
} else {
8566
@@ -89,10 +70,8 @@ export default function Posts({ allPosts }: PostsProps) {
8970

9071
const searchPosts = async (searchText) => {
9172
setLoadingSearch(true);
92-
const params = { currentPage: 1, pageSize, fetch, q };
93-
params.q += searchText ? '[fulltext(document,"' + searchText + '")]' : '';
9473

95-
const response = await listPostPrismic(params);
74+
const response = await SEARCH_LIST_POST_PRISMIC({ currentPage: 1 }, searchText);
9675
const postsResponse = handlerPosts(response.results);
9776

9877
setHasMore(!!response.results_size);
@@ -143,7 +122,7 @@ export default function Posts({ allPosts }: PostsProps) {
143122
alt={post.title}
144123
layout="fill"
145124
objectFit="cover"
146-
>
125+
>
147126
</Image>
148127
</div>
149128
<Link href={`/posts/${post.slug}`} key={post.slug}>
@@ -152,7 +131,7 @@ export default function Posts({ allPosts }: PostsProps) {
152131
<time>{post.updatedAt}</time>
153132
<div>
154133
<Image src="/images/icons/book.png" width={20} height={20} alt="livro aberto" />
155-
<span>{post.timeOfRead} min</span></div>
134+
<span>{post.timeOfRead} min</span></div>
156135
<Tag value={post.tag}></Tag>
157136
</div>
158137
<strong>{post.title}</strong>
@@ -184,18 +163,8 @@ export default function Posts({ allPosts }: PostsProps) {
184163
}
185164

186165
export const getStaticProps: GetStaticProps = async () => {
187-
const prismic = getPrismicClient();
188-
189-
const response = await prismic.query<any>(
190-
[Prismic.predicates.at('document.type', 'template-post')],
191-
{
192-
page: 1,
193-
fetch: fetch.split(','),
194-
pageSize,
195-
orderings: '[document.last_publication_date desc]'
196-
},
197-
)
198-
const allPosts = handlerPosts(response.results);
166+
const response = GET_STATIC_POST();
167+
const allPosts = handlerPosts(response);
199168

200169
return {
201170
props: {

src/services/prismic.ts

Lines changed: 96 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -6,12 +6,36 @@ const ACCESS_TOKEN = encodeURIComponent(env.PRISMIC_ACCESS_TOKEN);
66

77
type Params = {
88
currentPage: number;
9-
pageSize: number;
10-
fetch: string;
11-
q: string;
9+
pageSize?: number;
10+
fetch?: string;
11+
q?: string;
1212
}
1313

14-
export function getPrismicClient(req?: unknown) {
14+
export const PARAMS_DAFAULT_PRISMIC = {
15+
pageSize: 4,
16+
fetch: 'template-post.title,template-post.content,template-post.image,template-post.tags',
17+
q: '[at(document.type,"template-post")]',
18+
order: 'last_publication_date',
19+
20+
}
21+
22+
export async function GET_STATIC_POST() {
23+
const prismic = GET_PRISMIC_CLIENT();
24+
25+
const response = await prismic.query<any>(
26+
[Prismic.predicates.at('document.type', 'template-post')],
27+
{
28+
page: 1,
29+
fetch: PARAMS_DAFAULT_PRISMIC.fetch.split(','),
30+
pageSize: PARAMS_DAFAULT_PRISMIC.pageSize,
31+
orderings: `[document.${PARAMS_DAFAULT_PRISMIC.order} desc]`
32+
},
33+
)
34+
35+
return response.results
36+
}
37+
38+
export function GET_PRISMIC_CLIENT(req?: unknown) {
1539
return Prismic.client(
1640
process.env.PRISMIC_END_PONT,
1741
{
@@ -21,36 +45,85 @@ export function getPrismicClient(req?: unknown) {
2145
)
2246
}
2347

24-
async function getRef() {
48+
async function GET_REF() {
2549
try {
26-
console.log(ACCESS_TOKEN)
27-
const responseRef = await fetch(`${PRISMIC_END_PONT}?access_token=${ACCESS_TOKEN}`)
50+
const URL_GET_REF = `${PRISMIC_END_PONT}?access_token=${ACCESS_TOKEN}`
51+
const response = await fetch(URL_GET_REF)
2852
.then((response) => response.json());
29-
return encodeURIComponent(responseRef.refs[0].ref);
53+
return encodeURIComponent(response.refs[0].ref);
3054
} catch (error) {
31-
console.log('getRef', error);
55+
console.log('GET_REF', error);
3256
return false;
3357
}
3458
}
3559

36-
export async function listPostPrismic(data?: Params) {
60+
export async function LIST_POST_PRISMIC(data?: Params) {
61+
const ref = await GET_REF();
62+
if(!ref) {
63+
return false;
64+
}
65+
3766
try D7AE {
38-
const q = "q=" + encodeURIComponent(`[${data.q}]`);
39-
const fetchParams = encodeURIComponent(`fetch=[${data.fetch}]`);
40-
const pageSize = `pageSize=${data.pageSize}`;
41-
const page = `page=${data.currentPage}`;
42-
const order = `orderings=${encodeURIComponent('[document.last_publication_date desc]')}`;
67+
const params = {
68+
q: getQueryEncoded(PARAMS_DAFAULT_PRISMIC.q),
69+
fetch: getFetchEncoded(PARAMS_DAFAULT_PRISMIC.fetch),
70+
order: getOrderEncoded(PARAMS_DAFAULT_PRISMIC.order),
71+
pageSize: `pageSize=${PARAMS_DAFAULT_PRISMIC.pageSize}`,
72+
page: `page=${data.currentPage}`,
73+
ref: `ref=${ref}`
74+
}
75+
76+
const response = await fetch(toMountUrl(params)).then((response) => response.json());
77+
return response;
78+
} catch (error) {
79+
console.log('LIST_POST_PRISMIC', error);
80+
return false
81+
}
82+
}
4383

44-
const resp = await getRef();
45-
if(!resp) return false;
46-
const ref = encodeURIComponent(resp);
84+
export async function SEARCH_LIST_POST_PRISMIC(data: Params, search: string) {
85+
const ref = await GET_REF();
86+
if(!ref) {
87+
return false;
88+
}
4789

48-
const url = `${PRISMIC_END_PONT}/documents/search?ref=${ref}&access_token=${ACCESS_TOKEN}&${q}&${fetchParams}&${pageSize}&${page}&${order}`;
49-
50-
const response = await fetch(url).then((response) => response.json());
90+
try {
91+
const params = {
92+
q: getQueryEncoded(PARAMS_DAFAULT_PRISMIC.q, search),
93+
fetch: getFetchEncoded(PARAMS_DAFAULT_PRISMIC.fetch),
94+
order: getOrderEncoded(PARAMS_DAFAULT_PRISMIC.order),
95+
pageSize: `pageSize=${PARAMS_DAFAULT_PRISMIC.pageSize}`,
96+
page: `page=${data.currentPage}`,
97+
ref: `ref=${ref}`
98+
}
99+
100+
const response = await fetch(toMountUrl(params)).then((response) => response.json());
51101
return response;
52102
} catch (error) {
53-
console.log('listPostPrismic', error);
103+
console.log('SEARCH_LIST_POST_PRISMIC', error);
54104
return false
55105
}
56-
}
106+
}
107+
108+
export const toMountUrl = (params) => {
109+
const accessToken = `access_token=${ACCESS_TOKEN}`;
110+
const urlBase = `${PRISMIC_END_PONT}/documents/search?${params.ref}&${accessToken}`;
111+
const urlParams = `&${params.q}&${params.fetch}&${params.pageSize}&${params.page}&${params.order}`;
112+
return urlBase + urlParams;
113+
}
114+
115+
export const getQueryEncoded = (q: string, search = '') => {
116+
if(search) {
117+
search = '[fulltext(document,"' + search + '")]';
118+
}
119+
120+
return "q=" + encodeURIComponent(`[${q}${search}]`);
121+
}
122+
123+
export const getFetchEncoded = (fetch: string) => {
124+
return encodeURIComponent(`fetch=[${fetch}]`);
125+
}
126+
127+
export const getOrderEncoded = (order = 'last_publication_date') => {
128+
return `orderings=${encodeURIComponent(`[document.${order} desc]`)}`;
129+
}

0 commit comments

Comments
 (0)
0