jkchao / typescript-book-chinese

TypeScript Deep Dive 中文版
https://jkchao.github.io/typescript-book-chinese/
MIT License
6.53k stars 673 forks source link

Tips 下 Reflect Metadata得章节 Controller 与 Get 的实现 案例有误!缺少函数 isFunction 和 isConstructor #220

Open martin-yin opened 3 years ago

martin-yin commented 3 years ago
function mapRoute(instance: Object) {
  const prototype = Object.getPrototypeOf(instance);

  // 筛选出类的 methodName
  const methodsNames = Object.getOwnPropertyNames(prototype)
                              .filter(item => !isConstructor(item) && isFunction(prototype[item]));
  return methodsNames.map(methodName => {
    const fn = prototype[methodName];

    // 取出定义的 metadata
    const route = Reflect.getMetadata(PATH_METADATA, fn);
    const method = Reflect.getMetadata(METHOD_METADATA, fn);
    return {
      route,
      method,
      fn,
      methodName
    }
  })
};

这里缺少 isConstructor 和 isFunction函数。

测试之后,加上这俩函数即可解决问题。

export const isFunction = (fn: any): boolean => typeof fn === 'function';
export const isConstructor = (fn: any): boolean => fn === 'constructor';