Last time we have to implement the requirement:
Meeting Obsolete:
The meeting is available for 35 minutes. After that,meeting is not available anymore.
We did so for the 35 minutes. But we did not for the last sentence – meeting is not available anymore. There are 2 points here: of design ( do not retrieve meeting ) and enforcing that no participant can write to the meeting.
So we modify the functions AddParticipant,CheckCardByParticipant to raise an exception if the meeting is obsolete .( As a side effect of identifying the functions that make actions in the opposite of functions that just reports,I think about structuring code in CQRS form )
Now for TypeScript we have 2 options :
- Construct a class that inherits from Error
 - Modify the response type of those function to a combined type of result and error
 
For the first one,we should take care of TypeScript syntax of creating errors: See https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-2.html and https://github.com/Microsoft/TypeScript-wiki/blob/master/Breaking-Changes.md#extending-built-ins-like-error-array-and-map-may-no-longer-work
class CustomError extends Error {
constructor(message?: string) {
super(message);
// ‘Error’ breaks prototype chain here
Object.setPrototypeOf(this,new.target.prototype); // restore prototype chain
}
}
For the second,we could do ourselves or use a npm package such as https://github.com/gDelgado14/neverthrow
I decide to go to the second. I have too many times use the first thing in C# – it is time to have something new. Anyway,this is the code now
    import { ok,err,Result } from 'neverthrow';
//code
    public CheckCardByParticipant(c: Cards,p:Participant): Result<Meeting,Error>{
        //TODO: verify participant is added first or add
        //TODO: verify card is added first
        if(this.IsObsolete()){
            return err(new Error(`cannot check card to the obsolete meeting ${this.Id}`));
        }
        c.CheckMe(p);
        return ok(this);
    }
//code
    public AddParticipant(p:Participant ): Result<number,Error>{
        if(this.IsObsolete()){
            return err(new Error(`cannot add participant to the obsolete meeting ${this.Id}`));
        }
        this.Participants.push(p);
        return ok(this.Participants.length);
    }
and those are the tests
        const mf=new MeetingsFactory();
        const m1=mf.CreateMeeting("andrei","first meeting");
        const now = Date.now();
        const spy = jest.spyOn(Date,'now');
        spy.mockImplementation(()=>{
          console.log('calling DateTime Now');
          return now + 36 * 60* 1000;
        } );
        expect(m1.IsObsolete()).toBe(true);
        const p=new Participant();
        p.Id=70;
        p.Name ="alexandru";
        const res= m1.AddParticipant(p);
        expect(res.isOk()).toBe(false);
        spy.mockRestore();
Leave a Reply