Blog2019 ≫ I had a dream about api responses

Hmm insane, I wonder if I am ill? I did not sleep well again last night, and woke up in a sweat, for the third night in a row. I don't think the dream about api responses caused the waking up, nor even the not sleeping. Weather has been bad and noise for the past few days and that has been the cause. Mostly.

Anyway I know recently after changing routers and things I was looking at the response from my home automation api and it always responds with something like { ok: true } when it's ok, because it's nice to get a response and it's nice for it to be an object so you can add more details to it. So if things were not ok it might respond { ok: false, message: 'light switch not responding' } for example. Or just { message: 'light switch not responding' }, because if ok is undefined then it is falsey and that's what we want.

Then I thought, I never do anything with this response except read it, so should it be just text? But what if I need to add extra properties? Hey, this is javascript and everything truthy can have extra properties! So what if instead of something like (crazy pseudocode it's not really like this in my real api1):

// ok = true or false
// room = 'lounge'
// device = 'lounge'
if (ok) {
  return { ok, room, device }
}
return { message: 'something went wrong', room, device }

I did this?

response = ok ? 'ok' : new Error('something went wrong')
response.room = room
response.device = device
return response

This means the response is more easily readable, but still has all the properties we need. And if we have an error then it's an error.

I know this is not interesting to anyone else but I think it might be a thing I can work with.

js: Programming language of the web, mostly how I make my living.

⬅️ :: ➡️

Paul Clarke's blog - I live in Hythe near Folkestone. Wed to Clare + dad to two, I am a full stack web developr, and I do mostly javascript / nodejs, some ruby, python, php etc. I like pubbing, parkrun, restaurants, home automation and other diy jiggery-pokery, history, family tree stuff, TV, squirrels, pirates, lego, + time travel.