diff --git a/src/game/game.service.ts b/src/game/game.service.ts index 829586614b86962597fd6b7e686d9c905f5b3938..624ae20e2005017fdea3ba8bf49a8cc18408fd6a 100644 --- a/src/game/game.service.ts +++ b/src/game/game.service.ts @@ -65,22 +65,27 @@ export class GameService { HttpStatus.BAD_REQUEST, ); } - // update game entry in db + + // get factions that have been added previously let factions = await this.factionRepository.find({ game: id }); + // get flagboxes that have been added previously + let flagboxes = await this.objectivePointRepository.find({ + game: id, + }); + console.log(flagboxes); + // update game entry in db const updatedGame = await this.gameRepository.create(gameData); const gameId = await this.gameRepository.save(updatedGame); - // delete removed factions - // update/insert factions + // iterate factions if any were added if (gameData.factions) { - const factionNames = gameData.factions.map( - ({ factionName }) => factionName, - ); const factionIds = gameData.factions.map(({ factionId }) => factionId); + // delete all existing factions that are not in submitted data factions.map(async faction => { - if (!factionNames.includes(faction.factionName)) { + if (!factionIds.includes(faction.factionId)) { await this.factionRepository.delete(faction); } }); + // create / update factions present in the submitted data gameData.factions.map(async faction => { let name = await this.factionRepository.create({ ...faction, @@ -89,29 +94,29 @@ export class GameService { await this.factionRepository.save(name); }); } else { + // if no factions are present in data, delete all factions associated with the game await this.factionRepository.delete({ game: id }); } - // get old flagboxes to deny duplicate entries - const flagboxes = await this.objectivePointRepository.find({ - game: gameId, - }); - const flagboxIds = flagboxes.map( - ({ objectivePointDescription }) => objectivePointDescription, - ); // insert the flagboxes to db if (gameData.objective_points) { - gameData.objective_points.map(async flagbox => { - if ( - !Object.values(flagboxIds).includes(flagbox.objectivePointDescription) - ) { - let newFlagbox = await this.objectivePointRepository.create({ - ...flagbox, - game: gameId, - }); - await this.objectivePointRepository.insert(newFlagbox); + const flagboxIds = gameData.objective_points.map( + ({ objectivePointId }) => objectivePointId, + ); + flagboxes.map(async flagbox => { + if (!flagboxIds.includes(flagbox.objectivePointDescription)) { + await this.objectivePointRepository.delete(flagbox); } }); + gameData.objective_points.map(async flagbox => { + let newFlagbox = await this.objectivePointRepository.create({ + ...flagbox, + game: gameId, + }); + await this.objectivePointRepository.save(newFlagbox); + }); + } else { + await this.objectivePointRepository.delete({ game: id }); } // TO DO: ADD FLAGBOX LOCATION TO MAPDRAWING ENTITY