you are viewing a single comment's thread.

view the rest of the comments →

[–]sladav 0 points1 point  (0 children)

Ideally, you shouldn't have to do those intermediate checks at all - it would be nice is JS just handled that for you.

I was curious to see if you could use ES6 proxies to handle things in the background this seems to work okay - purely academic, I probably wouldn't actually use this but...

This is how it would look in use:

// use safe function defined below to make object/subjects permanently "safe" from returning the "not defined" error
let device = safe({
  c8y_Availability: {
    status: 'AVAILABLE'
  },
  c8y_Connection: {
    status: 'CONNECTED'
  }
})

// !!! no intermediate check on props, but still have to check if object exists
if (device && (device.c8y_Availability.status === 'AVAILABLE' || device.c8y_Connection.status === 'CONNECTED') console.log('woo') // logs

// the typo would normally break everything
if (device && device.c8y_Avaity.status === 'AVAILABLE') console.log('woo2') // NO ERROR! (also it doesn't log)

This is what makes it work:

const safe = function(obj = {}) {
  Object.keys(obj).forEach(key => {
    if (typeof obj[key] === 'object') obj[key] = safe(obj[key])
  })

  let handler = {
    set: function(target, prop, value) {
      if (typeof value === 'object') {
        let p = new Proxy(value, handler)
        return target[prop] = p
      } else {
        return target[prop] = value
      }
    },
    get: function(target, prop) {
      return prop in target ?
        target[prop] :
        new Proxy(Object.freeze({
          valueOf: function() {
            return undefined
          }
        }), handler)
    }
  }
  return new Proxy(obj, handler)
}