Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

gh-133: Add strict on BE #144

Merged
merged 4 commits into from
May 11, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 5 additions & 4 deletions backend/app.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import * as express from 'express'
import { Response, Request } from 'express'
import { NextFunction, Response, Request } from 'express'
import * as bodyParser from 'body-parser'

import * as storage from './storage/Storage'
Expand All @@ -10,14 +10,15 @@ import { addGame } from './repositories/GameRepository'
import { makeBot, SingleChannelBot } from './bot/bot-factory'

import { MatchReporter } from './match-reporter/MatchReporter'
import { InputError } from './errors/InputError'

const jsonParser = bodyParser.json()
const urlencodedParser = bodyParser.urlencoded({ extended: false })

const app = express()
const port = 3000

const addCrossDomainHeaders = function(req, res, next): void {
const addCrossDomainHeaders = function(req: Request, res: Response, next: NextFunction): void {
res.header('Access-Control-Allow-Origin', '*')
res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE')
res.header('Access-Control-Allow-Headers', 'Content-Type')
Expand All @@ -28,15 +29,15 @@ app.use(addCrossDomainHeaders)
app.use(urlencodedParser)
app.use(jsonParser)

let matchReporter
let matchReporter: MatchReporter
makeBot(process.env.FOOSBOT_TOKEN, process.env.FOOS_CHANNEL_NAME)
.then((bot: SingleChannelBot) => {
matchReporter = new MatchReporter(bot, process.env.MATCH_REPORT_PREFIX_SUFFIX_CONFIG)
console.log('Slackbot initialized!')
})
.catch(error => console.warn('Slackbot initialization failed:', error.message))

const processError = (response, error): void => {
const processError = (response: Response, error: InputError): void => {
console.error(error)
response.statusCode = error.httpStatusCode || 500
response.send(error.message)
Expand Down
14 changes: 8 additions & 6 deletions backend/bot/bot-factory.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,31 +3,33 @@ import SlackBot from 'slackbots'
export class SingleChannelBot {
constructor(
private readonly slackbot: SlackBot,
private readonly channelName,
private readonly channelId
private readonly channelName: string,
private readonly channelId: string
) {}

setGroupPurpose(purpose): Promise<void> {
setGroupPurpose(purpose: string): Promise<void> {
return this.slackbot._api('groups.setPurpose', { channel: this.channelId, purpose })
}

postMessage(message, isAsUser = true): Promise<void> {
postMessage(message: string, isAsUser = true): Promise<void> {
/* eslint-disable-next-line @typescript-eslint/camelcase */
return this.slackbot.postTo(this.channelName, message, { as_user: isAsUser })
}
}

export const makeBot = (botToken, channelName): Promise<SingleChannelBot> => {
export const makeBot =
(botToken: string | undefined, channelName: string | undefined): Promise<SingleChannelBot> => {
return new Promise((resolve, reject): void => {
if (!botToken || !channelName) {
reject(Error('botToken or channelName missing'))
return
}

const slackbot = new SlackBot({
token: botToken,
})

slackbot.on('error', error => reject(error))
slackbot.on('error', (error: Error) => reject(error))

slackbot.on('start', async () => {
let groupId
Expand Down
2 changes: 1 addition & 1 deletion backend/errors/BadRequestError.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
export class BadRequestError extends Error {
readonly httpStatusCode: number
constructor(message) {
constructor(message: string) {
super(message)
this.httpStatusCode = 400
}
Expand Down
2 changes: 1 addition & 1 deletion backend/errors/ConflictError.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
export class ConflictError extends Error {
readonly httpStatusCode: number
constructor(message) {
constructor(message: string) {
super(message)
this.httpStatusCode = 409
}
Expand Down
2 changes: 1 addition & 1 deletion backend/errors/InputError.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
export class InputError extends Error {
readonly httpStatusCode: number
constructor(message) {
constructor(message: string) {
super(message)
this.httpStatusCode = 422
}
Expand Down
2 changes: 1 addition & 1 deletion backend/errors/NotFoundError.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
export class NotFoundError extends Error {
readonly httpStatusCode: number
constructor(message) {
constructor(message: string) {
super(message)
this.httpStatusCode = 404
}
Expand Down
28 changes: 17 additions & 11 deletions backend/match-reporter/MatchReporter.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,12 @@
import { SingleChannelBot } from '../bot/bot-factory'
import { MatchReportDecoration, EMPTY_DECORATION } from '../types/MatchReportDecoration'
import { Player } from '../types/Player'
import { Match } from '../types/Match'

const DEFAULT_LEADERBOARD_SIZE = 5

const parseMatchReportDecorations = (config): Array<MatchReportDecoration> => config
const parseMatchReportDecorations =
(config: string | undefined): Array<MatchReportDecoration> => config
? config.split(';').map(configPart => {
const splitConfigPart = configPart.split(',')
if (splitConfigPart.length !== 4) {
Expand All @@ -18,7 +21,7 @@ const parseMatchReportDecorations = (config): Array<MatchReportDecoration> => co
})
: []

const createRankingChangeMessage = (oldRankings, newRankings): string => {
const createRankingChangeMessage = (oldRankings: Player[], newRankings: Player[]): string => {
const rankingChanges = oldRankings
.map((oldPlayer, index) => ({
name: oldPlayer.name,
Expand All @@ -38,13 +41,14 @@ const createRankingChangeMessage = (oldRankings, newRankings): string => {
.join('\n')
}

const hasLeaderboardChanged = (leaderboardSize, oldRankings, newRankings): boolean => {
const hasLeaderboardChanged =
(leaderboardSize: number, oldRankings: Player[], newRankings: Player[]): boolean => {
return oldRankings.findIndex((oldPlayer, index) => {
return oldPlayer.id !== newRankings[index].id
}) < leaderboardSize
}

const getDecorationsForTeam = (team, decorations: Array<MatchReportDecoration>):
const getDecorationsForTeam = (team: Player[], decorations: Array<MatchReportDecoration>):
MatchReportDecoration => {
for (const decoration of decorations) {
if (team.every(player => player.name === decoration.player1 ||
Expand All @@ -55,7 +59,7 @@ MatchReportDecoration => {
return EMPTY_DECORATION
}

const createMatchResultMessage = (match, decorations): string => {
const createMatchResultMessage = (match: Match, decorations: MatchReportDecoration[]): string => {
const { team1, team2, team1Won, winningTeamRatingChange, losingTeamRatingChange } = match
let winningTeam, losingTeam
if (team1Won) {
Expand Down Expand Up @@ -94,9 +98,9 @@ const createMatchResultMessage = (match, decorations): string => {
return messageParts.join(' ')
}

const ratingComparator = (a, b): number => b.rating - a.rating
const ratingComparator = (a: Player, b: Player): number => b.rating - a.rating

const createPurposeMessage = async (rankings): Promise<string> => {
const createPurposeMessage = async (rankings: Player[]): Promise<string> => {
const rankingsText = rankings
.map((ranking, i) => `${i + 1}. ${ranking.name} (${ranking.rating})`)
.join('\n')
Expand All @@ -108,21 +112,23 @@ export class MatchReporter {
readonly decorations: MatchReportDecoration[]
constructor(
readonly bot: SingleChannelBot,
matchReportPrefixSuffixConfig,
matchReportPrefixSuffixConfig: string | undefined,
readonly leaderboardSize = DEFAULT_LEADERBOARD_SIZE
) {
try {
this.decorations = parseMatchReportDecorations(matchReportPrefixSuffixConfig)
} catch (e) {
console.warn(`Parsing matchReportPrefixSuffixConfig failed: ${e.message}`)
this.decorations = []
}
}

async reportMatchOnSlack(match, oldUsers, newUsers): Promise<void> {
async reportMatchOnSlack(match: Match, oldPlayers: Player[], newPlayers: Player[]):
Promise<void> {
const matchResultMessage = createMatchResultMessage(match, this.decorations)

const oldRankings = oldUsers.sort(ratingComparator)
const newRankings = newUsers.sort(ratingComparator)
const oldRankings = oldPlayers.sort(ratingComparator)
const newRankings = newPlayers.sort(ratingComparator)

const rankingChangeMessage = createRankingChangeMessage(oldRankings, newRankings)
await this.bot.postMessage(`${matchResultMessage}\n${rankingChangeMessage}`)
Expand Down
6 changes: 6 additions & 0 deletions backend/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions backend/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
"slackbots": "^1.2.0"
},
"devDependencies": {
"@types/common-tags": "^1.8.0",
"@types/express": "^4.17.3",
"@types/jest": "^25.1.4",
"@types/node": "^13.9.0",
Expand Down
6 changes: 4 additions & 2 deletions backend/rating/rating-calculator.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { RatingChanges } from '../types/RatingChanges'
import { Player } from '../types/Player'

const average = (array): number => {
const average = (array: number[]): number => {
const sum = array.reduce((a, b) => a + b)
return sum / array.length
}
Expand All @@ -22,7 +23,8 @@ const average = (array): number => {
*
* @returns {RatingChanges} The rating changes of the teams.
*/
export const computeRatingChanges = (winningTeam, losingTeam): RatingChanges => {
export const computeRatingChanges = (winningTeam: Player[], losingTeam: Player[]):
RatingChanges => {
const winningAvg = average(winningTeam.map(player => player.rating))
const losingAvg = average(losingTeam.map(player => player.rating))

Expand Down
4 changes: 2 additions & 2 deletions backend/repositories/GameRepository.test.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { mocked } from 'ts-jest/utils'
import { FOOSBALL_DATA } from '../tests/TestData'
import { FOOSBALL_DATA, FOOSBALL_GAME } from '../tests/TestData'

import { insertGame } from '../storage/Storage'
import { addGame } from './GameRepository'
Expand Down Expand Up @@ -30,7 +30,7 @@ describe('GameRepository', () => {
})
describe('when insertGame resolves', () => {
beforeEach(() => {
mockedInsertGame.mockResolvedValue(undefined)
mockedInsertGame.mockResolvedValue(FOOSBALL_GAME)
})
})
it('stores a valid foosball data via insertGame', async () => {
Expand Down
4 changes: 2 additions & 2 deletions backend/repositories/GameRepository.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,8 @@ import * as storage from '../storage/Storage'

const isValidGameData = (data: unknown): data is GameData => {
const gameData = data as GameData
return gameData.name &&
gameData.description &&
return !!gameData.name &&
!!gameData.description &&
gameData.name.trim() == gameData.name &&
gameData.name.toLowerCase() == gameData.name &&
!gameData.name.includes(' ') &&
Expand Down
2 changes: 1 addition & 1 deletion backend/repositories/MatchRepository.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ describe('MatchRepository', () => {
.mockResolvedValueOnce(RADEK_PLAYER)
.mockResolvedValueOnce(PETR_PLAYER)
mockedGetLatestMatchByGameId.mockResolvedValueOnce(FOOSBALL_MATCH_WITH_ID)
mockedStoreMatch.mockResolvedValueOnce(undefined)
mockedStoreMatch.mockResolvedValueOnce(FOOSBALL_MATCH_WITH_ID)
})
describe('called one minute later', () => {
lockDate(ONE_MINUTE_AFTER)
Expand Down
16 changes: 7 additions & 9 deletions backend/repositories/MatchRepository.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ const getFilledTeam = async (playedIds: Array<number>): Promise<Array<Player>> =
}
}

const getRatingChanges = ({ team1, team2 }, team1Won): RatingChanges => {
const getRatingChanges = (team1: Player[], team2: Player[], team1Won: boolean): RatingChanges => {
const winningTeam = team1Won ? team1 : team2
const losingTeam = team1Won ? team2 : team1

Expand All @@ -31,18 +31,16 @@ const getRatingChanges = ({ team1, team2 }, team1Won): RatingChanges => {

const constructMatch = async (gameId: number, matchDescription: MatchDescription):
Promise<Match> => {
const teams = {
team1: await getFilledTeam(matchDescription.team1),
team2: await getFilledTeam(matchDescription.team2),
}
const team1 = await getFilledTeam(matchDescription.team1)
const team2 = await getFilledTeam(matchDescription.team2)
const {
winningTeamRatingChange,
losingTeamRatingChange,
} = getRatingChanges(teams, matchDescription.team1Won)
} = getRatingChanges(team1, team2, matchDescription.team1Won)
const date = new Date()
return new Match(
teams.team1,
teams.team2,
team1,
team2,
matchDescription.team1Won,
date,
winningTeamRatingChange,
Expand All @@ -51,7 +49,7 @@ Promise<Match> => {
)
}

const getElapsedSecondsSinceLatestMatch = async (gameId: number): Promise<number> => {
const getElapsedSecondsSinceLatestMatch = async (gameId: number): Promise<number | null> => {
const latestMatch = await storage.getLatestMatchByGameId(gameId)
if (latestMatch == null) {
return null
Expand Down
11 changes: 7 additions & 4 deletions backend/storage/Storage.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,14 @@ import * as dbTransactions from './db/db-transactions'
import { StorageContext } from './StorageContext'
import { User, UserData } from '../types/User'
import { MatchWithId, Match } from '../types/Match'
import { Game } from '../types/Game'
import { Game, GameData } from '../types/Game'
import { Player } from '../types/Player'

export const makeStorageContext = async (): Promise<StorageContext> => {
const transaction = await dbTransactions.beginTransaction()
if (!transaction) {
throw new Error('Failed to create transaction')
}
return new StorageContext(transaction)
}

Expand All @@ -29,7 +32,7 @@ export const getAllUsers = async (): Promise<Array<User>> => {
return executeAndCommit(context => context.getAllUsers())
}

export const getUser = async (userId): Promise<User> => {
export const getUser = async (userId: number): Promise<User> => {
return executeAndCommit(context => context.getUser(userId))
}

Expand All @@ -49,7 +52,7 @@ export const getAllMatches = async (): Promise<Array<MatchWithId>> => {
return executeAndCommit(context => context.getAllMatches())
}

export const getLatestMatchByGameId = async (gameId: number): Promise<MatchWithId> => {
export const getLatestMatchByGameId = async (gameId: number): Promise<MatchWithId | null> => {
return executeAndCommit(context => context.getLatestMatchByGameId(gameId))
}

Expand All @@ -61,7 +64,7 @@ export const getGameByName = async (name: string): Promise<Game> => {
return executeAndCommit(context => context.getGameByName(name))
}

export const insertGame = async (game): Promise<Game> => {
export const insertGame = async (game: GameData): Promise<Game | null> => {
return executeAndCommit(context => context.insertGame(game))
}

Expand Down
Loading