-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat: easy api routing with loading, fetch hook and typings
- Loading branch information
1 parent
4bc647e
commit 02f2e6a
Showing
9 changed files
with
446 additions
and
0 deletions.
There are no files selected for viewing
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,42 @@ | ||
import { serverSideRequest } from '@/src/services/api-services/server-side'; | ||
import { AxiosError } from 'axios'; | ||
import { NextApiRequest, NextApiResponse } from 'next'; | ||
import { createRouter } from 'next-connect'; | ||
|
||
const router = createRouter<NextApiRequest, NextApiResponse>(); | ||
|
||
const routerHandler = router.handler({ | ||
onError: (err, _: NextApiRequest, res: NextApiResponse) => { | ||
console.error(err); | ||
res.status(500).send({ statusCode: 500, message: 'Internal Server Error' }); | ||
}, | ||
onNoMatch: (_: NextApiRequest, res: NextApiResponse) => { | ||
res.status(405).send({ statusCode: 405, message: 'Method not allowed' }); | ||
}, | ||
}); | ||
|
||
router.post(async (req: NextApiRequest, res: NextApiResponse) => { | ||
try { | ||
const response = await serverSideRequest(req, req.body); | ||
res.setHeader('Set-Cookie', response.headers['set-cookie'] ? response.headers['set-cookie'] : []); | ||
res.status(200).send(response.data); | ||
} catch (err) { | ||
if (!(err instanceof AxiosError)) throw err; | ||
const msg = { | ||
request: { | ||
url: err.config?.url, | ||
}, | ||
status: err.response?.status, | ||
statusText: err.response?.statusText, | ||
body: JSON.stringify(err.response?.data), | ||
}; | ||
|
||
console.error(msg); | ||
|
||
const statusCode = err.response?.status ?? 500; | ||
|
||
res.status(statusCode).send(err.response?.data ?? { statusCode, message: 'Internal Server Error' }); | ||
} | ||
}); | ||
|
||
export default routerHandler; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,7 @@ | ||
export enum ErrorCode { | ||
API_ERROR = 'API_ERROR', | ||
NOT_FOUND = 'NOT_FOUND', | ||
NOT_ALLOWED = 'NOT_ALLOWED', | ||
WRONG_CREDENTIALS = 'WRONG_CREDENTIALS', | ||
ALREADY_EXISTS = 'ALREADY_EXISTS', | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,50 @@ | ||
import { Dispatch, SetStateAction, useEffect, useState } from 'react'; | ||
import { ErrorCode } from '../enums/error-codes.enum'; | ||
import { clientSideRequest } from '../services/api-services/client-side'; | ||
import { APIContext, APIOperation } from '../services/api-services/common'; | ||
|
||
type useFetchType = { | ||
isLoading: boolean; | ||
setIsLoading: Dispatch<SetStateAction<boolean>>; | ||
fetchDataWithLoadingTimeout: <T extends APIOperation, R = APIContext[T]['responseType']>( | ||
config: Omit<APIContext[T], 'responseType'> & { | ||
op: T; | ||
}, | ||
) => Promise< | ||
| { | ||
success: true; | ||
data: R; | ||
} | ||
| { success: false; errorCode: ErrorCode } | ||
>; | ||
}; | ||
|
||
const useFetch = (loadingTimeout = 100): useFetchType => { | ||
const [isLoading, setIsLoading] = useState<boolean>(false); | ||
let timeout: ReturnType<typeof setTimeout>; | ||
|
||
useEffect(() => { | ||
return () => clearInterval(timeout); | ||
}); | ||
|
||
const fetchDataWithLoadingTimeout = async <T extends APIOperation, R = APIContext[T]['responseType']>( | ||
config: Omit<APIContext[T], 'responseType'> & { op: T }, | ||
): Promise<{ success: true; data: R } | { success: false; errorCode: ErrorCode }> => { | ||
timeout = setTimeout(() => { | ||
setIsLoading(true); | ||
}, loadingTimeout); | ||
|
||
const res = await clientSideRequest(config); | ||
|
||
clearInterval(timeout); | ||
setIsLoading(false); | ||
|
||
// eslint-disable-next-line | ||
// @ts-ignore | ||
return res; | ||
}; | ||
|
||
return { isLoading, setIsLoading, fetchDataWithLoadingTimeout }; | ||
}; | ||
|
||
export default useFetch; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,35 @@ | ||
import { ErrorCode } from '@/src/enums/error-codes.enum'; | ||
import axios, { AxiosError } from 'axios'; | ||
import { APIContext, APIOperation } from './common'; | ||
|
||
const clientSideRequest = async <T extends APIOperation, R = APIContext[T]['responseType']>( | ||
options: Omit<APIContext[T], 'responseType'> & { op: T }, | ||
): Promise<{ success: true; data: R } | { success: false; errorCode: ErrorCode }> => { | ||
if (typeof window === 'undefined') throw new Error('Request can only be performed on the client side'); | ||
|
||
try { | ||
const { data } = await axios.post<R>( | ||
'/api', | ||
{ | ||
...options, | ||
}, | ||
{ withCredentials: true }, | ||
); | ||
|
||
return { success: true, data }; | ||
} catch (err) { | ||
if (!(err instanceof AxiosError)) return { success: false, errorCode: ErrorCode.API_ERROR }; | ||
|
||
if (typeof err.response?.data !== 'object') return { success: false, errorCode: ErrorCode.API_ERROR }; | ||
|
||
if (typeof err.response.data.error !== 'string') return { success: false, errorCode: ErrorCode.API_ERROR }; | ||
|
||
const errorCode = err.response.data.error; | ||
|
||
if (!Object.values(ErrorCode).includes(errorCode)) return { success: false, errorCode: ErrorCode.API_ERROR }; | ||
|
||
return { success: false, errorCode }; | ||
} | ||
}; | ||
|
||
export { clientSideRequest }; |
Oops, something went wrong.