【问题标题】:Nestjs swagger issueNestjs招摇问题
【发布时间】:2020-02-24 00:38:37
【问题描述】:

我正在尝试将 swagger 添加到我的 nestjs 应用程序中,这是我遇到的错误。

(node:78477) UnhandledPromiseRejectionWarning: TypeError: Cannot read property '0' of undefined
    at lodash_1.mapValues.param (/Users/anna/SoFetch/node_modules/@nestjs/swagger/dist/explorers/api-parameters.explorer.js:34:20)
    at /Users/anna/SoFetch/node_modules/@nestjs/swagger/node_modules/lodash/lodash.js:13401:38
    at /Users/anna/SoFetch/node_modules/@nestjs/swagger/node_modules/lodash/lodash.js:4905:15
    at baseForOwn (/Users/anna/SoFetch/node_modules/@nestjs/swagger/node_modules/lodash/lodash.js:2990:24)
    at Function.mapValues (/Users/anna/SoFetch/node_modules/@nestjs/swagger/node_modules/lodash/lodash.js:13400:7)
    at exploreApiReflectedParametersMetadata (/Users/anna/SoFetch/node_modules/@nestjs/swagger/dist/explorers/api-parameters.explorer.js:33:41)
    at exports.exploreApiParametersMetadata (/Users/anna/SoFetch/node_modules/@nestjs/swagger/dist/explorers/api-parameters.explorer.js:11:33)
    at explorers.reduce (/Users/anna/SoFetch/node_modules/@nestjs/swagger/dist/swagger-explorer.js:55:45)
    at Array.reduce (<anonymous>)
    at lodash_1.mapValues (/Users/anna/SoFetch/node_modules/@nestjs/swagger/dist/swagger-explorer.js:54:97)
    at /Users/anna/SoFetch/node_modules/@nestjs/swagger/node_modules/lodash/lodash.js:13401:38
    at /Users/anna/SoFetch/node_modules/@nestjs/swagger/node_modules/lodash/lodash.js:4905:15
    at baseForOwn (/Users/anna/SoFetch/node_modules/@nestjs/swagger/node_modules/lodash/lodash.js:2990:24)
    at Function.mapValues (/Users/anna/SoFetch/node_modules/@nestjs/swagger/node_modules/lodash/lodash.js:13400:7)
    at MapIterator.denormalizedPaths.metadataScanner.scanFromPrototype.name [as iteratee] (/Users/anna/SoFetch/node_modules/@nestjs/swagger/dist/swagger-explorer.js:54:45)
    at MapIterator.next (/Users/anna/SoFetch/node_modules/iterare/lib/map.js:13:39)
    at FilterIterator.next (/Users/anna/SoFetch/node_modules/iterare/lib/filter.js:12:34)
    at IteratorWithOperators.next (/Users/anna/SoFetch/node_modules/iterare/lib/iterate.js:21:28)
    at Function.from (<anonymous>)
    at IteratorWithOperators.toArray (/Users/anna/SoFetch/node_modules/iterare/lib/iterate.js:180:22)
    at MetadataScanner.scanFromPrototype (/Users/anna/SoFetch/node_modules/@nestjs/core/metadata-scanner.js:11:14)
    at SwaggerExplorer.generateDenormalizedDocument (/Users/anna/SoFetch/node_modules/@nestjs/swagger/dist/swagger-explorer.js:48:56)
(node:78477) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:78477) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

我将问题缩小到控制器。这里是:

constructor(@Inject('UserService') private  readonly  userService:  UserService) {}
    @Post('login')
    async login(@Body() login: LoginModel): Promise<any> {
      return this.userService.login(login.username, login.password);
    }  

    @Post('register/customer')
    async registerCustomer(@Body() customer: CustomerRegisterModel): Promise<any> {
        if(customer.password !== customer.confirmPassword) {
            throw new NotAcceptableException();
        }
      return this.userService.createCustomer(customer.name, customer.username, customer.email, customer.password);  
    }

    @Post('register/technician')
    async registerTechnician(@Body() technician: TechnicianRegistrationModel): Promise<any> {
        return this.userService.createTechnician(technician.name, technician.username, technician.email, technician.password, technician.location); 
    }  

这个控制器不工作,但是当我添加一个像这样的简单方法时:

    @Get()
     Hello(login: string):string{
      return "helloworld"
    }

它有效。

我的@Body @Query 属性似乎有问题。但我找不到它。

其他人有同样的问题吗?

【问题讨论】:

  • 我在你的实现中没有看到 swagger 的代码。
  • 我使用的是nest.js recipies 文档中的标准东西。在 main.ts 中添加了const options = new DocumentBuilder() .setTitle('Cats example') .setDescription('The cats API description') .setVersion('1.0') .addTag('cats') .build(); const document = SwaggerModule.createDocument(app, options); SwaggerModule.setup('api', app, document); 代码
  • 你的TechnicianRegistrationModelCustomerRegisterModelLoginModel是接口还是类? :)
  • 这些是类。我评论 Post 方法的那一刻,大摇大摆的工作。
  • 您能分享一下您定义这些模型类的方式吗?至少你在其中使用 swagger 注释的方式

标签: node.js swagger nestjs


【解决方案1】:

我在添加@Body() ... 参数装饰器后遇到了同样的错误,最后我通过将tsconfig.json 文件替换为以下内容来解决它。

{
  "compilerOptions": {
    "module": "commonjs",
    "declaration": false,
    "noImplicitAny": false,
    "removeComments": true,
    "noLib": false,
    "allowSyntheticDefaultImports": true,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "target": "es6",
    "sourceMap": true,
    "allowJs": false,
    "outDir": "./dist"
  },
  "include": [
    "src/**/*"
  ],
  "exclude": [
    "**/node_modules/*",
    "**/*.spec.ts"
  ]
}

发生了什么:swagger 文件parameter-metadata-accessor.js 中抛出了一个错误,特别是types 数组未定义,所以当parametersWithType 访问它时,它抛出了。

class ParameterMetadataAccessor {
    explore(instance, prototype, method) {
        const types = Reflect.getMetadata(constants_1.PARAMTYPES_METADATA, instance, method.name);
        const routeArgsMetadata = Reflect.getMetadata(constants_1.ROUTE_ARGS_METADATA, instance.constructor, method.name) || {};
        const parametersWithType = lodash_1.mapValues(reverse_object_keys_util_1.reverseObjectKeys(routeArgsMetadata), (param) => ({
            type: types[param.index],
            name: param.data,
            required: true
        }));
        ...
    }

【讨论】:

猜你喜欢
  • 2018-12-01
  • 2016-04-04
  • 1970-01-01
  • 2020-09-30
  • 2021-01-05
  • 1970-01-01
  • 1970-01-01
  • 2021-07-09
  • 2021-09-28
相关资源
最近更新 更多