Manual Reference Source Test

src/utilities/JsonApiUtility.js

/**
 * Flattens the json api format to a normal format
 *
 * @param  {Object} json  - Json to flatten
 * @return {Object}       - Flattened json
 */
function flattenJsonApi(json) {
  const obj = {
    id: json.id,
    type: json.type
  };
  if (json.relationships) {
    obj.relationships = json.relationships;
  }
  if (json.attributes) {
    obj.attributes = json.attributes;
  }
  if (json.meta) {
    obj.meta = json.meta;
  }
  return obj;
}

/**
 * Returns the type if the format is json api type.
 *
 * @param  {Object} json  - Data if it's in json api format, return the type
 * @return {String}       - Return type
 */
function getJsonApiType(json) {
  let type;
  if (json) {
    // Use the type inside an array if it exists.
    if (Array.isArray(json) && json[0] && json[0].type) {
      ([{ type }] = json);
    }

    // Use the type if it exists in the object
    if (json.type) {
      ({ type } = json);
    }
  }
  return type;
}


/**
 * Returns if the format is json api type.
 *
 * @param  {Object} json  - Check if it's in json api format
 * @return {Boolean}      - Return true or false
 */
function isJsonApiFormat(json) {
  let isFormat = false;
  if (json) {
    const data = json.data || json;
    if (Array.isArray(data) && data[0] && data[0].type) {
      isFormat = true;
    } else if (data.type) {
      isFormat = true;
    }
  }
  return isFormat;
}

export {
  flattenJsonApi,
  getJsonApiType,
  isJsonApiFormat
};