const log = require('t-log');

function valueChain(data, chain, defaultVal) {
  const keys = chain.split('.');
  const l = keys.length;
  let i = 0;
  let value = data;

  try {
    for (; i < l; i++) {
      value = value[keys[i]];
    }
  } catch (e) {
    log.error(`Read value of ${chain} on '${keys[i]}' error:\n`, e.stack);
    value = defaultVal;
  }

  if (value === undefined || value === null) {
    value = defaultVal;
  }

  return value;
}
// strange! 非常奇怪，getValue函数定义不能换行，否则只要对data做了原型扩展，
// 暂不清楚，换行对headers设置有何种影响
// 在代理转发的地方(request-proxy.js)pipe(res)就会报如下错误：
// TypeError: The header content contains invalid characters
// at ServerResponse.OutgoingMessage.setHeader (_http_outgoing.js:358:11)
//
// https://www.alexkras.com/typeerror-the-header-content-contains-invalid-characters/
function getValue(chain, defaultVal) { return valueChain.set(valueChain(this, chain, defaultVal)); }
function getList(chain) { return getValue.call(this, chain, []); }
function getMap(chain) { return getValue.call(this, chain, {}); }

valueChain.set = obj => {
  if (!obj) {
    return obj;
  }
  // 扩展数据原型，增加getValue方法
  const proto = Object.getPrototypeOf(obj);
  proto.getValue = getValue;
  proto.getList = getList;
  proto.getMap = getMap;

  return obj;
};

module.exports = valueChain;

@@ -504,35 +504,14 @@
 %0A// 
-%E6%9A%82%E4%B8%8D%E6%B8%85%E6%A5%9A%EF%BC%8C%E6%8D%A2%E8%A1%8C%E5%AF%B9headers%E8%AE%BE%E7%BD%AE%E6%9C%89%E4%BD%95%E7%A7%8D%E5%BD%B1%E5%93%8D%0A// %E5%9C%A8
+%E5%9C%A8%E6%B8%B2%E6%9F%93%E8%A7%86%E5%9B%BE%E5%8F%8A
 %E4%BB%A3%E7%90%86%E8%BD%AC%E5%8F%91
@@ -684,16 +684,42 @@
 358:11)%0A
+// %E6%9A%82%E4%B8%8D%E6%B8%85%E6%A5%9A%EF%BC%8C%E6%8D%A2%E8%A1%8C%E5%AF%B9headers%E8%AE%BE%E7%BD%AE%E6%9C%89%E4%BD%95%E7%A7%8D%E5%BD%B1%E5%93%8D%0A
 //%0A// ht

update comments