Skip to content

Commit

Permalink
refactor: 回答送信ページでnextjsのapiを使うように
Browse files Browse the repository at this point in the history
  • Loading branch information
rito528 committed Mar 17, 2024
1 parent 8ebae18 commit 7cd6779
Show file tree
Hide file tree
Showing 2 changed files with 52 additions and 12 deletions.
35 changes: 35 additions & 0 deletions src/app/api/questions/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
'use server';

import { BACKEND_SERVER_URL } from '@/env';
import { getCachedToken } from '@/features/user/api/mcToken';
import { NextRequest, NextResponse } from 'next/server';
import { redirectByResponse } from '../util/responseOrErrorResponse';

export async function GET(req: NextRequest) {
const token = await getCachedToken();
if (!token) {
return NextResponse.redirect('/');
}

const searchParms = req.nextUrl.searchParams;
const formId = searchParms.get('formId');
if (!formId) {
return NextResponse.redirect('/badrequest');
}

const response = await fetch(
`${BACKEND_SERVER_URL}/forms/${formId}/questions`,
{
method: 'GET',
headers: {
Accept: 'application/json',
Authorization: `Bearer ${token}`,
},
cache: 'no-cache',
}
);

redirectByResponse(response);

return NextResponse.json(await response.json());
}
29 changes: 17 additions & 12 deletions src/app/forms/[formId]/page.tsx
Original file line number Diff line number Diff line change
@@ -1,19 +1,24 @@
import { isRight } from 'fp-ts/lib/Either';
import { redirectOrDoNothing } from '@/app/error/RedirectByErrorResponse';
import { getFormQuestions } from '@/features/form/api/form';
'use client';

import AnswerForm from '@/features/form/components/AnswerForm';
import { getCachedToken } from '@/features/user/api/mcToken';
import { FormQuestion } from '@/features/form/types/formSchema';
import useSWR from 'swr';
import { redirect } from 'next/navigation';

const Home = async ({ params }: { params: { formId: number } }) => {
const token = (await getCachedToken()) ?? '';
const questions = await getFormQuestions(params.formId, token);
const Home = ({ params }: { params: { formId: number } }) => {
const fetcher = (url: string) => fetch(url).then((res) => res.json());
const { data: questions, isLoading } = useSWR<FormQuestion[]>(
`http://localhost:3000/api/questions?formId=${params.formId}`,
fetcher
);

if (isRight(questions)) {
return <AnswerForm questions={questions.right} formId={params.formId} />;
} else {
redirectOrDoNothing(questions);
return <></>;
if (!isLoading && !questions) {
redirect('/');
} else if (!questions) {
return null;
}

return <AnswerForm questions={questions} formId={params.formId} />;
};

export default Home;

0 comments on commit 7cd6779

Please sign in to comment.