Skip to content

Commit e3b459a

Browse files
Added most of the required typescript types
1 parent 3447472 commit e3b459a

22 files changed

+223
-184
lines changed

RaspberryPi-WebServer/backend/package.json

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,7 @@
3232
"@types/express": "^5.0.1",
3333
"@types/jest": "^29.5.14",
3434
"@types/node": "^22.15.18",
35+
"@types/ws": "^8.18.1",
3536
"@typescript-eslint/parser": "^8.32.1",
3637
"eslint": "^9.26.0",
3738
"globals": "^16.1.0",
@@ -42,4 +43,4 @@
4243
"tsx": "^4.19.4",
4344
"typescript": "^5.8.3"
4445
}
45-
}
46+
}

RaspberryPi-WebServer/backend/src/api/middleware/getAccessTokenFromHeader.ts

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,11 @@
1-
export function getAccessTokenFromHeader(req, res, next) {
1+
import { Request, Response, NextFunction } from "express";
2+
3+
export function getAccessTokenFromHeader(req: Request, res: Response, next: NextFunction) {
24
const authHeader = req.headers["authorization"];
35
if (authHeader && authHeader.startsWith("Bearer ")) {
46
req.accessToken = authHeader.split(" ")[1];
57
} else {
6-
req.accessToken = null;
8+
req.accessToken = undefined;
79
}
810

911
next();

RaspberryPi-WebServer/backend/src/api/routes/auth.ts

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import express from "express";
1+
import express, { Request, Response } from "express";
22
import axios from "axios";
33
import config from "@shared/config";
44
import MainEventStream from "@src/controllers/Streams/MainEventStream";
@@ -24,7 +24,7 @@ router.get("/login", (req, res) => {
2424
router.get("/logout", (req, res) => {
2525
res.clearCookie("lichess-access-token", {
2626
httpOnly: true,
27-
sameSite: "Strict",
27+
sameSite: "strict",
2828
});
2929

3030
if (LichessTokenVault.getAccessToken()) {
@@ -47,13 +47,13 @@ router.get("/logout", (req, res) => {
4747
MainEventStream.getInstance().stop();
4848
});
4949

50-
router.post("/set-access-token", (req, res) => {
50+
router.post("/set-access-token", (req: Request, res: Response) => {
5151
const token = req.accessToken;
5252
const expiresIn_seconds = req.body.expiresIn_seconds;
5353
if (!token || !expiresIn_seconds) {
5454
res.status(401).send();
5555
}
56-
LichessTokenVault.setAccessToken(token, expiresIn_seconds);
56+
LichessTokenVault.setAccessToken(token, BigInt(expiresIn_seconds));
5757

5858
res.status(204).send();
5959
});

RaspberryPi-WebServer/backend/src/controllers/LichessControllers/LichessChallengeController.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,15 +4,15 @@ import LichessTokenVault from "./LichessTokenVault";
44

55
const challengeBaseURL = `${config.lichess_base_url}/api/challenge`;
66
export default class LichessChallengeController {
7-
static async acceptChallenge(challengeId) {
7+
static async acceptChallenge(challengeId: string) {
88
try {
99
await axios.post(`${challengeBaseURL}/${challengeId}/accept`, {}, LichessTokenVault.getAuthorizationHeaderObject());
1010
} catch (error) {
1111
console.error(`Error while accepting challenge with id ${challengeId}: ${error}`);
1212
}
1313
}
1414

15-
static async declineChallenge(challengeId) {
15+
static async declineChallenge(challengeId: string) {
1616
try {
1717
await axios.post(`${challengeBaseURL}/${challengeId}/decline`, {}, LichessTokenVault.getAuthorizationHeaderObject());
1818
} catch (error) {

RaspberryPi-WebServer/backend/src/controllers/LichessControllers/LichessChatController.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@ import LichessTokenVault from "./LichessTokenVault";
55
const gameBaseURL = `${config.lichess_base_url}/api/board/game`;
66

77
export default class LichessChatController {
8-
static async sendMessage(gameId, message) {
8+
static async sendMessage(gameId: string, message: string) {
99
try {
1010
await axios.post(
1111
`${gameBaseURL}/${gameId}/chat`,
@@ -20,7 +20,7 @@ export default class LichessChatController {
2020
}
2121
}
2222

23-
static async fetchChat(gameId) {
23+
static async fetchChat(gameId: string) {
2424
try {
2525
const response = await axios.get(`${gameBaseURL}/${gameId}/chat`, LichessTokenVault.getAuthorizationHeaderObject());
2626
return response.data;

RaspberryPi-WebServer/backend/src/controllers/LichessControllers/LichessGameController.ts

Lines changed: 12 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -5,91 +5,91 @@ import LichessTokenVault from "./LichessTokenVault";
55
const gameBaseURL = `${config.lichess_base_url}/api/board/game`;
66

77
export default class LichessGameController {
8-
static async makeMove(gameId, move) {
8+
static async makeMove(gameId: string, move: string) {
99
try {
1010
await axios.post(`${gameBaseURL}/${gameId}/move/${move}`, {}, LichessTokenVault.getAuthorizationHeaderObject());
1111
} catch (error) {
1212
console.error(`Error while making the move ${move} in game with id ${gameId}: ${error}`);
1313
}
1414
}
1515

16-
static async abortGame(gameId) {
16+
static async abortGame(gameId: string) {
1717
try {
1818
await axios.post(`${gameBaseURL}/${gameId}/abort`, {}, LichessTokenVault.getAuthorizationHeaderObject());
1919
} catch (error) {
2020
console.error(`Error while aborting game with id ${gameId}: ${error}`);
2121
}
2222
}
2323

24-
static async resignGame(gameId) {
24+
static async resignGame(gameId: string) {
2525
try {
2626
await axios.post(`${gameBaseURL}/${gameId}/resign`, {}, LichessTokenVault.getAuthorizationHeaderObject());
2727
} catch (error) {
2828
console.error(`Error while resigning game with id ${gameId}: ${error}`);
2929
}
3030
}
3131

32-
static async offerDraw(gameId) {
32+
static async offerDraw(gameId: string) {
3333
try {
3434
await LichessGameController.#handleDrawOffer(gameId, "yes");
3535
} catch (error) {
3636
console.error(`Error while offering a draw to game with id ${gameId}: ${error}`);
3737
}
3838
}
3939

40-
static async acceptDraw(gameId) {
40+
static async acceptDraw(gameId: string) {
4141
try {
4242
await LichessGameController.#handleDrawOffer(gameId, "yes");
4343
} catch (error) {
4444
console.error(`Error while accepting a draw from game with id ${gameId}: ${error}`);
4545
}
4646
}
4747

48-
static async declineDraw(gameId) {
48+
static async declineDraw(gameId: string) {
4949
try {
5050
await LichessGameController.#handleDrawOffer(gameId, "no");
5151
} catch (error) {
5252
console.error(`Error while declining a draw from game with id ${gameId}: ${error}`);
5353
}
5454
}
5555

56-
static async createTakeback(gameId) {
56+
static async createTakeback(gameId: string) {
5757
try {
5858
await LichessGameController.#handleTakebackOffer(gameId, "yes");
5959
} catch (error) {
6060
console.error(`Error while creating a takeback for game with id ${gameId}: ${error}`);
6161
}
6262
}
6363

64-
static async acceptTakeback(gameId) {
64+
static async acceptTakeback(gameId: string) {
6565
try {
6666
await LichessGameController.#handleTakebackOffer(gameId, "yes");
6767
} catch (error) {
6868
console.error(`Error while accepting takeback from game with id ${gameId}: ${error}`);
6969
}
7070
}
7171

72-
static async declineTakeback(gameId) {
72+
static async declineTakeback(gameId: string) {
7373
try {
7474
await LichessGameController.#handleTakebackOffer(gameId, "no");
7575
} catch (error) {
7676
console.error(`Error while declining takeback from game with id ${gameId}: ${error}`);
7777
}
7878
}
7979

80-
static async claimVictory(gameId) {
80+
static async claimVictory(gameId: string) {
8181
try {
8282
await axios.post(`${gameBaseURL}/${gameId}/claim-victory`, {}, LichessTokenVault.getAuthorizationHeaderObject());
8383
} catch (error) {
8484
console.error(`Error while claiming victory for game with id ${gameId}: ${error}`);
8585
}
8686
}
8787

88-
static async #handleDrawOffer(gameId, accept) {
88+
static async #handleDrawOffer(gameId: string, accept: "yes" | "no") {
8989
await axios.post(`${gameBaseURL}/${gameId}/draw/${accept}`, {}, LichessTokenVault.getAuthorizationHeaderObject());
9090
}
9191

92-
static async #handleTakebackOffer(gameId, accept) {
92+
static async #handleTakebackOffer(gameId: string, accept: "yes" | "no") {
9393
await axios.post(`${gameBaseURL}/${gameId}/takeback/${accept}`, {}, LichessTokenVault.getAuthorizationHeaderObject());
9494
}
9595
}

RaspberryPi-WebServer/backend/src/controllers/LichessControllers/LichessTokenVault.ts

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2,9 +2,12 @@
22
* This Controller stores the lichess access token for the current user as only one user can be logged into the board at a time
33
*/
44
export default class LichessTokenVault {
5-
static setAccessToken(accessToken, expiresIn_seconds) {
5+
private static accessToken : string | undefined;
6+
private static accessTokenExpirationDate : bigint | undefined;
7+
8+
static setAccessToken(accessToken: string | undefined, expiresIn_seconds: bigint | undefined) {
69
this.accessToken = accessToken;
7-
this.accessTokenExpirationDate = Date.now() + expiresIn_seconds * 1000; //expiresIn is in seconds, Date.now() is in milliseconds
10+
this.accessTokenExpirationDate = expiresIn_seconds ? BigInt(Date.now()) + expiresIn_seconds * BigInt(1000) : undefined; //expiresIn is in seconds, Date.now() is in milliseconds
811
}
912

1013
static getAccessToken() {
@@ -29,7 +32,7 @@ export default class LichessTokenVault {
2932
}
3033

3134
static deleteAccessToken() {
32-
this.accessToken = null;
33-
this.accessTokenExpirationDate = null;
35+
this.accessToken = undefined;
36+
this.accessTokenExpirationDate = undefined;
3437
}
3538
}

RaspberryPi-WebServer/backend/src/controllers/LichessControllers/LichessUserController.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@ import LichessTokenVault from "./LichessTokenVault";
55
const userBaseURL = `${config.lichess_base_url}/api/user`;
66

77
export default class LichessUserController {
8-
static async fetchUserInformation(username) {
8+
static async fetchUserInformation(username: string) {
99
try {
1010
const response = await axios.get(`${userBaseURL}/${username}`, LichessTokenVault.getAuthorizationHeaderObject());
1111
return response.data;
@@ -24,6 +24,6 @@ export default class LichessUserController {
2424
}
2525

2626
static async fetchLoggedInUsername() {
27-
return await this.fetchLoggedInUserInformation().username;
27+
return (await this.fetchLoggedInUserInformation()).username;
2828
}
2929
}

RaspberryPi-WebServer/backend/src/controllers/PhysicalBoardController.ts

Lines changed: 22 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import { BISHOP, KING, KNIGHT, PAWN, QUEEN, ROOK } from "chess.js";
1+
import { BISHOP, KING, KNIGHT, PAWN, PieceSymbol, QUEEN, ROOK, Move } from "chess.js";
22
import BoardPosition from "@src/helpers/BoardPosition";
33
import VirtualBoardController from "./VirtualBoardController";
44
import LichessGameController from "./LichessControllers/LichessGameController";
@@ -7,30 +7,31 @@ import { concatZeroesUntilSizeMatches, hexToBinary64 } from "@src/helpers/util";
77
import { ArduinoCommunicator } from "@src/services/ArduinoCommunicator";
88

99
export default class PhysicalBoardController {
10-
static #instance = null;
10+
private static instance : PhysicalBoardController;
11+
private lastReadPositioning : string | null = null;
1112

1213
constructor() {
13-
if (PhysicalBoardController.#instance) {
14+
if (PhysicalBoardController.instance) {
1415
throw new Error("Use PhysicalBoardController.getInstance() instead of new.");
1516
}
1617

1718
this.lastReadPositioning = null;
18-
PhysicalBoardController.#instance = this;
19+
PhysicalBoardController.instance = this;
1920
}
2021

2122
static getInstance() {
22-
if (!PhysicalBoardController.#instance) {
23-
PhysicalBoardController.#instance = new PhysicalBoardController();
23+
if (!PhysicalBoardController.instance) {
24+
PhysicalBoardController.instance = new PhysicalBoardController();
2425
}
2526

26-
return PhysicalBoardController.#instance;
27+
return PhysicalBoardController.instance;
2728
}
2829

2930
/**
3031
* move: e.g. "a2a3"
3132
*/
3233
// eslint-disable-next-line no-unused-vars
33-
async movePiece(move, pieceType, moveInformation) {
34+
async movePiece(move: string, pieceType: PieceSymbol, moveInformation: Move) {
3435
const fromPosition = new BoardPosition(move[0], Number(move[1]));
3536
const toPosition = new BoardPosition(move[2], Number(move[3]));
3637

@@ -61,24 +62,24 @@ export default class PhysicalBoardController {
6162
}
6263
}
6364

64-
async #movePawn(fromPosition, toPosition) {
65+
async #movePawn(fromPosition: BoardPosition, toPosition: BoardPosition) {
6566
await this.#executePhysicalMovesInOrder(fromPosition, toPosition);
6667
}
6768

6869
/**
6970
* Tries to move the knight without moving another piece first.
7071
* If thats's not possible, it moves a helper piece to a corner, moves the knight, and the moves the helper piece back
7172
*/
72-
async #moveKnight(fromPosition, toPosition) {
73+
async #moveKnight(fromPosition: BoardPosition, toPosition: BoardPosition) {
7374
const helperPiecePositions = this.calculateKnightHelperPiecePositions(fromPosition, toPosition);
7475

7576
//if the tile near the from-position is empty
76-
if (!VirtualBoardController.getInstance().getPieceAtPosition(helperPiecePositions.nearFromPositionFrom?.toChessNotationString())) {
77+
if (!VirtualBoardController.getInstance().getPieceAtPosition(helperPiecePositions.nearFromPositionFrom?.toSquareString())) {
7778
return await this.#executePhysicalMovesInOrder(fromPosition, helperPiecePositions.nearFromPositionFrom, toPosition);
7879
}
7980

8081
//if the tile near the to-position is empty
81-
if (!VirtualBoardController.getInstance().getPieceAtPosition(helperPiecePositions.nearToPositionFrom?.toChessNotationString())) {
82+
if (!VirtualBoardController.getInstance().getPieceAtPosition(helperPiecePositions.nearToPositionFrom?.toSquareString())) {
8283
return await this.#executePhysicalMovesInOrder(fromPosition, helperPiecePositions.nearToPositionFrom, toPosition);
8384
}
8485

@@ -96,19 +97,19 @@ export default class PhysicalBoardController {
9697
await this.#executePhysicalMovesInOrder(helperToPositionToUse, helperFromPositionToUse);
9798
}
9899

99-
async #moveBishop(fromPosition, toPosition) {
100+
async #moveBishop(fromPosition: BoardPosition, toPosition: BoardPosition) {
100101
await this.#executePhysicalMovesInOrder(fromPosition, toPosition);
101102
}
102103

103-
async #moveRook(fromPosition, toPosition) {
104+
async #moveRook(fromPosition: BoardPosition, toPosition: BoardPosition) {
104105
await this.#executePhysicalMovesInOrder(fromPosition, toPosition);
105106
}
106107

107-
async #moveQueen(fromPosition, toPosition) {
108+
async #moveQueen(fromPosition: BoardPosition, toPosition: BoardPosition) {
108109
await this.#executePhysicalMovesInOrder(fromPosition, toPosition);
109110
}
110111

111-
async #moveKing(fromPosition, toPosition) {
112+
async #moveKing(fromPosition: BoardPosition, toPosition: BoardPosition) {
112113
await this.#executePhysicalMovesInOrder(fromPosition, toPosition);
113114
}
114115

@@ -119,7 +120,7 @@ export default class PhysicalBoardController {
119120
* along the rest of the positions and is released at the last position in the array
120121
* @param {BoardPosition} moves
121122
*/
122-
async #executePhysicalMovesInOrder(...moves) {
123+
async #executePhysicalMovesInOrder(...moves: BoardPosition[]) {
123124
if (moves.length < 2) return;
124125
const communicator = ArduinoCommunicator.getInstance();
125126
try {
@@ -188,13 +189,13 @@ export default class PhysicalBoardController {
188189
}
189190
}
190191

191-
#getChangedPosition(pos1, pos2) {
192+
#getChangedPosition(pos1: string, pos2: string) {
192193
const num1 = BigInt("0b" + pos1);
193194
const num2 = BigInt("0b" + pos2);
194195

195-
const position_int = concatZeroesUntilSizeMatches((num1 ^ num2).toString(2), 64).indexOf(1); //because of the xor, theres a 1 only at the changed position
196+
const position_int = concatZeroesUntilSizeMatches((num1 ^ num2).toString(2), 64).indexOf("1"); //because of the xor, theres a 1 only at the changed position
196197
const xPositionStr = String.fromCharCode("a".charCodeAt(0) + (position_int % 8));
197-
const yPositionStr = parseInt(position_int / 8) + 1;
198+
const yPositionStr = String.fromCharCode(position_int / 8 + 1);
198199
const positionInChessNotation = xPositionStr + yPositionStr;
199200
return positionInChessNotation;
200201
}
@@ -205,7 +206,7 @@ export default class PhysicalBoardController {
205206
* @param {BoardPosition} knightToPosition
206207
* @returns and object containing the from and to positions of the two potential helper pieces
207208
*/
208-
calculateKnightHelperPiecePositions(knightFromPosition, knightToPosition) {
209+
calculateKnightHelperPiecePositions(knightFromPosition: BoardPosition, knightToPosition: BoardPosition) {
209210
const delta = knightFromPosition.getDelta(knightToPosition);
210211
let nearFromDelta = { x: Math.ceil(delta.x / 2), y: Math.ceil(delta.y / 2) };
211212
let nearToDelta = { x: Math.floor(delta.x / 2), y: Math.floor(delta.y / 2) };

0 commit comments

Comments
 (0)