-
-
Save morintd/00c707c1d979a181adaa07a81e3236ff to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { Response, NextFunction } from "express"; | |
import { JumpTo } from "./use-cases/jump-to.use-case"; | |
import { Play } from "./use-cases/play.use-case"; | |
import { Initialize } from "./use-cases/initialize.use-case"; | |
import { | |
CellAlreadyTakenException, | |
StepDoesNotExistException, | |
} from "./exceptions"; | |
import { BadRequestException } from "../common/exceptions/bad-request.exception"; | |
export class TicTacToeController { | |
constructor( | |
private initialize: Initialize, | |
private play: Play, | |
private jumpTo: JumpTo | |
) {} | |
handleInitialize(res: Response) { | |
const game = this.initialize.execute(); | |
res.status(201).json({ | |
moves: this.getMoves(game.history), | |
status: this.getStatus(game.winner, game.xIsNext), | |
squares: game.history[game.step], | |
}); | |
} | |
handlePlay(res: Response, next: NextFunction, step: number, square: number) { | |
try { | |
const game = this.play.execute({ step, square }); | |
res.status(201).json({ | |
moves: this.getMoves(game.history), | |
status: this.getStatus(game.winner, game.xIsNext), | |
squares: game.history[game.step], | |
}); | |
} catch (e) { | |
if (e instanceof StepDoesNotExistException) { | |
return next( | |
new BadRequestException({ | |
error: "step does not exist", | |
}) | |
); | |
} | |
if (e instanceof CellAlreadyTakenException) { | |
return next( | |
new BadRequestException({ | |
error: "cell already taken", | |
}) | |
); | |
} | |
next(e); | |
} | |
} | |
handleJumpTo(res: Response, next: NextFunction, step: number) { | |
try { | |
const game = this.jumpTo.execute({ step }); | |
res.status(201).json({ | |
moves: this.getMoves(game.history), | |
status: this.getStatus(game.winner, game.xIsNext), | |
squares: game.history[game.step], | |
}); | |
} catch (e) { | |
if (e instanceof StepDoesNotExistException) { | |
return next( | |
new BadRequestException({ | |
error: "step does not exist", | |
}) | |
); | |
} | |
next(e); | |
} | |
} | |
private getMoves(history: string[][]) { | |
const moves = history.map((_, move: number) => { | |
return { | |
move, | |
description: move > 0 ? "Go to move #" + move : "Go to game start", | |
}; | |
}); | |
return moves; | |
} | |
private getStatus(winner: string | null, xIsNext: boolean) { | |
const status = winner | |
? winner === "draw" | |
? "Draw" | |
: "Winner: " + winner | |
: "Next player: " + (xIsNext ? "X" : "O"); | |
return status; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment