Match.Optional for null

Secur­ing my Mete­or app, I came across a strange quirk of Match.Optional of the “check” pack­age.
Exam­ple (in Cof­fee­Script)

  test: (x) -> check x, Match.Optional String

I expect­ed the match to be suc­cess­ful when call­ing the method like this: 'test', undefined

But instead, I got a “Match failed” excep­tion. After debug­ging for a bit, it turned out that the undefined becomes a null when it arrives on the server.
Which is odd, of course—but also annoy­ing as the check x, Match.Optional String fails for null (only undefined or String are accept­able).
To over­come this, here is a new Match.Optional that does the trick:

Match.OptionalOrNull = (pattern) -> Match.OneOf undefined, null, pattern

Also, I keep won­der­ing: what’s the pur­pose of mak­ing Match.Optional fail on null in the first place?

Leave a Reply

Your email address will not be published. Required fields are marked *