Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[TSK-45] リザルトの値を送信することができる #12

Merged
merged 19 commits into from
Jun 8, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
19 commits
Select commit Hold shift + click to select a range
598c1a4
fix: ディレクトリ名を修正した
RuiOkazaki Jun 2, 2024
29bce88
chore: `bun run gql:codegen`
RuiOkazaki Jun 2, 2024
cf66a10
fix: リレーションが型に反映されたため、フロントで扱う型からは除くように変更
RuiOkazaki Jun 2, 2024
80da7f2
feat: ゲームとゲーム内容を作成できるmutationを作成した
RuiOkazaki Jun 2, 2024
415d8cc
refactor: typecheck を type:check に変更した
RuiOkazaki Jun 2, 2024
e59b792
chore: biome の analyzer のスクリプトを追加し、check や fix は run-s で実行するように変更した
RuiOkazaki Jun 2, 2024
9a6d43b
chore: script ではなく graphql-codegen 側でコード整形をするように変更
RuiOkazaki Jun 2, 2024
92eb099
chore: `bun run gql:codegen`
RuiOkazaki Jun 2, 2024
d3dca73
chore: .editorconfig を作成
RuiOkazaki Jun 2, 2024
4a6f438
style: 空行が2つあったので修正した
RuiOkazaki Jun 2, 2024
14ac222
chore: 動作確認のために作成した query を削除した
RuiOkazaki Jun 2, 2024
713eca8
chore: mutation から id, played_at, created_at, updated_at のフィールドを削除した
RuiOkazaki Jun 2, 2024
bde4397
chore: float8, json, timestamptz, uuid の型を追加した
RuiOkazaki Jun 2, 2024
59aa046
chore: user.idをuuidから変更した
RuiOkazaki Jun 6, 2024
1e470a7
feat: アクセストークンをクライアントで使用できるようにAPI routeを実装
RuiOkazaki Jun 8, 2024
a756f85
feat: x-hasura-admin-secret の代わりに Authorization ヘッダを使う
RuiOkazaki Jun 8, 2024
ed872f3
chore: ログアウトボタンを実装
RuiOkazaki Jun 8, 2024
5e2bf64
feat: ゲーム結果をAPIに送信する
RuiOkazaki Jun 8, 2024
dd63f86
fix: `graphql-codegen`で使用されている環境変数が古いものだったので修正
RuiOkazaki Jun 8, 2024
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions .editorconfig
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
root = true

[*]
charset = utf-8
indent_style = space
indent_size = 2
trim_trailing_whitespace = true
end_of_line = lf
insert_final_newline = true
2 changes: 1 addition & 1 deletion .env.local.template
Original file line number Diff line number Diff line change
Expand Up @@ -4,5 +4,5 @@ AUTH0_ISSUER_BASE_URL=''
AUTH0_CLIENT_ID=''
AUTH0_CLIENT_SECRET=''

HASURA_GRAPHQL_URL=''
NEXT_PUBLIC_HASURA_GRAPHQL_URL=''
HASURA_GRAPHQL_ADMIN_SECRET=''
2 changes: 0 additions & 2 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,6 @@ jobs:
uses: oven-sh/setup-bun@v1
- name: Install dependencies
run: bun install
- name: Run Typecheck
run: bun run typecheck
- name: Run Check
run: bun run check
- name: Run Test
Expand Down
1 change: 1 addition & 0 deletions app/api/access-token/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export { GET } from '@/_shared/api/access-token';
2 changes: 1 addition & 1 deletion lefthook.yml
Original file line number Diff line number Diff line change
Expand Up @@ -8,4 +8,4 @@ pre-push:
commands:
check:
glob: "*.{js,ts,cjs,mjs,d.cts,d.mts,jsx,tsx,json,jsonc}"
run: bun typecheck && bun test && bunx biome check --no-errors-on-unmatched --files-ignore-unknown=true {pushed_files}
run: bun type:check && bun test && bunx biome check --no-errors-on-unmatched --files-ignore-unknown=true {pushed_files}
12 changes: 8 additions & 4 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -12,13 +12,17 @@
"test:watch": "vitest watch",
"coverage": "vitest run --coverage",
"fix": "run-s *:fix",
"lint:fix": "biome lint --apply-unsafe ./",
"format:fix": "biome format ./ --write",
"check": "biome check ./",
"typecheck": "tsc --noEmit",
"analyzer:fix": "biome check --apply ./",
"lint:fix": "biome lint --apply-unsafe ./",
"check": "run-s *:check",
"format:check": "biome format ./",
"analyzer:check": "biome check ./",
"lint:check": "biome lint ./",
"type:check": "tsc --noEmit",
"lefthook:sync": "lefthook install",
"add:component": "bunx shadcn-ui@latest add",
"gql:codegen": "graphql-codegen --config ./src/_shared/lib/gql-codegen/api/config.ts && bun format:fix && bun lint:fix"
"gql:codegen": "graphql-codegen --config ./src/_shared/lib/gql-codegen/api/config.ts"
},
"dependencies": {
"@auth0/nextjs-auth0": "^3.5.0",
Expand Down
9 changes: 0 additions & 9 deletions src/_entities/darts-position/api/get-darts-positions.graphql

This file was deleted.

13 changes: 13 additions & 0 deletions src/_entities/game/api/insert-game-session-with-throws.graphql
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
mutation InsertGameSessionWithThrows($gameSession: game_sessions_insert_input!) {
insert_game_sessions_one(object: $gameSession) {
game_type_id
rate_80
rate_100
score_summary
user_id
throws {
id
position_id
}
}
}
24 changes: 24 additions & 0 deletions src/_entities/game/api/insert-game-session-with-throws.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
import type { DartsHitHistory } from '@/_entities/score/model/types';
import { graphqlSdk } from '@/_shared/lib/gql-codegen';

type InsertGameSessionWithThrowsArgs = {
gameTypeId: number;
throws: (DartsHitHistory | undefined)[];
};

export const insertGameSessionWithThrows = async ({
gameTypeId,
throws,
}: InsertGameSessionWithThrowsArgs) => {
return graphqlSdk.InsertGameSessionWithThrows({
gameSession: {
game_type_id: gameTypeId,
rate_80: 1,
rate_100: 1,
score_summary: '{}',
throws: {
data: throws.map(t => ({ position_id: t?.id ?? null })),
},
},
});
};
5 changes: 3 additions & 2 deletions src/_entities/score/model/types.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import type { Darts_Positions } from '@/_shared/lib/gql-codegen/api/generated/graphql';
import type { Darts_Positions_Max_Fields } from '@/_shared/lib/gql-codegen/api/generated/graphql';

export type DartsPosition = Darts_Positions;
// MEMO: リレーションを取り除いた型定義を使用している
export type DartsPosition = Darts_Positions_Max_Fields;
export type DartsHitHistory = DartsPosition | null;
export type DartsRound = [DartsHitHistory?, DartsHitHistory?, DartsHitHistory?];
export type DartsRoundsHistory = Array<DartsRound>;
18 changes: 16 additions & 2 deletions src/_pages/game-play/ui/screen/screen.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
'use client';

import { insertGameSessionWithThrows } from '@/_entities/game/api/insert-game-session-with-throws';
import { useConnectDartsliveHome } from '@/_features/connect-dartsboard';
import { pagesPath } from '@/_shared/lib/pathpida';
import { Button } from '@/_shared/ui/button';
Expand Down Expand Up @@ -68,9 +69,22 @@ export default function Game() {

useEffect(() => {
if (Number(difficulty) <= currentSBullCount + currentDBullCount * 2) {
router.push(pagesPath.game.result.$url().pathname);
(async () => {
const response = await insertGameSessionWithThrows({
gameTypeId: 10,
throws: dartsRoundsHistory.flat(),
});
if (response.insert_game_sessions_one)
router.push(pagesPath.game.result.$url().pathname);
})();
}
}, [currentSBullCount, currentDBullCount, difficulty, router]);
}, [
currentSBullCount,
currentDBullCount,
difficulty,
router,
dartsRoundsHistory,
]);

return (
<main className='h-full p-4'>
Expand Down
3 changes: 3 additions & 0 deletions src/_pages/home/ui/screen/screen.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,9 @@ export default function Home() {
<Button asChild>
<Link href={pagesPath.game.$url()}>Play Game</Link>
</Button>
<Button asChild>
<Link href='/api/auth/logout'>Logout</Link>
</Button>
</div>
</div>
<Tabs defaultValue='overview' className='space-y-4'>
Expand Down
15 changes: 15 additions & 0 deletions src/_shared/api/access-token/api-route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import { getAccessToken } from '@auth0/nextjs-auth0';
import { NextResponse } from 'next/server';

export const GET = async () => {
const { accessToken } = await getAccessToken();

if (accessToken === undefined) {
return NextResponse.json(
{ error: 'Access token not found' },
{ status: 401 },
);
}

return NextResponse.json({ accessToken }, { status: 200 });
};
24 changes: 24 additions & 0 deletions src/_shared/api/access-token/get-access-token.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
import type {
AccessTokenResponse,
ErrorResponse,
} from '@/_shared/api/access-token/type';

export const getAccessToken = async (): Promise<
AccessTokenResponse | ErrorResponse
> => {
const response = await fetch('/api/access-token', {
next: {
revalidate: 60 * 60,
},
});

if (response.status === 200) {
return response.json() as Promise<AccessTokenResponse>;
}

if (response.status === 401) {
return response.json() as Promise<ErrorResponse>;
}

return { error: 'Internal Server Error' };
};
2 changes: 2 additions & 0 deletions src/_shared/api/access-token/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
export { GET } from './api-route';
export { getAccessToken } from './get-access-token';
7 changes: 7 additions & 0 deletions src/_shared/api/access-token/type.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
export type AccessTokenResponse = {
accessToken: string;
};

export type ErrorResponse = {
error: string;
};
19 changes: 16 additions & 3 deletions src/_shared/lib/gql-codegen/api/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,16 @@ import type { CodegenConfig } from '@graphql-codegen/cli';

const config: CodegenConfig = {
overwrite: true,
hooks: {
afterOneFileWrite: [
'bun run format:fix',
'bun run analyzer:fix',
'bun run lint:fix',
],
},
schema: [
{
[process.env.HASURA_GRAPHQL_URL ?? '']: {
[process.env.NEXT_PUBLIC_HASURA_GRAPHQL_URL ?? '']: {
headers: {
'x-hasura-admin-secret':
process.env.HASURA_GRAPHQL_ADMIN_SECRET ?? '',
Expand All @@ -14,7 +21,7 @@ const config: CodegenConfig = {
],
documents: ['src/**/*.tsx', 'src/**/*.ts', 'src/**/*.graphql'],
generates: {
'src/shared/lib/gql-codegen/api/generated/': {
'src/_shared/lib/gql-codegen/api/generated/': {
preset: 'client',
config: {
gqlTagName: 'graphql',
Expand All @@ -30,9 +37,15 @@ const config: CodegenConfig = {
defaultScalarType: 'unknown',
enumsAsTypes: true,
useTypeImports: true,
scalars: {
float8: 'number',
json: 'string',
timestamptz: 'string',
uuid: 'string',
},
},
},
'src/shared/lib/gql-codegen/api/generated/sdk.ts': {
'src/_shared/lib/gql-codegen/api/generated/sdk.ts': {
plugins: [
{
add: {
Expand Down
8 changes: 4 additions & 4 deletions src/_shared/lib/gql-codegen/api/generated/gql.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,8 @@ import * as types from './graphql';
* Therefore it is highly recommended to use the babel or swc plugin for production.
*/
const documents = {
'query GetDartsPositions {\n darts_positions {\n id\n multiplier\n score\n position_code\n sector\n }\n}':
types.GetDartsPositionsDocument,
'mutation InsertGameSessionWithThrows($gameSession: game_sessions_insert_input!) {\n insert_game_sessions_one(object: $gameSession) {\n game_type_id\n rate_80\n rate_100\n score_summary\n user_id\n throws {\n id\n position_id\n }\n }\n}':
types.InsertGameSessionWithThrowsDocument,
};

/**
Expand All @@ -35,8 +35,8 @@ export function graphql(source: string): unknown;
* The graphql function is used to parse GraphQL queries into a document that can be used by GraphQL clients.
*/
export function graphql(
source: 'query GetDartsPositions {\n darts_positions {\n id\n multiplier\n score\n position_code\n sector\n }\n}',
): (typeof documents)['query GetDartsPositions {\n darts_positions {\n id\n multiplier\n score\n position_code\n sector\n }\n}'];
source: 'mutation InsertGameSessionWithThrows($gameSession: game_sessions_insert_input!) {\n insert_game_sessions_one(object: $gameSession) {\n game_type_id\n rate_80\n rate_100\n score_summary\n user_id\n throws {\n id\n position_id\n }\n }\n}',
): (typeof documents)['mutation InsertGameSessionWithThrows($gameSession: game_sessions_insert_input!) {\n insert_game_sessions_one(object: $gameSession) {\n game_type_id\n rate_80\n rate_100\n score_summary\n user_id\n throws {\n id\n position_id\n }\n }\n}'];

export function graphql(source: string) {
return (documents as any)[source] ?? {};
Expand Down
Loading