Skip to content

Commit

Permalink
Merge pull request #284 from GiganticMinecraft/refactor/arrow-func
Browse files Browse the repository at this point in the history
Use arrow functions
  • Loading branch information
rito528 authored Oct 9, 2023
2 parents 1c9bad8 + c0d0d7b commit 0a6204f
Show file tree
Hide file tree
Showing 17 changed files with 176 additions and 91 deletions.
22 changes: 15 additions & 7 deletions .eslintrc.json
Original file line number Diff line number Diff line change
@@ -1,13 +1,21 @@
{
"extends": ["next/core-web-vitals", "plugin:import/recommended", "plugin:import/typescript", "prettier"],
"plugins": ["@typescript-eslint", "unused-imports"],
"extends": ["next/core-web-vitals", "plugin:@typescript-eslint/recommended-type-checked", "plugin:import/recommended", "plugin:import/typescript", "prettier"],
"plugins": ["@typescript-eslint", "unused-imports", "prefer-arrow"],
"parser": "@typescript-eslint/parser",
"parserOptions": {
"ecmaVersion": "latest",
"project": "./tsconfig.json",
"sourceType": "module"
},
"rules": {
"react/function-component-definition": ["error", { "namedComponents": "arrow-function" }],
"unused-imports/no-unused-imports": "error",
"unused-imports/no-unused-vars": [
"error",
{ "vars": "all", "varsIgnorePattern": "^_", "args": "after-used", "argsIgnorePattern": "^_" }
],
"@typescript-eslint/no-unused-vars": "off",
"unused-imports/no-unused-imports": "error",
"unused-imports/no-unused-vars": [
"error",
{ "vars": "all", "varsIgnorePattern": "^_", "args": "after-used", "argsIgnorePattern": "^_" }
],
"@typescript-eslint/no-misused-promises": ["error", { "checksVoidReturn": false }],
// See: https://zenn.dev/teppeis/articles/2023-04-typescript-5_0-verbatim-module-syntax
"@typescript-eslint/consistent-type-imports": "error",
"@typescript-eslint/no-import-type-side-effects": "error",
Expand Down
5 changes: 3 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -35,13 +35,14 @@
"@types/node": "18.17.1",
"@types/react": "18.2.19",
"@types/react-dom": "18.2.7",
"@typescript-eslint/eslint-plugin": "^6.7.0",
"@typescript-eslint/parser": "^6.7.0",
"@typescript-eslint/eslint-plugin": "^6.7.4",
"@typescript-eslint/parser": "^6.7.4",
"eslint": "8.46.0",
"eslint-config-next": "13.4.13",
"eslint-config-prettier": "^9.0.0",
"eslint-import-resolver-typescript": "^3.6.0",
"eslint-plugin-import": "^2.28.1",
"eslint-plugin-prefer-arrow": "^1.2.3",
"eslint-plugin-unused-imports": "^3.0.0",
"prettier": "^3.0.1",
"typescript": "5.1.6",
Expand Down
25 changes: 10 additions & 15 deletions src/api/form.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,12 +16,11 @@ export const getForms = async (token: string) => {
},
cache: 'no-cache',
});
const formsJson = await response.json();

return formsSchema.parse(formsJson);
return formsSchema.parse(await response.json());
};

export async function getForm(formId: number, token: string): Promise<Form> {
export const getForm = async (formId: number, token: string): Promise<Form> => {
const response = await fetch(`http://localhost:9000/forms/${formId}`, {
method: 'GET',
headers: {
Expand All @@ -30,16 +29,15 @@ export async function getForm(formId: number, token: string): Promise<Form> {
},
cache: 'no-cache',
});
const formJson = await response.json();

return formSchema.parse(formJson);
}
return formSchema.parse(await response.json());
};

export async function postAnswers(
export const postAnswers = async (
form_id: number,
answers: { question_id: number; answer: string }[],
token: string
): Promise<boolean> {
): Promise<boolean> => {
const answersJson = JSON.stringify({
uuid: '3fa85f64-5717-4562-b3fc-2c963f66afa6', //todo: user側の処理を実装したら書き換える
timestamp: new Date(),
Expand All @@ -57,18 +55,15 @@ export async function postAnswers(
});

return response.ok;
}
};

export async function getAllAnswers(token: string): Promise<BatchAnswer[]> {
export const getAllAnswers = async (token: string): Promise<BatchAnswer[]> => {
return await fetch(`http://localhost:9000/forms/answers`, {
method: 'GET',
headers: {
Accept: 'application/json',
Authorization: `Bearer ${token}`,
},
cache: 'no-cache',
}).then(async (response) => {
const batchAnswersJson = await response.json();
return batchAnswersSchema.parse(batchAnswersJson);
});
}
}).then(async (response) => batchAnswersSchema.parse(await response.json()));
};
30 changes: 18 additions & 12 deletions src/api/login.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import {
export const acquireXboxLiveToken = async (token: string) => {
const URL = 'https://user.auth.xboxlive.com/user/authenticate';

const json = await fetch(URL, {
const response = await fetch(URL, {
method: 'POST',
headers: {
Accept: 'application/json',
Expand All @@ -24,9 +24,11 @@ export const acquireXboxLiveToken = async (token: string) => {
RelyingParty: 'http://auth.xboxlive.com',
TokenType: 'JWT',
}),
}).then(async (r) => r.json());
});

const result = xboxLiveServiceTokenResponseSchema.parse(json);
const result = xboxLiveServiceTokenResponseSchema.parse(
await response.json()
);

return { token: result.Token, userHash: result.DisplayClaims.xui[0].uhs };
};
Expand All @@ -36,7 +38,7 @@ export const acquireXboxServiceSecurityToken = async ({
}: Awaited<ReturnType<typeof acquireXboxLiveToken>>) => {
const URL = 'https://xsts.auth.xboxlive.com/xsts/authorize';

const json = await fetch(URL, {
const response = await fetch(URL, {
method: 'POST',
headers: {
Accept: 'application/json',
Expand All @@ -50,9 +52,11 @@ export const acquireXboxServiceSecurityToken = async ({
RelyingParty: 'rp://api.minecraftservices.com/',
TokenType: 'JWT',
}),
}).then(async (r) => r.json());
});

const result = xboxLiveServiceTokenResponseSchema.parse(json);
const result = xboxLiveServiceTokenResponseSchema.parse(
await response.json()
);

return { token: result.Token, userHash: result.DisplayClaims.xui[0].uhs };
};
Expand All @@ -64,7 +68,7 @@ export const acquireMinecraftAccessToken = async ({
const URL =
'https://api.minecraftservices.com/authentication/login_with_xbox';

const json = await fetch(URL, {
const response = await fetch(URL, {
method: 'POST',
headers: {
Accept: 'application/json',
Expand All @@ -73,9 +77,11 @@ export const acquireMinecraftAccessToken = async ({
body: JSON.stringify({
identityToken: `XBL3.0 x=${userHash};${token}`,
}),
}).then(async (r) => r.json());
});

const result = minecraftAccessTokenResponseSchema.parse(json);
const result = minecraftAccessTokenResponseSchema.parse(
await response.json()
);

return { token: result.access_token, expires: result.expires_in };
};
Expand All @@ -85,15 +91,15 @@ export const acquireMinecraftProfile = async ({
}: Awaited<ReturnType<typeof acquireMinecraftAccessToken>>) => {
const URL = 'https://api.minecraftservices.com/minecraft/profile';

const json = await fetch(URL, {
const response = await fetch(URL, {
method: 'GET',
headers: {
Accept: 'application/json',
Authorization: `Bearer ${token}`,
},
}).then(async (r) => r.json());
});

const result = minecraftProfileResponseSchema.parse(json);
const result = minecraftProfileResponseSchema.parse(await response.json());

return result;
};
Expand Down
6 changes: 4 additions & 2 deletions src/app/admin/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import DashboardMenu from '@/components/dashboardMenu';
import NavBar from '@/components/NavBar';
import styles from '../page.module.css';

export default async function Home() {
const Home = async () => {
const token = getCachedToken() ?? '';
const answers = await getAllAnswers(token);
return (
Expand All @@ -15,4 +15,6 @@ export default async function Home() {
<DataTable answers={answers} />
</main>
);
}
};

export default Home;
6 changes: 4 additions & 2 deletions src/app/forms/[formId]/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,11 @@ import { getForm } from '@/api/form';
import { getCachedToken } from '@/api/mcToken';
import AnswerForm from '@/components/AnswerForm';

export default async function Home({ params }: { params: { formId: number } }) {
const Home = async ({ params }: { params: { formId: number } }) => {
const token = getCachedToken() ?? '';
const form = await getForm(params.formId, token);

return <AnswerForm form={form} />;
}
};

export default Home;
6 changes: 4 additions & 2 deletions src/app/forms/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,10 @@ import { getForms } from '@/api/form';
import { getCachedToken } from '@/api/mcToken';
import FormList from '@/components/FormList';

export default async function Home() {
const Home = async () => {
const token = getCachedToken() ?? '';
const forms = await getForms(token);
return <FormList forms={forms} />;
}
};

export default Home;
6 changes: 4 additions & 2 deletions src/app/layout.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ export const metadata: Metadata = {
description: '整地鯖公式のポータルサイトです。',
};

export default function RootLayout({ children }: { children: ReactNode }) {
const RootLayout = ({ children }: { children: ReactNode }) => {
return (
<html lang="ja">
<body className={inter.className}>
Expand All @@ -32,4 +32,6 @@ export default function RootLayout({ children }: { children: ReactNode }) {
</body>
</html>
);
}
};

export default RootLayout;
6 changes: 4 additions & 2 deletions src/app/page.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
import Menu from '@/components/Menu';

export default function Home() {
const Home = () => {
return <Menu />;
}
};

export default Home;
14 changes: 9 additions & 5 deletions src/components/AnswerForm.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ import {
import { useState } from 'react';
import { useForm } from 'react-hook-form';
import { postAnswers } from '@/api/form';
import { getCachedToken } from '@/api/mcToken';
import { Link } from './link';
import type { Form, FormQuestion } from '@/schemas/formSchema';

Expand All @@ -45,7 +46,7 @@ const Item = styled(Paper)(({ theme }) => ({
width: '100%',
}));

export default function AnswerForm({ form }: Props) {
const AnswerForm = ({ form }: Props) => {
const [isSubmitted, toggleIsSubmitted] = useState(false);
const [selectedValues, setSelectedValues] = useState<{ [x: string]: string }>(
{}
Expand All @@ -63,7 +64,7 @@ export default function AnswerForm({ form }: Props) {

const onSubmit = async (data: IFormInput) => {
console.info(data);
const formAnswers = Object.entries(data).flatMap(function ([key, values]) {
const formAnswers = Object.entries(data).flatMap(([key, values]) => {
// Note:
// ここで型をstringかどうか判定しているのは、valuesに複数の値が入っていた場合にmapを使って
// 一つのquestion_idとanswerに分離したいという理由がある。
Expand Down Expand Up @@ -92,7 +93,8 @@ export default function AnswerForm({ form }: Props) {
}
});

if (await postAnswers(form.id, formAnswers)) {
const token = getCachedToken() ?? '';
if (await postAnswers(form.id, formAnswers, token)) {
toggleIsSubmitted(true);
reset();
setSelectedValues({});
Expand Down Expand Up @@ -124,7 +126,7 @@ export default function AnswerForm({ form }: Props) {
onChange={(event) => {
setSelectedValues({
...selectedValues,
[questionId]: event.target.value as string,
[questionId]: event.target.value,
});
}}
renderValue={() =>
Expand Down Expand Up @@ -278,4 +280,6 @@ export default function AnswerForm({ form }: Props) {
</Box>
);
}
}
};

export default AnswerForm;
14 changes: 8 additions & 6 deletions src/components/FormList.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ extend(timezone);
extend(utc);
dayjs.tz.setDefault('Asia/Tokyo');

function formatResponsePeriod(startAt: string | null, endAt: string | null) {
const formatResponsePeriod = (startAt: string | null, endAt: string | null) => {
if (startAt != null && endAt != null) {
const formatString = 'YYYY年MM月DD日 HH時mm分';

Expand All @@ -37,9 +37,9 @@ function formatResponsePeriod(startAt: string | null, endAt: string | null) {
} else {
return `回答期限なし`;
}
}
};

function EachForm({ form }: { form: Form }) {
const EachForm = ({ form }: { form: Form }) => {
return (
<Box sx={{ minWidth: 275 }}>
<Card variant="outlined">
Expand All @@ -62,7 +62,7 @@ function EachForm({ form }: { form: Form }) {
</Card>
</Box>
);
}
};

const Item = styled(Paper)(({ theme }) => ({
backgroundColor: theme.palette.mode === 'dark' ? '#1A2027' : '#fff',
Expand All @@ -76,7 +76,7 @@ interface Props {
forms: Form[];
}

export default function FormList({ forms }: Props) {
const FormList = ({ forms }: Props) => {
return (
<Box sx={{ width: '100%' }}>
<Stack spacing={2}>
Expand All @@ -99,4 +99,6 @@ export default function FormList({ forms }: Props) {
</Stack>
</Box>
);
}
};

export default FormList;
6 changes: 4 additions & 2 deletions src/components/Menu.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ const Item = styled(Button)(({ theme }) => ({
color: theme.palette.text.secondary,
}));

export default function Menu() {
const Menu = () => {
return (
<Box sx={{ width: '100%' }}>
<Stack spacing={2}>
Expand All @@ -34,4 +34,6 @@ export default function Menu() {
</Stack>
</Box>
);
}
};

export default Menu;
6 changes: 4 additions & 2 deletions src/components/NavBar.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import { SigninButton } from './SigninButton';
import { SignoutButton } from './SignoutButton';
import { UnauthenticatedTemplate } from './UnauthenticatedTemplate';

export default function NavBar() {
const NavBar = () => {
return (
<Box sx={{ flexGrow: 1 }}>
<AppBar position="fixed">
Expand Down Expand Up @@ -35,4 +35,6 @@ export default function NavBar() {
</AppBar>
</Box>
);
}
};

export default NavBar;
Loading

0 comments on commit 0a6204f

Please sign in to comment.