Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
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
6 changes: 6 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,12 @@ Main packages :

Nextjs App Router project structure based

## Subjects

- Server side cache invalidation :
- https://galadrim.fr/blog/nextjs-app-router-le-cache-et-ses-dangers
- https://www.answeroverflow.com/m/1103789268679282709

## Links

- Nextjs tutorial base : https://nextjs.org/learn/basics/navigate-between-pages/client-side
Expand Down
2 changes: 2 additions & 0 deletions src/app/api/higher-scores/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,8 @@ export async function GET() {
const scoresOrdered = Scores.getScoresParsedAndOrdered(scoresBase).slice(0, NUMITEMS)
const scores = await addUserNameToArrayById(scoresOrdered)

// console.log('GET route - result -->', scores)

if (!scores) {
throw new APIError('Find userName by score request failed', {
cause: { api: 'Higher score GET', values: 'scores' },
Expand Down
1 change: 1 addition & 0 deletions src/app/api/score-ranking/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ export async function POST(request: NextRequest) {

try {
const requestData = await request.json()
console.log('requestdata ', requestData)
if (!requestData.score) {
throw new APIError('Undefined request body informations', {
cause: { api: 'Score-ranking POST', values: 'user' },
Expand Down
75 changes: 38 additions & 37 deletions src/app/page.tsx
Original file line number Diff line number Diff line change
@@ -1,52 +1,57 @@
// https://nextjs.org/docs/app/building-your-application/caching#segment-config-options
export const dynamic = 'force-dynamic'
export const revalidate = 0

import { cookies, headers } from 'next/headers'
import { Box, CircularProgress } from '@mui/material'

import { Home } from '@/components/home'
import { ScoreList } from '@/components/score-list'
import { Scores } from '@/services/scores'
import { APIError } from '@/utils/errors'
import { cookies } from 'next/headers'
import { PUZZLE_COOKIE } from '@/constants'

let server = 'http://localhost:3000'
try {
const env = process.env.NODE_ENV
const { signal } = new AbortController()

if (env == 'production') {
server = 'https://speed-puzzle-kz08m3nxu-001-817d24a7.vercel.app/'
}
} catch (error) {
console.log('ENVIRONEMENT VARIABLE - ERROR', error)
}
// const getHigherScores = async (server: string | null) => {
// try {
// if (!server) {
// throw new APIError('server url is invalid', {
// cause: { api: 'Higher score GET', values: 'scores' },
// })
// }
// const response = await fetch(`${server}api/higher-scores`, {
// signal,
// cache: 'no-store',
// next: { revalidate: 0 },
// })

const getHigherScores = async () => {
try {
const response = await fetch(`${server}/api/higher-scores`, {
method: 'GET',
cache: 'no-store',
})

if (!response) {
throw new APIError('Higher score request failed', {
cause: { api: 'Higher score GET', values: 'scores' },
})
}
const result = await response.json()
const { scores } = result
return Scores.getScoresParsedAndOrdered(scores)
} catch {
return []
}
}
// if (!response) {
// throw new APIError('Higher score request failed', {
// cause: { api: 'Higher score GET', values: 'scores' },
// })
// }
// const result = await response.json()
// // console.log('getHigherScores - result', result)
// const { scores } = result
// return Scores.getScoresParsedAndOrdered(scores)
// } catch {
// return []
// }
// }

const getPuzzleCookie = () => {
const cookieStore = cookies()
return cookieStore.get(PUZZLE_COOKIE)
}

export default async function Page() {
const recentScores = await getHigherScores()
export default function Page() {
const heads = headers()
const pathname = heads.get('x-url')
// const recentScores = await getHigherScores(pathname)
const cookie = getPuzzleCookie()

console.log('pathname', pathname)

return (
<Box
sx={{
Expand All @@ -63,11 +68,7 @@ export default async function Page() {
gap: 4,
}}
>
{recentScores ? (
<Home scores={recentScores} cookie={cookie} />
) : (
<CircularProgress color='primary' />
)}
<Home cookie={cookie} />
</Box>
)
}
28 changes: 27 additions & 1 deletion src/components/home/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,15 +7,41 @@ import { ROUTES } from '@/constants'
import { Metadata } from 'next'
import { ScoreList } from '../score-list'
import { useEffect, useState } from 'react'
import { API } from '@/services/server'

export const metadata: Metadata = {
title: 'SPEED PUZZLE - 2023',
description: 'Version - 2',
}

export const Home = ({ scores, cookie }: { scores: any[]; cookie: any }) => {
export const Home = ({ cookie }: { cookie: any }) => {
const router = useRouter()
const [userName, setUserNamme] = useState<string | undefined>()
const [scores, setScores] = useState<any[]>([])

// const getHigherScores = async () => {
// const response = await API.getHighestScores()
// if (response) {
// console.log('getHigherScores response status', response.status)
// const result = await response.json()
// // const { scores } = result
// // const scoresParsed = Scores.getScoresParsedAndOrdered(scores)
// // console.log('getHigherScores scoreParsed', scoresParsed)
// console.log('test onClick result', result)
// }
// }

useEffect(() => {
const getHigherScores = async () => {
const response = await API.getHighestScores()
if (response) {
console.log('getHigherScores response status', response.status)
const result = await response.json()
setScores(result?.scores)
}
}
getHigherScores()
}, [])

useEffect(() => {
if (cookie) {
Expand Down
23 changes: 19 additions & 4 deletions src/components/score-list/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ export const ScoreList = ({ scores }: { scores: any[] }) => {
sx={{
display: 'flex',
flexDirection: 'column',
alignContent: 'center',
width: '100%',
}}
>
{scores.map((item, index) => {
Expand All @@ -17,12 +17,27 @@ export const ScoreList = ({ scores }: { scores: any[] }) => {
sx={{
display: 'flex',
flexDirection: 'row',
alignContent: 'flex-start',
gap: 10,
}}
>
<Typography variant='h6'>{item.userName}</Typography>
<Typography variant='h6'>{item.value}</Typography>
<Typography
variant='h6'
sx={{
width: '50%',
textAlign: 'end',
}}
>
{item.userName}
</Typography>
<Typography
variant='h6'
sx={{
width: '50%',
textAlign: 'start',
}}
>
{item.value}
</Typography>
</Box>
)
})}
Expand Down
14 changes: 14 additions & 0 deletions src/middleware.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import { NextResponse, type NextRequest } from "next/server";

// https://nextjs.org/docs/app/building-your-application/routing/middleware#matcher
export const config = {
matcher: '/',
}

export async function middleware(request: NextRequest) {
return NextResponse.next({
request: {
headers: new Headers({ "x-url": request.url }),
},
});
}
7 changes: 3 additions & 4 deletions src/providers/puzzle-provider.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -94,13 +94,12 @@ export const PuzzleProvider: React.FC<Props> = ({ children }) => {

async function compareScoreWithDB() {
try {
const data = { score: state.result?.value.toString() }

if (!state.result?.value.toString()) {
if (!state?.result?.value.toString()) {
throw new Error()
// TODO conitnue to manage the error state
}
console.log('compareScoreWithDB - score :', data)
// const data = { score: state?.result?.value.toString() }
// console.log('compareScoreWithDB - score :', data)

const response = await API.currentScoreRanking(
state.result.value.toString()
Expand Down
3 changes: 1 addition & 2 deletions src/services/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,13 +12,12 @@ export class API {
}

static currentScoreRanking = async (score: string) => {
const data = { score }
return await fetch('/api/score-ranking', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(data),
body: JSON.stringify({ score }),
})
}

Expand Down