triangle-exclamationState

// Could be an Abastract Class instead of an Interface
export default interface RideStatus {
    value: string;
    request(): void;
    accept(): void;
    start(): void;
    finish(): void;
}

export class RequestedStatus implements RideStatus {
    value: string;
    constructor(readonly ride: Ride) { this.value = 'requested'; }
    
    // Cannot request the ride again if state is already requested
    request(): void { throw new Error('Invalid State'); }
    // Setup next possible status after request
    accept(): void { this.ride.setStatus(new AcceptedStatus(this.ride)); }
    start(): void { throw new Error('Invalid State'); }
    finish(): void { throw new Error('Invalid State'); }
}

export class AcceptedStatus implements RideStatus {
    value: string;
    constructor(readonly ride: Ride) { this.value = 'accepted'; }
    
    request(): void { throw new Error('Invalid State'); }
    // Cannot accept the ride again if state is already accepted
    accept(): void { throw new Error('Invalid State'); }
    // Setup next possible status after request
    start(): void { this.ride.setStatus(new InProgressStatus(this.ride)); }
    finish(): void { throw new Error('Invalid State'); }
}

export class InProgressStatus implements RideStatus {
    value: string;
    constructor(readonly ride: Ride) { this.value = 'in_progress'; }
    
    request(): void { throw new Error('Invalid State'); }    
    accept(): void { throw new Error('Invalid State'); }
    // Cannot start the ride again if state is already started
    start(): void { throw new Error('Invalid State'); }
    // Setup next possible status after request
    finish(): void { this.ride.setStatus(new CompletedStatus(this.ride)); }
}

export class CompletedStatus implements RideStatus {
    value: string;
    constructor(readonly ride: Ride) { this.value = 'completed'; }
    
    request(): void { throw new Error('Invalid State'); }    
    accept(): void { throw new Error('Invalid State'); }
    start(): void { throw new Error('Invalid State'); }
    // Cannot finish the ride again if state is already completed
    finish(): void { throw new Error('Invalid State'); }
}

Last updated