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') @Get('inReturn')
@UseGuards(FtOauthGuard) @UseGuards(FtOauthGuard)
@Redirect('http://' + process.env.HOST + ':' + process.env.FRONT_PORT + '/') @Redirect(`http://${process.env.HOST}:${process.env.FRONT_PORT}`)
ftAuthCallback ( ftAuthCallback (
@Res({ passthrough: true }) response: Response, @Res({ passthrough: true }) response: Response,
@Req() request: Request @Req() request: Request
) { ): any {
console.log('cookie:', request.cookies['connect.sid']) console.log('cookie:', request.cookies['connect.sid'])
response.cookie('connect.sid', request.cookies['connect.sid']) response.cookie('connect.sid', request.cookies['connect.sid'])
} }
@Get('profile') @Get('profile')
@UseGuards(AuthenticatedGuard) @UseGuards(AuthenticatedGuard)
profile (@FtUser() user: Profile) { profile (@FtUser() user: Profile): any {
return { user } return { user }
} }
@Get('out') @Get('out')
@Redirect('http://' + process.env.HOST + ':' + process.env.FRONT_PORT + '/') @Redirect(`http://${process.env.HOST}:${process.env.FRONT_PORT}`)
logOut (@Req() req: Request) { logOut (@Req() req: Request): any {
req.logOut(function (err) { 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() @Injectable()
export class SessionSerializer extends PassportSerializer { export class SessionSerializer extends PassportSerializer {
// useless constructor?
constructor () { constructor () {
super() super()
} }
@ -18,7 +19,7 @@ export class SessionSerializer extends PassportSerializer {
deserializeUser ( deserializeUser (
payload: Profile, payload: Profile,
done: (err: Error | null, user: Profile) => void done: (err: Error | null, user: Profile) => void
) { ): any {
done(null, payload) done(null, payload)
} }
} }

19
back/volume/src/main.ts

@ -1,18 +1,20 @@
import { WsAdapter } from '@nestjs/platform-ws' import { WsAdapter } from '@nestjs/platform-ws'
import { Logger } from '@nestjs/common' import { InternalServerErrorException, Logger } from '@nestjs/common'
import { NestFactory } from '@nestjs/core' import { NestFactory } from '@nestjs/core'
import { AppModule } from './app.module' import { AppModule } from './app.module'
import * as session from 'express-session' import * as session from 'express-session'
import * as passport from 'passport' import * as passport from 'passport'
import { type NestExpressApplication } from '@nestjs/platform-express' import { type NestExpressApplication } from '@nestjs/platform-express'
import * as cookieParser from 'cookie-parser' import * as cookieParser from 'cookie-parser'
import { Response } from 'express'
async function bootstrap () { async function bootstrap (): Promise<void> {
const logger = new Logger() const logger = new Logger()
const app = await NestFactory.create<NestExpressApplication>(AppModule) 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 = { const cors = {
origin: ['http://localhost:80', 'http://localhost', '*'], origin: ['http://localhost:80', 'http://localhost', '*'],
methods: 'GET, HEAD, PUT, PATCH, POST, DELETE, OPTIONS', methods: 'GET, HEAD, PUT, PATCH, POST, DELETE, OPTIONS',
@ -25,7 +27,10 @@ async function bootstrap () {
session({ session({
resave: false, resave: false,
saveUninitialized: 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()) app.use(cookieParser())
@ -36,4 +41,6 @@ async function bootstrap () {
await app.listen(port) await app.listen(port)
logger.log(`Application listening on port ${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, PrimaryGeneratedColumn,
Column, Column,
ManyToMany, ManyToMany,
CreateDateColumn, CreateDateColumn
JoinTable
} from 'typeorm' } from 'typeorm'
import User from 'src/users/entity/user.entity' import User from 'src/users/entity/user.entity'

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

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

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

@ -137,7 +137,7 @@ export class UsersController {
@FtUser() profile: Profile, @FtUser() profile: Profile,
@Param('id', ParseIntPipe) id: number @Param('id', ParseIntPipe) id: number
): Promise<NotFoundException | null | undefined> { ): Promise<NotFoundException | null | undefined> {
if (profile.id == id) { if (profile.id === id) {
throw new BadRequestException("You can't invit yourself.") throw new BadRequestException("You can't invit yourself.")
} }
return await this.usersService.invit(profile.id, id) 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) const newUser = this.usersRepository.create(userData)
return await this.usersRepository.save(newUser) return await this.usersRepository.save(newUser)
} catch (err) { } 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> { async getRank (ftId: number): Promise<number> {
const leader = await this.getLeader() 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({ const user = await this.usersRepository.findOne({
where: { ftId }, where: { ftId },
relations: { relations: {
@ -144,7 +144,7 @@ export class UsersService {
if (user == null) { if (user == null) {
return new NotFoundException(`Error: user id ${ftId} isn't in our db.`) 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 return null
} }
const target = await this.usersRepository.findOne({ const target = await this.usersRepository.findOne({
@ -162,18 +162,18 @@ export class UsersService {
const id = user.followers.findIndex( const id = user.followers.findIndex(
(follower) => follower.ftId === targetFtId (follower) => follower.ftId === targetFtId
) )
if (id != -1) { if (id !== -1) {
console.log( console.log(
`Friend relation complete between ${user.username} and ${target.username}` `Friend relation complete between ${user.username} and ${target.username}`
) )
user.friends.push(target) 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) user.followers.slice(id, 1)
this.usersRepository.save(user) await this.usersRepository.save(user)
} else { } else {
console.log(`You asked ${target.username} to be your friend.`) console.log(`You asked ${target.username} to be your friend.`)
target.followers.push(user) 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; username: string;
wins: number; wins: number;
looses: number; looses: number;
matchs: number;
winrate: number; winrate: number;
rank: number; rank: number;
} }
@ -14,21 +15,36 @@
<div class="overlay"> <div class="overlay">
<div class="history" on:click|stopPropagation on:keydown|stopPropagation> <div class="history" on:click|stopPropagation on:keydown|stopPropagation>
<div>
{#if leaderboard.length > 0} {#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} {#each leaderboard.slice(0, 10) as player}
<li> <tr>
<span>{player.username}</span> <td>{player.rank}</td>
<span>{player.wins} - {player.looses} - {player.winrate}%wins</span> <td>{player.username}</td>
<span> | rank #{player.rank}</span> <td>{player.wins}</td>
</li> <td>{player.matchs}</td>
<td>{player.winrate}%</td>
</tr>
{/each} {/each}
</tbody>
</table>
{:else} {:else}
<p>No Players to display</p> <p>No Players to display</p>
{/if} {/if}
</div> </div>
</div>
</div> </div>
<style> <style>
@ -51,5 +67,14 @@
border-radius: 5px; border-radius: 5px;
padding: 1rem; padding: 1rem;
width: 300px; width: 300px;
display: flex;
justify-content: center;
}
td {
border: 1px solid #333;
text-align: center;
max-width: 12ch;
overflow: hidden;
} }
</style> </style>

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

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

Loading…
Cancel
Save