fetcher with API type

This commit is contained in:
Aarni Halinen
2022-05-17 23:30:45 +03:00
parent 0e285c1ecc
commit 1f1595a1e8
2 changed files with 23 additions and 16 deletions
+6 -2
View File
@@ -19,7 +19,7 @@ export enum APIPath {
AUTH_TOKEN_VERIFY = "/api-token-verify",
}
type API = {
export type API = {
path: APIPath;
urlParams?: {
id?: string | number;
@@ -123,4 +123,8 @@ export const deleteBackendAPI = async <ResponseType>({
return callBackendAPI<undefined, ResponseType>(path, urlParams, queryParams, "DELETE", headers, undefined);
};
export const fetcher = <ResponseType>(path: APIPath, options: { limit?: number, auth?: boolean }) => getBackendAPI<ResponseType>({ path, queryParams: { limit: options.limit }, authenticated: options.auth });
export const fetcher = <ResponseType>({
path, urlParams, queryParams, authenticated,
}: API) => getBackendAPI<ResponseType>({
path, urlParams, queryParams, authenticated,
});
+17 -14
View File
@@ -3,29 +3,32 @@ import { NextPage, GetStaticProps } from "next";
import Head from "next/head";
import useSWR from "swr";
import Event from "@models/Event";
import EventApi from "@api/eventApi";
import Post from "@models/Feed";
import FeedApi from "@api/feedApi";
import FrontPageView from "@views/FrontPage/FrontPageView";
import PageWrapper from "@views/common/PageWrapper";
import { fetcher, APIPath } from "@api/backend";
import { fetcher, API, APIPath } from "@api/backend";
const eventOptions = {
limit: 4,
const eventApi: API = {
path: APIPath.EVENTS,
queryParams: {
limit: 4,
},
};
const feedOptions = {
limit: 4,
const feedApi: API = {
path: APIPath.FEED,
queryParams: {
limit: 4,
},
};
interface InitialProps {
initialEvents: Event[];
initialFeed: Post[];
}
const FrontPage: NextPage<InitialProps> = ({ initialEvents, initialFeed }) => {
const { data: events } = useSWR<Event[]>([APIPath.EVENTS, eventOptions], fetcher, { fallbackData: initialEvents });
const { data: feed } = useSWR<Post[]>([APIPath.FEED, feedOptions], fetcher, { fallbackData: initialFeed });
const { data: events } = useSWR<Event[]>(eventApi, fetcher, { fallbackData: initialEvents });
const { data: feed } = useSWR<Post[]>(feedApi, fetcher, { fallbackData: initialFeed });
return (
<>
@@ -40,12 +43,12 @@ const FrontPage: NextPage<InitialProps> = ({ initialEvents, initialFeed }) => {
};
export const getStaticProps: GetStaticProps<InitialProps> = async () => {
const initialEvents = await EventApi.getEvents(eventOptions);
const initialFeed = await FeedApi.getFeed(feedOptions);
const initialEvents = fetcher<Event[]>(eventApi);
const initialFeed = fetcher<Post[]>(feedApi);
return {
props: {
initialEvents,
initialFeed,
initialEvents: await initialEvents,
initialFeed: await initialFeed,
},
revalidate: 10,
};