Discussion regarding the complex response structure for REST & GraphQL (Developer Experience)

When working with the new response for a few days, it somehow started to bug me to mistype attributes every single time and missing the ‘old’ response. I decided to write a normalizer function which looks into deep objects & arrays. In case somebody want’s to work with this, here’s the code. It’s not implemented into the API, but into Nuxt in the frontend.

const normalize = (data) => {
  const isObject = (data) =>
    Object.prototype.toString.call(data) === '[object Object]'
  const isArray = (data) =>
    Object.prototype.toString.call(data) === '[object Array]'

  const flatten = (data) => {
    if (!data.attributes) return data

    return {
      id: data.id,
      ...data.attributes
    }
  }

  if (isArray(data)) {
    return data.map((item) => normalize(item))
  }

  if (isObject(data)) {
    if (isArray(data.data)) {
      data = [...data.data]
    } else if (isObject(data.data)) {
      data = flatten({ ...data.data })
    } else if (data.data === null) {
      data = null
    } else {
      data = flatten(data)
    }

    for (const key in data) {
      data[key] = normalize(data[key])
    }

    return data
  }

  return data
}
15 Likes