handle api response and errors

This commit is contained in:
amirhouieh 2023-05-08 16:38:42 +02:00 committed by Jinho Jang
parent 76aeba9fdf
commit 0babbafd35
4 changed files with 75 additions and 54 deletions

View File

@ -1,5 +1,4 @@
import axios, { Axios } from 'axios'
import { UnbodyExploreArgs } from './unbody.types'
export class UnbodyClient {
public client: Axios

View File

@ -3,10 +3,7 @@ import { ArticleLayout } from '@/layouts/ArticleLayout'
import { ReactNode } from 'react'
import ArticleContainer from '@/containers/ArticleContainer'
import { UnbodyGoogleDoc, UnbodyImageBlock } from '@/lib/unbody/unbody.types'
import {
getAllArticlePostSlugs,
getArticlePost,
} from '@/services/unbody.service'
import api from '@/services/unbody.service'
import { ArticlePostData } from '@/types/data.types'
type ArticleProps = {
@ -21,13 +18,11 @@ export const getStaticProps = async ({ params }: GetStaticPropsContext) => {
notFound: true,
}
}
const article = await getArticlePost(remoteId as string)
const { data: article, errors } = await api.getArticlePost(remoteId as string)
return {
props: {
data: article,
error: !!article,
error: errors,
},
}
}
@ -45,9 +40,11 @@ const ArticlePage = (props: ArticleProps) => {
}
export async function getStaticPaths() {
const posts = await getAllArticlePostSlugs()
const { data: posts, errors } = await api.getAllArticlePostSlugs()
return {
paths: posts.map((post) => ({ params: { remoteId: `${post.remoteId}` } })),
paths: errors
? []
: posts.map((post) => ({ params: { remoteId: `${post.remoteId}` } })),
fallback: true,
}
}

View File

@ -1,7 +1,7 @@
import { PostDataProps } from '@/components/Post/Post'
import PostsDemo from '@/components/Post/PostsDemo'
import { UnbodyGoogleDoc, UnbodyImageBlock } from '@/lib/unbody/unbody.types'
import { getHomepagePosts } from '@/services/unbody.service'
import api from '@/services/unbody.service'
import { GetStaticProps } from 'next'
type Props = {
@ -18,14 +18,7 @@ export default function Home({ posts }: Props) {
}
export const getStaticProps = async () => {
let posts: Partial<UnbodyGoogleDoc>[] = []
let error = null
try {
posts = await getHomepagePosts()
} catch (e) {
error = JSON.stringify(e)
}
const { data: posts, errors } = await api.getHomepagePosts()
return {
props: {
@ -39,7 +32,7 @@ export const getStaticProps = async () => {
? { coverImage: post.blocks![0] as UnbodyImageBlock }
: {}),
})),
error,
errors,
},
}
}

View File

@ -13,49 +13,81 @@ import { getAllPostsSlugQuery } from '@/queries/getPostsSlugs'
const { UNBODY_API_KEY, UNBODY_LPE_PROJECT_ID } = process.env
const unbody = new UnbodyClient(
UNBODY_API_KEY as string,
UNBODY_LPE_PROJECT_ID as string,
)
type HomepagePost = Pick<
UnbodyGoogleDoc,
'title' | 'summary' | 'tags' | 'modifiedAt' | 'subtitle' | 'blocks'
>
export const getHomepagePosts = (): Promise<HomepagePost[]> => {
return unbody
.request<UnbodyGraphQlResponseGoogleDoc>(getHomePagePostsQuery())
.then(({ data }) => data.Get.GoogleDoc)
type ApiResponse<T> = {
data: T
errors: any
}
export const getAllArticlePostSlugs = (): Promise<{ remoteId: string }[]> => {
console.log(getAllPostsSlugQuery())
return unbody
.request<UnbodyGraphQlResponseGoogleDoc>(getAllPostsSlugQuery())
.then(({ data }) => data.Get.GoogleDoc)
}
class ApiService extends UnbodyClient {
constructor() {
super(UNBODY_API_KEY as string, UNBODY_LPE_PROJECT_ID as string)
}
export const getArticlePost = (id: string): Promise<UnbodyGoogleDoc> => {
const query = getArticlePostQuery({
where: {
path: ['remoteId'],
operator: UnbodyGraphQl.Filters.WhereOperatorEnum.Equal,
valueString: id,
},
})
return unbody
.request<UnbodyGraphQlResponseGoogleDoc>(getArticlePostQuery())
.then(({ data }) => {
const article = data.Get.GoogleDoc[0]
handleResponse = <T>(
data: T | null = null,
errors: any = null,
): ApiResponse<T> => {
if (errors || !data) {
console.log(errors)
return {
...article,
toc: JSON.parse(
article.toc as string,
) as Array<UnbodyGraphQl.Fragments.TocItem>,
data: null as any,
errors: JSON.stringify(errors),
}
}
return {
data,
errors,
}
}
getHomepagePosts = (): Promise<ApiResponse<HomepagePost[]>> => {
return this.request<UnbodyGraphQlResponseGoogleDoc>(getHomePagePostsQuery())
.then(({ data }) => {
if (!data) return this.handleResponse([], 'No data')
return this.handleResponse(data.Get.GoogleDoc)
})
.catch((e) => this.handleResponse([], e))
}
getAllArticlePostSlugs = (): Promise<ApiResponse<{ remoteId: string }[]>> => {
return this.request<UnbodyGraphQlResponseGoogleDoc>(getAllPostsSlugQuery())
.then(({ data }) => {
if (!data) return this.handleResponse([], 'No data')
return this.handleResponse(data.Get.GoogleDoc)
})
.catch((e) => this.handleResponse([], e))
}
getArticlePost = (
id: string,
): Promise<ApiResponse<UnbodyGoogleDoc | null>> => {
const query = getArticlePostQuery({
where: {
path: ['remoteId'],
operator: UnbodyGraphQl.Filters.WhereOperatorEnum.Equal,
valueString: id,
},
})
return this.request<UnbodyGraphQlResponseGoogleDoc>(query)
.then(({ data }) => {
if (!data) return this.handleResponse(null, 'No data')
const article = data.Get.GoogleDoc[0]
return this.handleResponse({
...article,
toc: JSON.parse(
article.toc as string,
) as Array<UnbodyGraphQl.Fragments.TocItem>,
})
})
.catch((e) => this.handleResponse(null, e))
}
}
export default unbody
const api = new ApiService()
export default api