Skip to content
Snippets Groups Projects
game.service.ts 1.54 KiB
Newer Older
import { Injectable, Logger } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { GameEntity, FactionEntity } from './game.entity';
import { FactionDTO, GameDTO } from './game.dto';

@Injectable()
export class GameService {
  constructor(
    @InjectRepository(GameEntity)
    private gameRepository: Repository<GameEntity>,
    @InjectRepository(FactionEntity)
    private factionRepository: Repository<FactionEntity>,
L4168's avatar
L4168 committed
  ) { }

  // create a new game
  async createNewGame(
    personId: string,
    gameData: GameDTO,
    factions: FactionDTO[],
  ) {
    const game = await this.gameRepository.create({
      ...gameData,
      factions: factions,
    });
    await this.gameRepository.insert(game);
L4168's avatar
L4168 committed
    // get the id of the game created to pass it to factions table
    const gameid = await this.gameRepository.findOne({ where: { name: gameData.name } })

    factions.map(async faction => {
L4168's avatar
L4168 committed
      let name = await this.factionRepository.create({
        ...faction,
        game: gameid
      });
      await this.factionRepository.insert(name);
    });
    return 'success';
L4168's avatar
L4168 committed
  }
L4168's avatar
L4168 committed
  // returns name and id of each game
  async listGames() {
    const games = await this.gameRepository.find({ relations: ['factions'] });
    return games.map(game => {
L4168's avatar
L4168 committed
      return { game };
L4168's avatar
L4168 committed

  // returns information about a game identified by id
  async returnGameInfo(id: string) {
    const game = await this.gameRepository.findOne({ where: { id: id }, relations: ['factions'] });
    return game;
  }
}