63 lines
2.2 KiB
TypeScript
63 lines
2.2 KiB
TypeScript
import MongoStoredObjectCollection from "./MongoStoredObjectCollection";
|
|
import {ActiveRecordId} from "../Objects/ActiveRecord";
|
|
import PlayerCollection from "./PlayerCollection";
|
|
import SavedGame from "../Objects/SavedGame";
|
|
import {getMongoObjectCollection} from "../database";
|
|
import RulesetCollection from "./RulesetCollection";
|
|
import {ProcessedGameSubmission, ScoredResultsWithOutcome} from "../Controllers/statsController";
|
|
|
|
export interface SavedGameMongoData {
|
|
id: string;
|
|
ruleset: ActiveRecordId;
|
|
players: ActiveRecordId[];
|
|
results: ScoredResultsWithOutcome[];
|
|
}
|
|
|
|
class SavedGameCollection extends MongoStoredObjectCollection<SavedGameMongoData> {
|
|
private static instance?: SavedGameCollection;
|
|
constructor() {
|
|
super();
|
|
}
|
|
|
|
static getInstance(): SavedGameCollection {
|
|
if (SavedGameCollection.instance === undefined) {
|
|
SavedGameCollection.instance = new SavedGameCollection();
|
|
}
|
|
return SavedGameCollection.instance;
|
|
}
|
|
|
|
async init() {
|
|
this.mongoDbClientCollection = getMongoObjectCollection("savedGames");
|
|
}
|
|
|
|
private async savedGameFrom(data: SavedGameMongoData): Promise<SavedGame> {
|
|
const playerList: {name: string, id: ActiveRecordId}[] = [];
|
|
for (const playerId of data.players) {
|
|
const player = await PlayerCollection().read(playerId);
|
|
playerList.push({name: player.getNick(), id: playerId})
|
|
}
|
|
const rulesetUsed = await RulesetCollection().read(data.ruleset);
|
|
return new SavedGame(
|
|
data.id,
|
|
{name: rulesetUsed.getName(), id: data.ruleset},
|
|
playerList,
|
|
data.results);
|
|
}
|
|
|
|
async read(id: ActiveRecordId): Promise<SavedGame> {
|
|
const foundGame = await this.mongoRead(id);
|
|
return this.savedGameFrom(foundGame);
|
|
}
|
|
|
|
async create(submission: ProcessedGameSubmission): Promise<SavedGame> {
|
|
const pids = submission.players.map(playerIdAndNick => playerIdAndNick.id);
|
|
return this.savedGameFrom(
|
|
await this.mongoCreate({
|
|
ruleset: submission.ruleset,
|
|
players: pids,
|
|
results: submission.results})
|
|
);
|
|
}
|
|
}
|
|
|
|
export default SavedGameCollection.getInstance; |