From e93abfeae12707ea5f80074a39dc913fa37c0c5c Mon Sep 17 00:00:00 2001 From: Tau Date: Fri, 26 Apr 2019 16:37:42 -0400 Subject: [PATCH] Fix empty garage condition during profile creation --- src/idz/world/car.ts | 22 ++++++++++++++++------ 1 file changed, 16 insertions(+), 6 deletions(-) diff --git a/src/idz/world/car.ts b/src/idz/world/car.ts index 452939b..be730f0 100644 --- a/src/idz/world/car.ts +++ b/src/idz/world/car.ts @@ -1,3 +1,5 @@ +import { existsSync } from "fs"; + import { loadJson, saveJson } from "./_util"; import { CarRepository } from "./defs"; import { Id } from "../model/base"; @@ -5,7 +7,7 @@ import { Car, CarSelector } from "../model/car"; import { Profile } from "../model/profile"; interface GarageJson { - selected: CarSelector; + selected?: CarSelector; cars: Car[]; } @@ -16,20 +18,28 @@ export class CarRepositoryImpl implements CarRepository { this._path = root + "/garage.json"; } + private async _loadJson(): Promise { + if (existsSync(this._path)) { + return loadJson(this._path); + } else { + return { cars: [] }; + } + } + async countCars(profileId: Id): Promise { - const garage: GarageJson = await loadJson(this._path); + const garage: GarageJson = await this._loadJson(); return garage.cars.length; } async loadAllCars(profileId: Id): Promise { - const garage: GarageJson = await loadJson(this._path); + const garage: GarageJson = await this._loadJson(); return garage.cars; } async loadSelectedCar(profileId: Id): Promise { - const garage: GarageJson = await loadJson(this._path); + const garage: GarageJson = await this._loadJson(); const sel = garage.cars.find(item => item.selector === garage.selected); if (sel === undefined) { @@ -40,7 +50,7 @@ export class CarRepositoryImpl implements CarRepository { } async saveCar(profileId: Id, car: Car): Promise { - const garage: GarageJson = await loadJson(this._path); + const garage: GarageJson = await this._loadJson(); const rest = garage.cars.filter(item => item.selector != car.selector); const updated = { ...garage, cars: [...rest, car] }; @@ -52,7 +62,7 @@ export class CarRepositoryImpl implements CarRepository { profileId: Id, selection: CarSelector ): Promise { - const garage: GarageJson = await loadJson(this._path); + const garage: GarageJson = await this._loadJson(); const match = garage.cars.find(item => item.selector === selection); if (!match) {