Browse Source

*some linting and redisigned history and leaderboard with tables

master
nicolas-arnaud 2 years ago
parent
commit
447a88704c
  1. 12
      back/volume/src/auth/auth.controller.ts
  2. 3
      back/volume/src/auth/session.serializer.ts
  3. 19
      back/volume/src/main.ts
  4. 3
      back/volume/src/pong/entity/result.entity.ts
  5. 3
      back/volume/src/users/entity/user.entity.ts
  6. 2
      back/volume/src/users/users.controller.ts
  7. 16
      back/volume/src/users/users.service.ts
  8. 41
      front/volume/src/components/Leaderboard.svelte
  9. 50
      front/volume/src/components/MatchHistory.svelte

12
back/volume/src/auth/auth.controller.ts

@ -13,26 +13,26 @@ export class AuthController {
@Get('inReturn')
@UseGuards(FtOauthGuard)
@Redirect('http://' + process.env.HOST + ':' + process.env.FRONT_PORT + '/')
@Redirect(`http://${process.env.HOST}:${process.env.FRONT_PORT}`)
ftAuthCallback (
@Res({ passthrough: true }) response: Response,
@Req() request: Request
) {
): any {
console.log('cookie:', request.cookies['connect.sid'])
response.cookie('connect.sid', request.cookies['connect.sid'])
}
@Get('profile')
@UseGuards(AuthenticatedGuard)
profile (@FtUser() user: Profile) {
profile (@FtUser() user: Profile): any {
return { user }
}
@Get('out')
@Redirect('http://' + process.env.HOST + ':' + process.env.FRONT_PORT + '/')
logOut (@Req() req: Request) {
@Redirect(`http://${process.env.HOST}:${process.env.FRONT_PORT}`)
logOut (@Req() req: Request): any {
req.logOut(function (err) {
if (err) return err
if (err != null) return err
})
}
}

3
back/volume/src/auth/session.serializer.ts

@ -4,6 +4,7 @@ import { type Profile } from 'passport-42'
@Injectable()
export class SessionSerializer extends PassportSerializer {
// useless constructor?
constructor () {
super()
}
@ -18,7 +19,7 @@ export class SessionSerializer extends PassportSerializer {
deserializeUser (
payload: Profile,
done: (err: Error | null, user: Profile) => void
) {
): any {
done(null, payload)
}
}

19
back/volume/src/main.ts

@ -1,18 +1,20 @@
import { WsAdapter } from '@nestjs/platform-ws'
import { Logger } from '@nestjs/common'
import { InternalServerErrorException, Logger } from '@nestjs/common'
import { NestFactory } from '@nestjs/core'
import { AppModule } from './app.module'
import * as session from 'express-session'
import * as passport from 'passport'
import { type NestExpressApplication } from '@nestjs/platform-express'
import * as cookieParser from 'cookie-parser'
import { Response } from 'express'
async function bootstrap () {
async function bootstrap (): Promise<void> {
const logger = new Logger()
const app = await NestFactory.create<NestExpressApplication>(AppModule)
const port = process.env.BACK_PORT!
const port =
process.env.BACK_PORT && process.env.BACK_PORT !== ''
? +process.env.BACK_PORT
: 3001
const cors = {
origin: ['http://localhost:80', 'http://localhost', '*'],
methods: 'GET, HEAD, PUT, PATCH, POST, DELETE, OPTIONS',
@ -25,7 +27,10 @@ async function bootstrap () {
session({
resave: false,
saveUninitialized: false,
secret: process.env.JWT_SECRET!
secret:
process.env.JWT_SECRET && process.env.JWT_SECRET !== ''
? process.env.JWT_SECRET
: 'secret'
})
)
app.use(cookieParser())
@ -36,4 +41,6 @@ async function bootstrap () {
await app.listen(port)
logger.log(`Application listening on port ${port}`)
}
bootstrap()
bootstrap().catch((e) => {
throw new InternalServerErrorException(e)
})

3
back/volume/src/pong/entity/result.entity.ts

@ -3,8 +3,7 @@ import {
PrimaryGeneratedColumn,
Column,
ManyToMany,
CreateDateColumn,
JoinTable
CreateDateColumn
} from 'typeorm'
import User from 'src/users/entity/user.entity'

3
back/volume/src/users/entity/user.entity.ts

@ -4,8 +4,7 @@ import {
Column,
OneToMany,
ManyToMany,
JoinTable,
UpdateDateColumn
JoinTable
} from 'typeorm'
import { randomUUID } from 'crypto'

2
back/volume/src/users/users.controller.ts

@ -137,7 +137,7 @@ export class UsersController {
@FtUser() profile: Profile,
@Param('id', ParseIntPipe) id: number
): Promise<NotFoundException | null | undefined> {
if (profile.id == id) {
if (profile.id === id) {
throw new BadRequestException("You can't invit yourself.")
}
return await this.usersService.invit(profile.id, id)

16
back/volume/src/users/users.service.ts

@ -59,7 +59,7 @@ export class UsersService {
const newUser = this.usersRepository.create(userData)
return await this.usersRepository.save(newUser)
} catch (err) {
throw new Error(`Error creating ${err} user ${err.message}`)
throw new Error(`Error creating user ${err}`)
}
}
@ -130,10 +130,10 @@ export class UsersService {
async getRank (ftId: number): Promise<number> {
const leader = await this.getLeader()
return leader.findIndex((user) => user.ftId == ftId)
return leader.findIndex((user) => user.ftId === ftId)
}
async invit (ftId: number, targetFtId: number) {
async invit (ftId: number, targetFtId: number): Promise<any> {
const user = await this.usersRepository.findOne({
where: { ftId },
relations: {
@ -144,7 +144,7 @@ export class UsersService {
if (user == null) {
return new NotFoundException(`Error: user id ${ftId} isn't in our db.`)
}
if (user.friends.findIndex((friend) => friend.ftId === targetFtId) != -1) {
if (user.friends.findIndex((friend) => friend.ftId === targetFtId) !== -1) {
return null
}
const target = await this.usersRepository.findOne({
@ -162,18 +162,18 @@ export class UsersService {
const id = user.followers.findIndex(
(follower) => follower.ftId === targetFtId
)
if (id != -1) {
if (id !== -1) {
console.log(
`Friend relation complete between ${user.username} and ${target.username}`
)
user.friends.push(target)
if (user.ftId != target.ftId) target.friends.push(user)
if (user.ftId !== target.ftId) target.friends.push(user)
user.followers.slice(id, 1)
this.usersRepository.save(user)
await this.usersRepository.save(user)
} else {
console.log(`You asked ${target.username} to be your friend.`)
target.followers.push(user)
}
this.usersRepository.save(target)
await this.usersRepository.save(target)
}
}

41
front/volume/src/components/Leaderboard.svelte

@ -3,6 +3,7 @@
username: string;
wins: number;
looses: number;
matchs: number;
winrate: number;
rank: number;
}
@ -14,22 +15,37 @@
<div class="overlay">
<div class="history" on:click|stopPropagation on:keydown|stopPropagation>
<div>
{#if leaderboard.length > 0}
<h2>Leaderboard</h2>
<table>
<thead>
<tr>
<th colspan="5">Leaderboard</th>
</tr>
</thead>
<tbody>
<tr>
<td>Rank</td>
<td>Usernames</td>
<td>Wins</td>
<td>Matchs</td>
<td>Winrates</td>
</tr>
{#each leaderboard.slice(0, 10) as player}
<li>
<span>{player.username}</span>
<span>{player.wins} - {player.looses} - {player.winrate}%wins</span>
<span> | rank #{player.rank}</span>
</li>
<tr>
<td>{player.rank}</td>
<td>{player.username}</td>
<td>{player.wins}</td>
<td>{player.matchs}</td>
<td>{player.winrate}%</td>
</tr>
{/each}
</tbody>
</table>
{:else}
<p>No Players to display</p>
{/if}
</div>
</div>
</div>
<style>
.overlay {
@ -51,5 +67,14 @@
border-radius: 5px;
padding: 1rem;
width: 300px;
display: flex;
justify-content: center;
}
td {
border: 1px solid #333;
text-align: center;
max-width: 12ch;
overflow: hidden;
}
</style>

50
front/volume/src/components/MatchHistory.svelte

@ -11,8 +11,9 @@
export let matches: Array<Match> = [];
function displayDate(str: string) {
const splitT = str.split("T");
const splitdot = splitT[1].split(".");
return splitT[0] + "-" + splitdot[0];
const splitDate = splitT[0].split('-')
const splitDot = splitT[1].split(".");
return `${splitDate[1]}/${splitDate[2]}-${splitDot[0]}`;
}
</script>
@ -20,24 +21,27 @@
<div class="history" on:click|stopPropagation on:keydown|stopPropagation>
<div>
{#if matches.length > 0}
<h2>Last 10 monkey games</h2>
<table>
<thead>
<tr>
<th colspan="3">Last 10 monkey games</th>
</tr>
</thead>
<tbody>
<tr>
<td>Date</td>
<td>Players</td>
<td>Scores</td>
</tr>
{#each matches.slice(0, 10) as match}
<li>
<span
>{displayDate(match.date.toString())}: {match.players[0].username}
{match.scores[0]} - {match.scores[1]}
{match.players[1].username}</span
>
<!---
{#if match.points > 0}
<span>+{match.points}</span>
{:else}
<span>{match.points}</span>
{/if}
<span>MP | rank #{match.rank}</span>
--->
</li>
<tr>
<td>{displayDate(match.date.toString())}</td>
<td>{match.players[0].username}<br>{match.players[1].username}</td>
<td>{match.score[0]}<br>{match.score[1]}</td>
</tr>
{/each}
</tbody>
</table>
{:else}
<p>No matches to display</p>
{/if}
@ -65,5 +69,15 @@
border-radius: 5px;
padding: 1rem;
width: 300px;
display:flex;
justify-content: center;
}
td {
border:1px solid #111;
text-align: center;
max-width: 15ch;
overflow: hidden;
}
</style>

Loading…
Cancel
Save