init
This commit is contained in:
2
.env.example
Normal file
2
.env.example
Normal file
@@ -0,0 +1,2 @@
|
|||||||
|
MONGODB_URI=mongodb://localhost:27017
|
||||||
|
DB_NAME=rick_and_morty
|
2
.gitignore
vendored
Normal file
2
.gitignore
vendored
Normal file
@@ -0,0 +1,2 @@
|
|||||||
|
/target
|
||||||
|
.env
|
3126
Cargo.lock
generated
Normal file
3126
Cargo.lock
generated
Normal file
File diff suppressed because it is too large
Load Diff
22
Cargo.toml
Normal file
22
Cargo.toml
Normal file
@@ -0,0 +1,22 @@
|
|||||||
|
[package]
|
||||||
|
name = "rick-and-morty"
|
||||||
|
version = "0.1.0"
|
||||||
|
edition = "2024"
|
||||||
|
|
||||||
|
[dependencies]
|
||||||
|
anyhow = "1.0.98"
|
||||||
|
axum = { version = "0.8.4", features = ["macros"] }
|
||||||
|
dotenvy = "0.15.7"
|
||||||
|
futures-util = "0.3.31"
|
||||||
|
http = "1.3.1"
|
||||||
|
mongodb = "3.2.4"
|
||||||
|
once_cell = "1.21.3"
|
||||||
|
reqwest = { version = "0.12.22", features = ["json"] }
|
||||||
|
serde = { version = "1.0.219", features = ["derive"] }
|
||||||
|
serde_json = "1.0.140"
|
||||||
|
tokio = { version = "1.46.1", features = [] }
|
||||||
|
tower = { version = "0.5.2", features = ["util"] }
|
||||||
|
tower-http = { version = "0.6.6", features = ["cors", "fs", "trace"] }
|
||||||
|
tracing = "0.1.41"
|
||||||
|
tracing-log = "0.2.0"
|
||||||
|
tracing-subscriber = { version = "0.3.19", features = ["env-filter", "fmt"] }
|
24
Dockerfile
Normal file
24
Dockerfile
Normal file
@@ -0,0 +1,24 @@
|
|||||||
|
FROM node:latest AS frontend-builder
|
||||||
|
WORKDIR /app
|
||||||
|
COPY frontend/package*.json ./
|
||||||
|
RUN npm install
|
||||||
|
COPY frontend/ ./
|
||||||
|
RUN npm run build
|
||||||
|
|
||||||
|
FROM rust:1.87-slim AS backend-builder
|
||||||
|
WORKDIR /app
|
||||||
|
RUN apt-get update && \
|
||||||
|
apt-get install -y pkg-config libssl-dev build-essential ca-certificates
|
||||||
|
|
||||||
|
COPY src/ src/
|
||||||
|
COPY Cargo.toml Cargo.lock ./
|
||||||
|
RUN cargo build --release
|
||||||
|
|
||||||
|
FROM debian:bookworm-slim
|
||||||
|
WORKDIR /app
|
||||||
|
RUN apt-get update && apt-get install -y ca-certificates openssl && rm -rf /var/lib/apt/lists/*
|
||||||
|
COPY --from=backend-builder /app/target/release/rick-and-morty .
|
||||||
|
COPY --from=frontend-builder /app/dist ./frontend/dist
|
||||||
|
EXPOSE 8000
|
||||||
|
|
||||||
|
CMD ["./rick-and-morty"]
|
26
compose.yml
Normal file
26
compose.yml
Normal file
@@ -0,0 +1,26 @@
|
|||||||
|
services:
|
||||||
|
mongo:
|
||||||
|
image: mongo:6.0
|
||||||
|
container_name: rick_and_morty_mongo
|
||||||
|
restart: unless-stopped
|
||||||
|
ports:
|
||||||
|
- "27017:27017"
|
||||||
|
environment:
|
||||||
|
MONGO_INITDB_DATABASE: rick_and_morty
|
||||||
|
volumes:
|
||||||
|
- mongo-data:/data/db
|
||||||
|
app:
|
||||||
|
build: .
|
||||||
|
container_name: rick_and_morty_app
|
||||||
|
depends_on:
|
||||||
|
- mongo
|
||||||
|
environment:
|
||||||
|
MONGODB_URI: mongodb://mongo:27017
|
||||||
|
DB_NAME: rick_and_morty
|
||||||
|
BIND_ADDR: 0.0.0.0:8000
|
||||||
|
ports:
|
||||||
|
- "8000:8000"
|
||||||
|
restart: unless-stopped
|
||||||
|
|
||||||
|
volumes:
|
||||||
|
mongo-data:
|
24
frontend/.gitignore
vendored
Normal file
24
frontend/.gitignore
vendored
Normal file
@@ -0,0 +1,24 @@
|
|||||||
|
# Logs
|
||||||
|
logs
|
||||||
|
*.log
|
||||||
|
npm-debug.log*
|
||||||
|
yarn-debug.log*
|
||||||
|
yarn-error.log*
|
||||||
|
pnpm-debug.log*
|
||||||
|
lerna-debug.log*
|
||||||
|
|
||||||
|
node_modules
|
||||||
|
dist
|
||||||
|
dist-ssr
|
||||||
|
*.local
|
||||||
|
|
||||||
|
# Editor directories and files
|
||||||
|
.vscode/*
|
||||||
|
!.vscode/extensions.json
|
||||||
|
.idea
|
||||||
|
.DS_Store
|
||||||
|
*.suo
|
||||||
|
*.ntvs*
|
||||||
|
*.njsproj
|
||||||
|
*.sln
|
||||||
|
*.sw?
|
69
frontend/README.md
Normal file
69
frontend/README.md
Normal file
@@ -0,0 +1,69 @@
|
|||||||
|
# React + TypeScript + Vite
|
||||||
|
|
||||||
|
This template provides a minimal setup to get React working in Vite with HMR and some ESLint rules.
|
||||||
|
|
||||||
|
Currently, two official plugins are available:
|
||||||
|
|
||||||
|
- [@vitejs/plugin-react](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react) uses [Babel](https://babeljs.io/) for Fast Refresh
|
||||||
|
- [@vitejs/plugin-react-swc](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react-swc) uses [SWC](https://swc.rs/) for Fast Refresh
|
||||||
|
|
||||||
|
## Expanding the ESLint configuration
|
||||||
|
|
||||||
|
If you are developing a production application, we recommend updating the configuration to enable type-aware lint rules:
|
||||||
|
|
||||||
|
```js
|
||||||
|
export default tseslint.config([
|
||||||
|
globalIgnores(['dist']),
|
||||||
|
{
|
||||||
|
files: ['**/*.{ts,tsx}'],
|
||||||
|
extends: [
|
||||||
|
// Other configs...
|
||||||
|
|
||||||
|
// Remove tseslint.configs.recommended and replace with this
|
||||||
|
...tseslint.configs.recommendedTypeChecked,
|
||||||
|
// Alternatively, use this for stricter rules
|
||||||
|
...tseslint.configs.strictTypeChecked,
|
||||||
|
// Optionally, add this for stylistic rules
|
||||||
|
...tseslint.configs.stylisticTypeChecked,
|
||||||
|
|
||||||
|
// Other configs...
|
||||||
|
],
|
||||||
|
languageOptions: {
|
||||||
|
parserOptions: {
|
||||||
|
project: ['./tsconfig.node.json', './tsconfig.app.json'],
|
||||||
|
tsconfigRootDir: import.meta.dirname,
|
||||||
|
},
|
||||||
|
// other options...
|
||||||
|
},
|
||||||
|
},
|
||||||
|
])
|
||||||
|
```
|
||||||
|
|
||||||
|
You can also install [eslint-plugin-react-x](https://github.com/Rel1cx/eslint-react/tree/main/packages/plugins/eslint-plugin-react-x) and [eslint-plugin-react-dom](https://github.com/Rel1cx/eslint-react/tree/main/packages/plugins/eslint-plugin-react-dom) for React-specific lint rules:
|
||||||
|
|
||||||
|
```js
|
||||||
|
// eslint.config.js
|
||||||
|
import reactX from 'eslint-plugin-react-x'
|
||||||
|
import reactDom from 'eslint-plugin-react-dom'
|
||||||
|
|
||||||
|
export default tseslint.config([
|
||||||
|
globalIgnores(['dist']),
|
||||||
|
{
|
||||||
|
files: ['**/*.{ts,tsx}'],
|
||||||
|
extends: [
|
||||||
|
// Other configs...
|
||||||
|
// Enable lint rules for React
|
||||||
|
reactX.configs['recommended-typescript'],
|
||||||
|
// Enable lint rules for React DOM
|
||||||
|
reactDom.configs.recommended,
|
||||||
|
],
|
||||||
|
languageOptions: {
|
||||||
|
parserOptions: {
|
||||||
|
project: ['./tsconfig.node.json', './tsconfig.app.json'],
|
||||||
|
tsconfigRootDir: import.meta.dirname,
|
||||||
|
},
|
||||||
|
// other options...
|
||||||
|
},
|
||||||
|
},
|
||||||
|
])
|
||||||
|
```
|
BIN
frontend/bun.lockb
Executable file
BIN
frontend/bun.lockb
Executable file
Binary file not shown.
23
frontend/eslint.config.js
Normal file
23
frontend/eslint.config.js
Normal file
@@ -0,0 +1,23 @@
|
|||||||
|
import js from '@eslint/js'
|
||||||
|
import globals from 'globals'
|
||||||
|
import reactHooks from 'eslint-plugin-react-hooks'
|
||||||
|
import reactRefresh from 'eslint-plugin-react-refresh'
|
||||||
|
import tseslint from 'typescript-eslint'
|
||||||
|
import { globalIgnores } from 'eslint/config'
|
||||||
|
|
||||||
|
export default tseslint.config([
|
||||||
|
globalIgnores(['dist']),
|
||||||
|
{
|
||||||
|
files: ['**/*.{ts,tsx}'],
|
||||||
|
extends: [
|
||||||
|
js.configs.recommended,
|
||||||
|
tseslint.configs.recommended,
|
||||||
|
reactHooks.configs['recommended-latest'],
|
||||||
|
reactRefresh.configs.vite,
|
||||||
|
],
|
||||||
|
languageOptions: {
|
||||||
|
ecmaVersion: 2020,
|
||||||
|
globals: globals.browser,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
])
|
13
frontend/index.html
Normal file
13
frontend/index.html
Normal file
@@ -0,0 +1,13 @@
|
|||||||
|
<!DOCTYPE html>
|
||||||
|
<html lang="en">
|
||||||
|
<head>
|
||||||
|
<meta charset="UTF-8" />
|
||||||
|
<link rel="icon" type="image/ico" href="/favicon.ico" />
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||||
|
<title>Rick and Morty Tournament</title>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<div id="root"></div>
|
||||||
|
<script type="module" src="/src/main.tsx"></script>
|
||||||
|
</body>
|
||||||
|
</html>
|
31
frontend/package.json
Normal file
31
frontend/package.json
Normal file
@@ -0,0 +1,31 @@
|
|||||||
|
{
|
||||||
|
"name": "frontend",
|
||||||
|
"private": true,
|
||||||
|
"version": "0.0.0",
|
||||||
|
"type": "module",
|
||||||
|
"scripts": {
|
||||||
|
"dev": "vite",
|
||||||
|
"build": "tsc -b && vite build",
|
||||||
|
"lint": "eslint .",
|
||||||
|
"preview": "vite preview"
|
||||||
|
},
|
||||||
|
"dependencies": {
|
||||||
|
"@tailwindcss/vite": "^4.1.11",
|
||||||
|
"react": "^19.1.0",
|
||||||
|
"react-dom": "^19.1.0",
|
||||||
|
"tailwindcss": "^4.1.11"
|
||||||
|
},
|
||||||
|
"devDependencies": {
|
||||||
|
"@eslint/js": "^9.30.1",
|
||||||
|
"@types/react": "^19.1.8",
|
||||||
|
"@types/react-dom": "^19.1.6",
|
||||||
|
"@vitejs/plugin-react-swc": "^3.10.2",
|
||||||
|
"eslint": "^9.30.1",
|
||||||
|
"eslint-plugin-react-hooks": "^5.2.0",
|
||||||
|
"eslint-plugin-react-refresh": "^0.4.20",
|
||||||
|
"globals": "^16.3.0",
|
||||||
|
"typescript": "~5.8.3",
|
||||||
|
"typescript-eslint": "^8.35.1",
|
||||||
|
"vite": "^7.0.3"
|
||||||
|
}
|
||||||
|
}
|
BIN
frontend/public/favicon.ico
Normal file
BIN
frontend/public/favicon.ico
Normal file
Binary file not shown.
After Width: | Height: | Size: 16 KiB |
BIN
frontend/public/morty.png
Normal file
BIN
frontend/public/morty.png
Normal file
Binary file not shown.
After Width: | Height: | Size: 22 KiB |
137
frontend/src/App.tsx
Normal file
137
frontend/src/App.tsx
Normal file
@@ -0,0 +1,137 @@
|
|||||||
|
// src/App.tsx
|
||||||
|
import React, { useEffect, useState } from "react";
|
||||||
|
import { getCharacters, rateCharacters } from "./api";
|
||||||
|
import type { Character } from "./types";
|
||||||
|
import { Card } from "./components/card";
|
||||||
|
import { Table } from "./components/table";
|
||||||
|
import { getId } from "./utils";
|
||||||
|
|
||||||
|
function getRandomIndex(length: number) {
|
||||||
|
return Math.floor(Math.random() * length);
|
||||||
|
}
|
||||||
|
|
||||||
|
function getRandomPair(characters: Character[], lastPair: [number, number]) {
|
||||||
|
if (characters.length < 2) return [null, null];
|
||||||
|
|
||||||
|
let firstIndex = getRandomIndex(characters.length);
|
||||||
|
let secondIndex = getRandomIndex(characters.length);
|
||||||
|
|
||||||
|
while (
|
||||||
|
firstIndex === lastPair[0] ||
|
||||||
|
secondIndex === lastPair[1] ||
|
||||||
|
firstIndex === secondIndex
|
||||||
|
) {
|
||||||
|
firstIndex = getRandomIndex(characters.length);
|
||||||
|
secondIndex = getRandomIndex(characters.length);
|
||||||
|
}
|
||||||
|
return [characters[firstIndex], characters[secondIndex]];
|
||||||
|
}
|
||||||
|
|
||||||
|
const App: React.FC = () => {
|
||||||
|
const [characters, setCharacters] = useState<Character[]>([]);
|
||||||
|
const [rivals, setRivals] = useState<[Character | null, Character | null]>([
|
||||||
|
null,
|
||||||
|
null,
|
||||||
|
]);
|
||||||
|
const [voting, setVoting] = useState(false);
|
||||||
|
const [, setVotedLeft] = useState(false);
|
||||||
|
const [skipped, setSkipped] = useState(false);
|
||||||
|
const [lastPair] = useState<[number, number]>([0, 0]);
|
||||||
|
const currentYear = new Date().getFullYear();
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
(async () => {
|
||||||
|
const chars = await getCharacters();
|
||||||
|
setCharacters(chars);
|
||||||
|
const [first, second] = getRandomPair(chars, lastPair);
|
||||||
|
setRivals([first, second]);
|
||||||
|
})();
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
const generateNewRivals = () => {
|
||||||
|
const [first, second] = getRandomPair(characters, lastPair);
|
||||||
|
setRivals([first, second]);
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleVote = async (winnerIdx: 0 | 1, loserIdx: 0 | 1) => {
|
||||||
|
if (voting || !rivals[winnerIdx] || !rivals[loserIdx]) return;
|
||||||
|
setVoting(true);
|
||||||
|
setVotedLeft(winnerIdx === 0);
|
||||||
|
const winnerId = getId(rivals[winnerIdx]);
|
||||||
|
const loserId = getId(rivals[loserIdx]);
|
||||||
|
if (!winnerId || !loserId) return;
|
||||||
|
await rateCharacters(winnerId, loserId);
|
||||||
|
const chars = await getCharacters();
|
||||||
|
setCharacters(chars);
|
||||||
|
setTimeout(() => {
|
||||||
|
setVoting(false);
|
||||||
|
generateNewRivals();
|
||||||
|
}, 1000);
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleSkip = () => {
|
||||||
|
setSkipped(true);
|
||||||
|
setTimeout(() => {
|
||||||
|
setSkipped(false);
|
||||||
|
generateNewRivals();
|
||||||
|
}, 1000);
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="flex flex-col w-full min-h-screen items-center bg-gray-900 gap-2">
|
||||||
|
<h1 className="text-center text-white text-7xl">Rick & Morty</h1>
|
||||||
|
<h2 className="text-center text-white text-5xl">Tournament</h2>
|
||||||
|
<div className="bg-gray-700 flex flex-col justify-center rounded p-2 shadow-lg m-4">
|
||||||
|
<h1 className="text-center text-white text-2xl font-bold">
|
||||||
|
How does it work?
|
||||||
|
</h1>
|
||||||
|
<p className="text-center text-white">
|
||||||
|
Below there are two cards with two characters.
|
||||||
|
</p>
|
||||||
|
<p className="text-center text-white">
|
||||||
|
Choose whichever character you like better.
|
||||||
|
</p>
|
||||||
|
<p className="text-center text-white">Enjoy!</p>
|
||||||
|
</div>
|
||||||
|
{/* Loader can be added here */}
|
||||||
|
<div className="flex flex-wrap flex-row gap-1 items-center justify-center w-full">
|
||||||
|
{rivals[0] && (
|
||||||
|
<Card
|
||||||
|
data={rivals[0]}
|
||||||
|
isClicked={voting}
|
||||||
|
skipped={skipped}
|
||||||
|
onClick={() => handleVote(0, 1)}
|
||||||
|
isRight={false}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
{rivals[1] && (
|
||||||
|
<Card
|
||||||
|
data={rivals[1]}
|
||||||
|
isClicked={voting}
|
||||||
|
skipped={skipped}
|
||||||
|
onClick={() => handleVote(1, 0)}
|
||||||
|
isRight={true}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
{rivals[0] && (
|
||||||
|
<>
|
||||||
|
<button
|
||||||
|
className="bg-gray-50 p-2 rounded w-24 shadow"
|
||||||
|
onClick={handleSkip}
|
||||||
|
>
|
||||||
|
Skip >>
|
||||||
|
</button>
|
||||||
|
<h1 className="text-white text-4xl">Top 10</h1>
|
||||||
|
<Table characters={characters.slice(0, 10)} />
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
<span className="flex-1"></span>
|
||||||
|
<p className="m-1 text-white">
|
||||||
|
Copyright {currentYear} Gabriel Kaszewski
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
export default App;
|
14
frontend/src/api.ts
Normal file
14
frontend/src/api.ts
Normal file
@@ -0,0 +1,14 @@
|
|||||||
|
import type { Character } from './types';
|
||||||
|
|
||||||
|
export const getCharacters = async (): Promise<Character[]> => {
|
||||||
|
const res = await fetch('/characters');
|
||||||
|
return res.json();
|
||||||
|
};
|
||||||
|
|
||||||
|
export const rateCharacters = async (winnerId: string, loserId: string) => {
|
||||||
|
await fetch('/rate', {
|
||||||
|
method: 'POST',
|
||||||
|
headers: { 'Content-Type': 'application/json' },
|
||||||
|
body: JSON.stringify({ winner_id: winnerId, loser_id: loserId }),
|
||||||
|
});
|
||||||
|
};
|
62
frontend/src/components/card.tsx
Normal file
62
frontend/src/components/card.tsx
Normal file
@@ -0,0 +1,62 @@
|
|||||||
|
import React from 'react';
|
||||||
|
import type { Character } from '../types';
|
||||||
|
|
||||||
|
interface CardProps {
|
||||||
|
data: Character;
|
||||||
|
isClicked?: boolean;
|
||||||
|
skipped?: boolean;
|
||||||
|
onClick?: () => void;
|
||||||
|
isRight?: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
export const Card: React.FC<CardProps> = ({
|
||||||
|
data,
|
||||||
|
isClicked,
|
||||||
|
skipped,
|
||||||
|
onClick,
|
||||||
|
}) => (
|
||||||
|
<div
|
||||||
|
className={`card bg-gray-300 flex flex-col items-center shadow-lg rounded p-1 transform transition ease-in-out ${isClicked || skipped ? 'flip-card' : ''} md:hover:scale-105`}
|
||||||
|
onClick={onClick}
|
||||||
|
style={{ cursor: 'pointer' }}
|
||||||
|
>
|
||||||
|
<div className="card-inner">
|
||||||
|
{/* FRONT */}
|
||||||
|
<div className="card-front flex flex-col items-center">
|
||||||
|
<h1 className="text-lg font-bold">{data.name}</h1>
|
||||||
|
<img className="avatar" src={data.image} alt={data.name} />
|
||||||
|
<h2 className="text-lg text-center font-bold">Info</h2>
|
||||||
|
<div className="w-full md:w-2/3">
|
||||||
|
<table className="table-auto text-left">
|
||||||
|
<tbody>
|
||||||
|
<tr>
|
||||||
|
<th>Species</th>
|
||||||
|
<td>{data.species}</td>
|
||||||
|
</tr>
|
||||||
|
<tr>
|
||||||
|
<th>Gender</th>
|
||||||
|
<td>{data.gender}</td>
|
||||||
|
</tr>
|
||||||
|
<tr>
|
||||||
|
<th>Status</th>
|
||||||
|
<td>{data.status}</td>
|
||||||
|
</tr>
|
||||||
|
<tr>
|
||||||
|
<th>Origin</th>
|
||||||
|
<td>{data.origin.name}</td>
|
||||||
|
</tr>
|
||||||
|
<tr>
|
||||||
|
<th>Last location</th>
|
||||||
|
<td>{data.location.name}</td>
|
||||||
|
</tr>
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
{/* BACK */}
|
||||||
|
<div className="card-back">
|
||||||
|
{/* You can put whatever you want here, like a background or extra info */}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
10
frontend/src/components/table-element.tsx
Normal file
10
frontend/src/components/table-element.tsx
Normal file
@@ -0,0 +1,10 @@
|
|||||||
|
// src/components/TableElement.tsx
|
||||||
|
import React from 'react';
|
||||||
|
import type { Character } from '../types';
|
||||||
|
|
||||||
|
export const TableElement: React.FC<{ character: Character }> = ({ character }) => (
|
||||||
|
<div className="flex items-center gap-2">
|
||||||
|
<img className="avatar" src={character.image} alt={character.name} />
|
||||||
|
<p className="text-white text-lg">{character.name}</p>
|
||||||
|
</div>
|
||||||
|
);
|
11
frontend/src/components/table.tsx
Normal file
11
frontend/src/components/table.tsx
Normal file
@@ -0,0 +1,11 @@
|
|||||||
|
import React from 'react';
|
||||||
|
import type { Character } from '../types';
|
||||||
|
import { TableElement } from './table-element';
|
||||||
|
|
||||||
|
export const Table: React.FC<{ characters: Character[] }> = ({ characters }) => (
|
||||||
|
<div className="flex flex-col gap-2 m-4">
|
||||||
|
{characters.map((character) => (
|
||||||
|
<TableElement key={character.rmid} character={character} />
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
);
|
42
frontend/src/index.css
Normal file
42
frontend/src/index.css
Normal file
@@ -0,0 +1,42 @@
|
|||||||
|
@import "tailwindcss";
|
||||||
|
|
||||||
|
.card {
|
||||||
|
height: 470px;
|
||||||
|
width: 300px;
|
||||||
|
perspective: 1000px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.card-inner {
|
||||||
|
position: relative;
|
||||||
|
width: 100%;
|
||||||
|
height: 100%;
|
||||||
|
transition: transform 0.8s;
|
||||||
|
transform-style: preserve-3d;
|
||||||
|
}
|
||||||
|
|
||||||
|
.flip-card .card-inner {
|
||||||
|
transform: rotateY(180deg);
|
||||||
|
}
|
||||||
|
|
||||||
|
.card-front, .card-back {
|
||||||
|
position: absolute;
|
||||||
|
width: 100%;
|
||||||
|
height: 100%;
|
||||||
|
backface-visibility: hidden;
|
||||||
|
}
|
||||||
|
|
||||||
|
.card-back {
|
||||||
|
transform: rotateY(180deg);
|
||||||
|
background-image: url("/morty.png"); /* Adjust path as needed */
|
||||||
|
background-position: center;
|
||||||
|
background-size: contain;
|
||||||
|
background-repeat: no-repeat;
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: center;
|
||||||
|
}
|
||||||
|
|
||||||
|
.avatar {
|
||||||
|
width: 150px;
|
||||||
|
height: 150px;
|
||||||
|
}
|
10
frontend/src/main.tsx
Normal file
10
frontend/src/main.tsx
Normal file
@@ -0,0 +1,10 @@
|
|||||||
|
import { StrictMode } from 'react'
|
||||||
|
import { createRoot } from 'react-dom/client'
|
||||||
|
import './index.css'
|
||||||
|
import App from './App.tsx'
|
||||||
|
|
||||||
|
createRoot(document.getElementById('root')!).render(
|
||||||
|
<StrictMode>
|
||||||
|
<App />
|
||||||
|
</StrictMode>,
|
||||||
|
)
|
21
frontend/src/types.ts
Normal file
21
frontend/src/types.ts
Normal file
@@ -0,0 +1,21 @@
|
|||||||
|
export interface OriginOrLocation {
|
||||||
|
name: string;
|
||||||
|
url: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface Character {
|
||||||
|
_id: string | { $oid: string };
|
||||||
|
rmid: number;
|
||||||
|
name: string;
|
||||||
|
status: string;
|
||||||
|
species: string;
|
||||||
|
type: string;
|
||||||
|
gender: string;
|
||||||
|
origin: OriginOrLocation;
|
||||||
|
location: OriginOrLocation;
|
||||||
|
image: string;
|
||||||
|
episode: string[];
|
||||||
|
url: string;
|
||||||
|
created: string;
|
||||||
|
elo_rating: number;
|
||||||
|
}
|
9
frontend/src/utils.ts
Normal file
9
frontend/src/utils.ts
Normal file
@@ -0,0 +1,9 @@
|
|||||||
|
import type { Character } from "./types";
|
||||||
|
|
||||||
|
export function getId(character: Character | null) {
|
||||||
|
if (!character) return undefined;
|
||||||
|
const id = character._id as string | { $oid: string } | undefined;
|
||||||
|
if (typeof id === 'string') return id;
|
||||||
|
if (id && typeof id.$oid === 'string') return id.$oid;
|
||||||
|
return undefined;
|
||||||
|
}
|
1
frontend/src/vite-env.d.ts
vendored
Normal file
1
frontend/src/vite-env.d.ts
vendored
Normal file
@@ -0,0 +1 @@
|
|||||||
|
/// <reference types="vite/client" />
|
27
frontend/tsconfig.app.json
Normal file
27
frontend/tsconfig.app.json
Normal file
@@ -0,0 +1,27 @@
|
|||||||
|
{
|
||||||
|
"compilerOptions": {
|
||||||
|
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.app.tsbuildinfo",
|
||||||
|
"target": "ES2022",
|
||||||
|
"useDefineForClassFields": true,
|
||||||
|
"lib": ["ES2022", "DOM", "DOM.Iterable"],
|
||||||
|
"module": "ESNext",
|
||||||
|
"skipLibCheck": true,
|
||||||
|
|
||||||
|
/* Bundler mode */
|
||||||
|
"moduleResolution": "bundler",
|
||||||
|
"allowImportingTsExtensions": true,
|
||||||
|
"verbatimModuleSyntax": true,
|
||||||
|
"moduleDetection": "force",
|
||||||
|
"noEmit": true,
|
||||||
|
"jsx": "react-jsx",
|
||||||
|
|
||||||
|
/* Linting */
|
||||||
|
"strict": true,
|
||||||
|
"noUnusedLocals": true,
|
||||||
|
"noUnusedParameters": true,
|
||||||
|
"erasableSyntaxOnly": true,
|
||||||
|
"noFallthroughCasesInSwitch": true,
|
||||||
|
"noUncheckedSideEffectImports": true
|
||||||
|
},
|
||||||
|
"include": ["src"]
|
||||||
|
}
|
7
frontend/tsconfig.json
Normal file
7
frontend/tsconfig.json
Normal file
@@ -0,0 +1,7 @@
|
|||||||
|
{
|
||||||
|
"files": [],
|
||||||
|
"references": [
|
||||||
|
{ "path": "./tsconfig.app.json" },
|
||||||
|
{ "path": "./tsconfig.node.json" }
|
||||||
|
]
|
||||||
|
}
|
25
frontend/tsconfig.node.json
Normal file
25
frontend/tsconfig.node.json
Normal file
@@ -0,0 +1,25 @@
|
|||||||
|
{
|
||||||
|
"compilerOptions": {
|
||||||
|
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.node.tsbuildinfo",
|
||||||
|
"target": "ES2023",
|
||||||
|
"lib": ["ES2023"],
|
||||||
|
"module": "ESNext",
|
||||||
|
"skipLibCheck": true,
|
||||||
|
|
||||||
|
/* Bundler mode */
|
||||||
|
"moduleResolution": "bundler",
|
||||||
|
"allowImportingTsExtensions": true,
|
||||||
|
"verbatimModuleSyntax": true,
|
||||||
|
"moduleDetection": "force",
|
||||||
|
"noEmit": true,
|
||||||
|
|
||||||
|
/* Linting */
|
||||||
|
"strict": true,
|
||||||
|
"noUnusedLocals": true,
|
||||||
|
"noUnusedParameters": true,
|
||||||
|
"erasableSyntaxOnly": true,
|
||||||
|
"noFallthroughCasesInSwitch": true,
|
||||||
|
"noUncheckedSideEffectImports": true
|
||||||
|
},
|
||||||
|
"include": ["vite.config.ts"]
|
||||||
|
}
|
8
frontend/vite.config.ts
Normal file
8
frontend/vite.config.ts
Normal file
@@ -0,0 +1,8 @@
|
|||||||
|
import { defineConfig } from 'vite'
|
||||||
|
import react from '@vitejs/plugin-react-swc'
|
||||||
|
import tailwindcss from '@tailwindcss/vite'
|
||||||
|
|
||||||
|
// https://vite.dev/config/
|
||||||
|
export default defineConfig({
|
||||||
|
plugins: [react(), tailwindcss()],
|
||||||
|
})
|
127
src/bin/fetch_characters.rs
Normal file
127
src/bin/fetch_characters.rs
Normal file
@@ -0,0 +1,127 @@
|
|||||||
|
use mongodb::{
|
||||||
|
Client,
|
||||||
|
bson::{doc, to_document},
|
||||||
|
options::UpdateOptions,
|
||||||
|
};
|
||||||
|
use reqwest::Client as HttpClient;
|
||||||
|
use rick_and_morty::models::{Character, OriginOrLocation};
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
|
||||||
|
#[derive(Debug, Deserialize, Serialize)]
|
||||||
|
struct ApiCharacter {
|
||||||
|
id: i32,
|
||||||
|
name: String,
|
||||||
|
status: String,
|
||||||
|
species: String,
|
||||||
|
#[serde(rename = "type")]
|
||||||
|
character_type: String,
|
||||||
|
gender: String,
|
||||||
|
origin: OriginOrLocation,
|
||||||
|
location: OriginOrLocation,
|
||||||
|
image: String,
|
||||||
|
episode: Vec<String>,
|
||||||
|
url: String,
|
||||||
|
created: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl From<ApiCharacter> for Character {
|
||||||
|
fn from(api: ApiCharacter) -> Self {
|
||||||
|
Character {
|
||||||
|
id: None, // always None for new/incoming data
|
||||||
|
rmid: api.id,
|
||||||
|
name: api.name,
|
||||||
|
status: api.status,
|
||||||
|
species: api.species,
|
||||||
|
r#type: api.character_type,
|
||||||
|
gender: api.gender,
|
||||||
|
origin: api.origin,
|
||||||
|
location: api.location,
|
||||||
|
image: api.image,
|
||||||
|
episode: api.episode,
|
||||||
|
url: api.url,
|
||||||
|
created: api.created,
|
||||||
|
elo_rating: 1000.0,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn init_tracing() {
|
||||||
|
use tracing_subscriber::EnvFilter;
|
||||||
|
tracing_subscriber::fmt()
|
||||||
|
.with_env_filter(EnvFilter::from_default_env())
|
||||||
|
.with_target(true)
|
||||||
|
.with_level(true)
|
||||||
|
.init();
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::main]
|
||||||
|
async fn main() -> anyhow::Result<()> {
|
||||||
|
init_tracing();
|
||||||
|
dotenvy::dotenv().ok();
|
||||||
|
let db_uri =
|
||||||
|
std::env::var("MONGODB_URI").unwrap_or_else(|_| "mongodb://localhost:27017".to_string());
|
||||||
|
let db_name = std::env::var("DB_NAME").unwrap_or_else(|_| "rick_and_morty".to_string());
|
||||||
|
|
||||||
|
let client = Client::with_uri_str(&db_uri).await?;
|
||||||
|
let db = client.database(&db_name);
|
||||||
|
let collection = db.collection::<Character>("characters");
|
||||||
|
|
||||||
|
tracing::info!("Starting to fetch characters from Rick and Morty API");
|
||||||
|
let http = HttpClient::new();
|
||||||
|
|
||||||
|
let mut all_characters: Vec<Character> = Vec::new();
|
||||||
|
let mut next_url = "https://rickandmortyapi.com/api/character".to_string();
|
||||||
|
|
||||||
|
while !next_url.is_empty() {
|
||||||
|
tracing::info!(url = %next_url, "Fetching page");
|
||||||
|
let resp = http
|
||||||
|
.get(&next_url)
|
||||||
|
.send()
|
||||||
|
.await?
|
||||||
|
.json::<serde_json::Value>()
|
||||||
|
.await?;
|
||||||
|
let results = resp["results"].as_array().unwrap();
|
||||||
|
for c in results {
|
||||||
|
let c: ApiCharacter = serde_json::from_value(c.clone()).unwrap();
|
||||||
|
all_characters.push(c.into());
|
||||||
|
}
|
||||||
|
next_url = resp["info"]["next"].as_str().unwrap_or("").to_string();
|
||||||
|
}
|
||||||
|
|
||||||
|
tracing::info!(
|
||||||
|
count = all_characters.len(),
|
||||||
|
"Fetched all characters, starting DB upsert"
|
||||||
|
);
|
||||||
|
let options = UpdateOptions::builder().upsert(true).build();
|
||||||
|
// let insert_result = collection.insert_many(all_characters.clone()).await?;
|
||||||
|
|
||||||
|
for character in &all_characters {
|
||||||
|
let filter = doc! { "rmid": character.rmid };
|
||||||
|
let mut set_doc = to_document(character)?;
|
||||||
|
set_doc.remove("elo_rating"); // Do NOT overwrite existing Elo
|
||||||
|
let update = doc! {
|
||||||
|
"$set": set_doc,
|
||||||
|
"$setOnInsert": { "elo_rating": 1000.0 }
|
||||||
|
};
|
||||||
|
if let Err(e) = collection
|
||||||
|
.update_one(filter, update)
|
||||||
|
.with_options(Some(options.clone()))
|
||||||
|
.await
|
||||||
|
{
|
||||||
|
tracing::error!(error = ?e, id = character.rmid, name = %character.name, "Failed to upsert character");
|
||||||
|
}
|
||||||
|
tracing::info!(id = character.rmid, name = %character.name, "Upserted character");
|
||||||
|
}
|
||||||
|
|
||||||
|
// tracing::info!("Inserted {} characters", insert_result.inserted_ids.len());
|
||||||
|
|
||||||
|
let character_count = collection.count_documents(doc! {}).await?;
|
||||||
|
tracing::info!(
|
||||||
|
count = character_count,
|
||||||
|
"Total characters in DB after import"
|
||||||
|
);
|
||||||
|
|
||||||
|
tracing::info!("Done! Imported/updated characters.");
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
11
src/db.rs
Normal file
11
src/db.rs
Normal file
@@ -0,0 +1,11 @@
|
|||||||
|
use mongodb::{Client, Database};
|
||||||
|
use once_cell::sync::OnceCell;
|
||||||
|
|
||||||
|
pub static DB: OnceCell<Database> = OnceCell::new();
|
||||||
|
|
||||||
|
pub async fn connect_db(uri: &str, db_name: &str) -> mongodb::error::Result<()> {
|
||||||
|
let client = Client::with_uri_str(uri).await?;
|
||||||
|
let db = client.database(db_name);
|
||||||
|
DB.set(db).ok();
|
||||||
|
Ok(())
|
||||||
|
}
|
4
src/lib.rs
Normal file
4
src/lib.rs
Normal file
@@ -0,0 +1,4 @@
|
|||||||
|
pub mod db;
|
||||||
|
pub mod models;
|
||||||
|
pub mod routes;
|
||||||
|
pub mod utils;
|
59
src/main.rs
Normal file
59
src/main.rs
Normal file
@@ -0,0 +1,59 @@
|
|||||||
|
use axum::{
|
||||||
|
Router,
|
||||||
|
routing::{get, post},
|
||||||
|
};
|
||||||
|
use http::Method;
|
||||||
|
use rick_and_morty::{db, routes};
|
||||||
|
use tower_http::{
|
||||||
|
cors::{Any, CorsLayer},
|
||||||
|
services::ServeDir,
|
||||||
|
trace::TraceLayer,
|
||||||
|
};
|
||||||
|
|
||||||
|
fn init_tracing() {
|
||||||
|
use tracing_subscriber::EnvFilter;
|
||||||
|
tracing_subscriber::fmt()
|
||||||
|
.with_env_filter(EnvFilter::from_default_env())
|
||||||
|
.with_target(true)
|
||||||
|
.with_level(true)
|
||||||
|
.init();
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::main]
|
||||||
|
async fn main() {
|
||||||
|
init_tracing();
|
||||||
|
dotenvy::dotenv().ok();
|
||||||
|
|
||||||
|
let db_uri = std::env::var("MONGODB_URI").expect("MONGODB_URI not set");
|
||||||
|
let db_name = std::env::var("DB_NAME").unwrap_or_else(|_| "rick_and_morty".to_string());
|
||||||
|
let address = std::env::var("BIND_ADDR").unwrap_or_else(|_| "0.0.0.0:8000".to_string());
|
||||||
|
|
||||||
|
db::connect_db(&db_uri, &db_name)
|
||||||
|
.await
|
||||||
|
.expect("Failed to connect to database");
|
||||||
|
|
||||||
|
let db = db::DB.get().expect("Database not initialized");
|
||||||
|
|
||||||
|
let cors = CorsLayer::new()
|
||||||
|
// allow `GET` and `POST` when accessing the resource
|
||||||
|
.allow_methods([Method::GET, Method::POST, Method::OPTIONS])
|
||||||
|
.allow_headers([http::header::CONTENT_TYPE])
|
||||||
|
// allow requests from any origin
|
||||||
|
.allow_origin(Any);
|
||||||
|
|
||||||
|
let app = Router::new()
|
||||||
|
.route("/characters", get(routes::get_characters))
|
||||||
|
.route("/rate", post(routes::rate))
|
||||||
|
.with_state(db.clone())
|
||||||
|
.layer(TraceLayer::new_for_http())
|
||||||
|
.layer(cors)
|
||||||
|
.fallback_service(ServeDir::new("frontend/dist").append_index_html_on_directories(true));
|
||||||
|
|
||||||
|
let listener = tokio::net::TcpListener::bind(address)
|
||||||
|
.await
|
||||||
|
.expect("Failed to bind address");
|
||||||
|
|
||||||
|
println!("Listening on {}", listener.local_addr().unwrap());
|
||||||
|
|
||||||
|
axum::serve(listener, app).await.unwrap();
|
||||||
|
}
|
27
src/models/mod.rs
Normal file
27
src/models/mod.rs
Normal file
@@ -0,0 +1,27 @@
|
|||||||
|
use mongodb::bson::{doc, oid::ObjectId};
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
|
||||||
|
#[derive(Debug, Serialize, Deserialize, Clone)]
|
||||||
|
pub struct OriginOrLocation {
|
||||||
|
pub name: String,
|
||||||
|
pub url: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Serialize, Deserialize, Clone)]
|
||||||
|
pub struct Character {
|
||||||
|
#[serde(rename = "_id", skip_serializing_if = "Option::is_none")]
|
||||||
|
pub id: Option<ObjectId>, // Mongo _id
|
||||||
|
pub rmid: i32, // Rick&Morty ID, don't confuse with _id
|
||||||
|
pub name: String,
|
||||||
|
pub status: String,
|
||||||
|
pub species: String,
|
||||||
|
pub r#type: String,
|
||||||
|
pub gender: String,
|
||||||
|
pub origin: OriginOrLocation,
|
||||||
|
pub location: OriginOrLocation,
|
||||||
|
pub image: String,
|
||||||
|
pub episode: Vec<String>,
|
||||||
|
pub url: String,
|
||||||
|
pub created: String,
|
||||||
|
pub elo_rating: f64,
|
||||||
|
}
|
125
src/routes/mod.rs
Normal file
125
src/routes/mod.rs
Normal file
@@ -0,0 +1,125 @@
|
|||||||
|
use axum::response::Html;
|
||||||
|
use axum::{Json, extract::State, http::StatusCode};
|
||||||
|
use futures_util::stream::TryStreamExt;
|
||||||
|
use mongodb::Database;
|
||||||
|
use mongodb::bson::doc;
|
||||||
|
use mongodb::bson::oid::ObjectId;
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
|
||||||
|
use crate::models::Character;
|
||||||
|
use crate::utils::calculate_elo;
|
||||||
|
|
||||||
|
#[derive(Deserialize)]
|
||||||
|
pub struct RateRequest {
|
||||||
|
winner_id: String,
|
||||||
|
loser_id: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Deserialize, Serialize)]
|
||||||
|
pub struct RateResponse {
|
||||||
|
winner: Character,
|
||||||
|
loser: Character,
|
||||||
|
}
|
||||||
|
|
||||||
|
static K_FACTOR: f64 = 32.0; // K-factor for Elo rating system
|
||||||
|
|
||||||
|
pub async fn get_characters(
|
||||||
|
State(db): State<Database>,
|
||||||
|
) -> Result<Json<Vec<Character>>, StatusCode> {
|
||||||
|
let collection = db.collection::<Character>("characters");
|
||||||
|
let pipeline = vec![doc! { "$sort": { "elo_rating": -1 } }];
|
||||||
|
|
||||||
|
let mut cursor = collection
|
||||||
|
.aggregate(pipeline)
|
||||||
|
.await
|
||||||
|
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
|
||||||
|
|
||||||
|
let mut characters = Vec::new();
|
||||||
|
while let Some(result) = cursor
|
||||||
|
.try_next()
|
||||||
|
.await
|
||||||
|
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?
|
||||||
|
{
|
||||||
|
let character: Character =
|
||||||
|
mongodb::bson::from_document(result).map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
|
||||||
|
characters.push(character);
|
||||||
|
}
|
||||||
|
|
||||||
|
tracing::info!(count = characters.len(), "Fetched characters from DB");
|
||||||
|
|
||||||
|
Ok(Json(characters))
|
||||||
|
}
|
||||||
|
|
||||||
|
#[axum::debug_handler]
|
||||||
|
pub async fn rate(
|
||||||
|
State(db): State<Database>,
|
||||||
|
Json(req): Json<RateRequest>,
|
||||||
|
) -> Result<Json<RateResponse>, StatusCode> {
|
||||||
|
let collection = db.collection::<Character>("characters");
|
||||||
|
|
||||||
|
let winner_oid = ObjectId::parse_str(&req.winner_id).map_err(|_| StatusCode::BAD_REQUEST)?;
|
||||||
|
let loser_oid = ObjectId::parse_str(&req.loser_id).map_err(|_| StatusCode::BAD_REQUEST)?;
|
||||||
|
|
||||||
|
let winner = collection
|
||||||
|
.find_one(doc! { "_id": winner_oid })
|
||||||
|
.await
|
||||||
|
.ok()
|
||||||
|
.flatten()
|
||||||
|
.ok_or(StatusCode::NOT_FOUND)?;
|
||||||
|
let loser = collection
|
||||||
|
.find_one(doc! { "_id": loser_oid })
|
||||||
|
.await
|
||||||
|
.ok()
|
||||||
|
.flatten()
|
||||||
|
.ok_or(StatusCode::NOT_FOUND)?;
|
||||||
|
|
||||||
|
let (new_winner_elo, new_loser_elo) =
|
||||||
|
calculate_elo(winner.elo_rating, loser.elo_rating, K_FACTOR);
|
||||||
|
|
||||||
|
collection
|
||||||
|
.update_one(
|
||||||
|
doc! {"_id": &winner_oid},
|
||||||
|
doc! { "$set": { "elo_rating": new_winner_elo } },
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
|
||||||
|
|
||||||
|
collection
|
||||||
|
.update_one(
|
||||||
|
doc! {"_id": &loser_oid},
|
||||||
|
doc! { "$set": { "elo_rating": new_loser_elo } },
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
|
||||||
|
|
||||||
|
// return resposnse with characters' new Elo ratings
|
||||||
|
let updated_winner = collection
|
||||||
|
.find_one(doc! { "_id": winner_oid })
|
||||||
|
.await
|
||||||
|
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?
|
||||||
|
.ok_or(StatusCode::NOT_FOUND)?;
|
||||||
|
let updated_loser = collection
|
||||||
|
.find_one(doc! { "_id": loser_oid })
|
||||||
|
.await
|
||||||
|
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?
|
||||||
|
.ok_or(StatusCode::NOT_FOUND)?;
|
||||||
|
|
||||||
|
tracing::info!(
|
||||||
|
"Rated characters: winner_id = {}, loser_id = {}, new_winner_elo =
|
||||||
|
{}, new_loser_elo = {}",
|
||||||
|
req.winner_id,
|
||||||
|
req.loser_id,
|
||||||
|
new_winner_elo,
|
||||||
|
new_loser_elo
|
||||||
|
);
|
||||||
|
|
||||||
|
Ok(Json(RateResponse {
|
||||||
|
winner: updated_winner,
|
||||||
|
loser: updated_loser,
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn index() -> Html<&'static str> {
|
||||||
|
tracing::info!("Serving index page");
|
||||||
|
Html("<h1>Welcome to the Rick and Morty Character Rating API</h1>")
|
||||||
|
}
|
9
src/utils.rs
Normal file
9
src/utils.rs
Normal file
@@ -0,0 +1,9 @@
|
|||||||
|
pub fn calculate_elo(winner_elo: f64, loser_elo: f64, k_factor: f64) -> (f64, f64) {
|
||||||
|
let expected_winner = 1.0 / (1.0 + 10f64.powf((loser_elo - winner_elo) / 400.0));
|
||||||
|
let expected_loser = 1.0 / (1.0 + 10f64.powf((winner_elo - loser_elo) / 400.0));
|
||||||
|
|
||||||
|
let new_winner_elo = winner_elo + k_factor * (1.0 - expected_winner);
|
||||||
|
let new_loser_elo = loser_elo + k_factor * (0.0 - expected_loser);
|
||||||
|
|
||||||
|
(new_winner_elo, new_loser_elo)
|
||||||
|
}
|
Reference in New Issue
Block a user