From 52e0128258d019f1550686523d91f7d353a66c7d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Kamil=20My=C5=9Bliwiec?= Date: Thu, 21 Dec 2017 19:29:39 +0100 Subject: [PATCH] ci(@nestjs) integrate with prettier --- .prettierrc | 3 + .../01-cats-app/e2e/cats/cats.e2e-spec.ts | 4 +- .../01-cats-app/src/modules/app.module.ts | 15 +- .../src/modules/cats/cats.controller.spec.ts | 8 +- .../src/modules/cats/cats.controller.ts | 18 +- .../src/modules/cats/cats.module.ts | 6 +- .../src/modules/cats/cats.service.ts | 2 +- .../src/modules/cats/dto/create-cat.dto.ts | 11 +- .../modules/cats/interfaces/cat.interface.ts | 2 +- .../common/decorators/roles.decorator.ts | 2 +- .../common/exceptions/forbidden.exception.ts | 2 +- .../common/filters/http-exception.filter.ts | 4 +- .../src/modules/common/guards/roles.guard.ts | 5 +- .../common/interceptors/cache.interceptor.ts | 8 +- .../interceptors/exception.interceptor.ts | 26 +- .../interceptors/logging.interceptor.ts | 12 +- .../interceptors/mixin-cache.interceptor.ts | 10 +- .../interceptors/transform.interceptor.ts | 10 +- .../common/middlewares/logger.middleware.ts | 4 +- .../modules/common/pipes/parse-int.pipe.ts | 9 +- .../modules/common/pipes/validation.pipe.ts | 37 +- .../02-gateways/src/modules/app.module.ts | 4 +- .../src/modules/common/adapters/ws-adapter.ts | 16 +- .../common/decorators/roles.decorator.ts | 2 +- .../common/filters/ws-exception.filter.ts | 4 +- .../src/modules/common/guards/roles.guard.ts | 5 +- .../common/interceptors/cache.interceptor.ts | 8 +- .../interceptors/logging.interceptor.ts | 12 +- .../interceptors/transform.interceptor.ts | 10 +- .../modules/common/pipes/validation.pipe.ts | 37 +- .../src/modules/events/events.gateway.ts | 18 +- .../src/modules/events/events.module.ts | 6 +- .../src/modules/app.module.ts | 4 +- .../common/adapters/rabbitmq-client.ts | 29 +- .../common/adapters/rabbitmq-server.ts | 24 +- .../common/decorators/roles.decorator.ts | 2 +- .../common/filters/rpc-exception.filter.ts | 2 +- .../src/modules/common/guards/roles.guard.ts | 5 +- .../common/interceptors/cache.interceptor.ts | 8 +- .../interceptors/logging.interceptor.ts | 12 +- .../interceptors/transform.interceptor.ts | 10 +- .../modules/common/pipes/validation.pipe.ts | 28 +- .../src/modules/math/math.controller.ts | 9 +- .../src/modules/math/math.module.ts | 4 +- examples/03-microservices/src/server.ts | 2 +- .../04-injector/src/modules/app.module.ts | 4 +- .../src/modules/common/common.module.ts | 4 +- .../src/modules/common/common.service.ts | 2 +- .../src/modules/core/context.service.ts | 2 +- .../src/modules/core/core.module.ts | 4 +- .../src/modules/core/core.service.ts | 2 +- .../src/modules/feature/feature.module.ts | 4 +- .../src/modules/feature/feature.service.ts | 5 +- .../05-sql-typeorm/src/modules/app.module.ts | 5 +- .../src/modules/photo/photo.entity.ts | 17 +- .../src/modules/photo/photo.module.ts | 2 +- .../src/modules/photo/photo.service.ts | 3 +- .../06-mongoose/src/modules/app.module.ts | 4 +- .../src/modules/cats/cats.controller.ts | 2 +- .../src/modules/cats/cats.module.ts | 7 +- .../src/modules/cats/cats.providers.ts | 6 +- .../src/modules/cats/cats.service.ts | 5 +- .../src/modules/cats/dto/create-cat.dto.ts | 2 +- .../modules/cats/interfaces/cat.interface.ts | 2 +- .../src/modules/cats/schemas/cat.schema.ts | 4 +- .../src/modules/database/database.module.ts | 4 +- .../modules/database/database.providers.ts | 8 +- .../07-sequelize/src/modules/app.module.ts | 4 +- .../src/modules/cats/cat.entity.ts | 9 +- .../src/modules/cats/cats.controller.ts | 2 +- .../src/modules/cats/cats.module.ts | 7 +- .../src/modules/cats/cats.providers.ts | 6 +- .../src/modules/cats/cats.service.ts | 6 +- .../src/modules/cats/dto/create-cat.dto.ts | 2 +- .../src/modules/database/database.module.ts | 4 +- .../modules/database/database.providers.ts | 8 +- .../08-passport/src/modules/app.module.ts | 4 +- .../src/modules/auth/auth.module.ts | 9 +- .../src/modules/auth/auth.service.ts | 5 +- .../src/modules/auth/passport/jwt.strategy.ts | 2 +- .../10-mockgoose/e2e/cats/cats.e2e-spec.ts | 76 +- .../10-mockgoose/src/modules/app.module.ts | 4 +- .../src/modules/cats/cats.controller.ts | 2 +- .../src/modules/cats/cats.module.ts | 7 +- .../src/modules/cats/cats.providers.ts | 8 +- .../src/modules/cats/cats.service.ts | 5 +- .../src/modules/cats/dto/create-cat.dto.ts | 2 +- .../modules/cats/interfaces/cat.interface.ts | 2 +- .../src/modules/cats/schemas/cat.schema.ts | 4 +- .../src/modules/database/database.module.ts | 4 +- .../modules/database/database.providers.ts | 30 +- examples/11-swagger/src/modules/app.module.ts | 4 +- .../src/modules/cats/cats.controller.ts | 16 +- .../src/modules/cats/cats.module.ts | 6 +- .../src/modules/cats/cats.service.ts | 2 +- .../src/modules/cats/dto/create-cat.dto.ts | 2 +- .../modules/cats/interfaces/cat.interface.ts | 2 +- examples/11-swagger/src/server.ts | 18 +- .../src/modules/app.module.ts | 10 +- .../src/modules/cats/cats.module.ts | 2 +- .../src/modules/cats/cats.resolvers.ts | 13 +- .../src/modules/cats/cats.service.ts | 6 +- .../modules/cats/interfaces/cat.interface.ts | 2 +- .../src/modules/app.module.ts | 5 +- .../src/modules/photo/photo.entity.ts | 25 +- .../src/modules/photo/photo.module.ts | 2 +- .../src/modules/photo/photo.service.ts | 3 +- .../src/modules/app.module.ts | 6 +- .../src/modules/cats/cats.controller.ts | 2 +- .../src/modules/cats/cats.module.ts | 2 +- .../src/modules/cats/dto/create-cat.dto.ts | 2 +- .../modules/cats/interfaces/cat.interface.ts | 2 +- .../src/modules/cats/schemas/cat.schema.ts | 4 +- lib/common/constants.d.ts | 38 +- .../decorators/core/bind.decorator.d.ts | 4 +- .../core/exception-filters.decorator.d.ts | 4 +- .../core/reflect-metadata.decorator.d.ts | 5 +- .../decorators/core/use-guards.decorator.d.ts | 4 +- .../core/use-interceptors.decorator.d.ts | 4 +- .../decorators/core/use-pipes.decorator.d.ts | 4 +- ...create-route-param-metadata.decorator.d.ts | 4 +- .../http/request-mapping.decorator.d.ts | 4 +- .../http/route-params.decorator.d.ts | 23 +- .../invalid-module-config.exception.d.ts | 2 +- .../decorators/modules/module.decorator.d.ts | 8 +- lib/common/enums/http-status.enum.d.ts | 86 +- lib/common/enums/nest-environment.enum.d.ts | 4 +- lib/common/enums/request-method.enum.d.ts | 16 +- lib/common/enums/route-paramtypes.enum.d.ts | 16 +- lib/common/enums/transport.enum.d.ts | 4 +- .../exceptions/bad-gateway.exception.d.ts | 2 +- .../exceptions/bad-request.exception.d.ts | 2 +- lib/common/exceptions/conflict.exception.d.ts | 2 +- .../exceptions/forbidden.exception.d.ts | 2 +- .../exceptions/gateway-timeout.exception.d.ts | 2 +- lib/common/exceptions/gone.exception.d.ts | 2 +- lib/common/exceptions/http.exception.d.ts | 40 +- .../internal-server-error.exception.d.ts | 2 +- .../invalid-module-config.exception.d.ts | 2 +- .../method-not-allowed.exception.d.ts | 2 +- .../exceptions/not-acceptable.exception.d.ts | 2 +- .../exceptions/not-found.exception.d.ts | 2 +- .../exceptions/not-implemented.exception.d.ts | 2 +- .../payload-too-large.exception.d.ts | 2 +- .../exceptions/request-timeout.exception.d.ts | 2 +- .../service-unavailable.exception.d.ts | 2 +- .../exceptions/unauthorized.exception.d.ts | 2 +- .../unprocessable-entity.exception.d.ts | 2 +- .../unsupported-media-type.exception.d.ts | 2 +- lib/common/index.d.ts | 25 +- .../interfaces/can-activate.interface.d.ts | 5 +- .../configuration-provider.interface.d.ts | 4 +- .../controller-metadata.interface.d.ts | 2 +- .../controllers/controller.interface.d.ts | 3 +- .../exception-filter-metadata.interface.d.ts | 4 +- .../exception-filter.interface.d.ts | 2 +- ...c-exception-filter-metadata.interface.d.ts | 4 +- .../rpc-exception-filter.interface.d.ts | 2 +- .../ws-exception-filter.interface.d.ts | 2 +- .../execution-context.interface.d.ts | 4 +- .../interfaces/injectable.interface.d.ts | 3 +- lib/common/interfaces/metatype.interface.d.ts | 2 +- .../custom-transport-strategy.interface.d.ts | 4 +- .../microservice-configuration.interface.d.ts | 10 +- .../express-middleware.interface.d.ts | 2 +- .../express-midleware.interface.d.ts | 2 +- .../middleware-config-proxy.interface.d.ts | 42 +- .../middleware-configuration.interface.d.ts | 8 +- .../middlewares-consumer.interface.d.ts | 16 +- .../nest-middleware.interface.d.ts | 7 +- .../modules/dynamic-module.interface.d.ts | 2 +- .../modules/module-metadata.interface.d.ts | 8 +- .../modules/module-metatype.interface.d.ts | 3 +- .../modules/nest-module.interface.d.ts | 2 +- .../modules/on-destroy.interface.d.ts | 2 +- .../interfaces/modules/on-init.interface.d.ts | 2 +- .../nest-application-context.interface.d.ts | 20 +- .../nest-application.interface.d.ts | 230 ++-- .../nest-interceptor.interface.d.ts | 6 +- .../nest-microservice.interface.d.ts | 90 +- .../interfaces/pipe-transform.interface.d.ts | 13 +- .../request-mapping-metadata.interface.d.ts | 4 +- .../web-socket-adapter.interface.d.ts | 22 +- lib/common/pipes/parse-int.pipe.d.ts | 2 +- lib/common/pipes/validation.pipe.d.ts | 4 +- lib/common/services/logger.service.d.ts | 26 +- .../utils/bind-resolve-values.util.d.ts | 6 +- .../utils/decorators/bind.decorator.d.ts | 4 +- ...create-route-param-metadata.decorator.d.ts | 4 +- .../exception-filters.decorator.d.ts | 4 +- .../invalid-module-config.exception.d.ts | 2 +- .../utils/decorators/module.decorator.d.ts | 8 +- .../reflect-metadata.decorator.d.ts | 5 +- .../decorators/request-mapping.decorator.d.ts | 4 +- .../decorators/route-params.decorator.d.ts | 23 +- .../decorators/use-guards.decorator.d.ts | 4 +- .../use-interceptors.decorator.d.ts | 4 +- .../utils/decorators/use-pipes.decorator.d.ts | 4 +- lib/common/utils/forward-ref.util.d.ts | 6 +- .../utils/http-exception-body.util.d.ts | 22 +- lib/common/utils/merge-with-values.util.d.ts | 8 +- lib/core/adapters/express-adapter.d.ts | 4 +- lib/core/application-config.d.ts | 46 +- lib/core/constants.d.ts | 8 +- lib/core/errors/exception-handler.d.ts | 4 +- lib/core/errors/exceptions-zone.d.ts | 6 +- .../invalid-exception-filter.exception.d.ts | 2 +- ...id-middleware-configuration.exception.d.ts | 2 +- .../invalid-middleware.exception.d.ts | 2 +- .../exceptions/invalid-module.exception.d.ts | 2 +- ...oservices-package-not-found.exception.d.ts | 2 +- .../errors/exceptions/runtime.exception.d.ts | 14 +- .../undefined-dependency.exception.d.ts | 2 +- .../unknown-dependencies.exception.d.ts | 2 +- .../exceptions/unknown-export.exception.d.ts | 2 +- .../exceptions/unknown-module.exception.d.ts | 2 +- .../unknown-request-mapping.exception.d.ts | 2 +- lib/core/errors/messages.d.ts | 6 +- .../base-exception-filter-context.d.ts | 4 +- lib/core/exceptions/exceptions-handler.d.ts | 10 +- lib/core/exceptions/http-exception.d.ts | 42 +- lib/core/guards/constants.d.ts | 2 +- lib/core/guards/guards-consumer.d.ts | 16 +- lib/core/guards/guards-context-creator.d.ts | 28 +- lib/core/helpers/context-creator.d.ts | 18 +- .../helpers/external-context-creator.d.ts | 28 +- lib/core/helpers/messages.d.ts | 5 +- lib/core/helpers/router-method-factory.d.ts | 2 +- lib/core/injector/container.d.ts | 96 +- lib/core/injector/injector.d.ts | 179 ++- lib/core/injector/instance-loader.d.ts | 26 +- lib/core/injector/module-ref.d.ts | 4 +- lib/core/injector/module-token-factory.d.ts | 16 +- lib/core/injector/module.d.ts | 118 +- lib/core/injector/modules-container.d.ts | 3 +- .../interceptors/interceptors-consumer.d.ts | 15 +- .../interceptors-context-creator.d.ts | 28 +- lib/core/metadata-scanner.d.ts | 6 +- lib/core/middlewares/builder.d.ts | 26 +- lib/core/middlewares/container.d.ts | 18 +- lib/core/middlewares/middlewares-module.d.ts | 55 +- lib/core/middlewares/resolver.d.ts | 10 +- lib/core/middlewares/routes-mapper.d.ts | 18 +- lib/core/nest-application-context.d.ts | 20 +- lib/core/nest-application.d.ts | 95 +- lib/core/nest-factory.d.ts | 71 +- lib/core/pipes/params-token-factory.d.ts | 2 +- lib/core/pipes/pipes-consumer.d.ts | 38 +- lib/core/pipes/pipes-context-creator.d.ts | 10 +- .../exceptions-filter.interface.d.ts | 2 +- .../router/interfaces/explorer.inteface.d.ts | 8 +- .../router/interfaces/resolver.interface.d.ts | 2 +- .../route-params-factory.interface.d.ts | 18 +- lib/core/router/route-params-factory.d.ts | 18 +- lib/core/router/router-exception-filters.d.ts | 11 +- lib/core/router/router-execution-context.d.ts | 93 +- lib/core/router/router-explorer.d.ts | 68 +- lib/core/router/router-proxy.d.ts | 10 +- .../router/router-response-controller.d.ts | 11 +- lib/core/router/routes-resolver.d.ts | 32 +- lib/core/scanner.d.ts | 62 +- lib/core/services/reflector.service.d.ts | 2 +- .../client/client-proxy-factory.d.ts | 2 +- lib/microservices/client/client-proxy.d.ts | 13 +- lib/microservices/client/client-redis.d.ts | 27 +- lib/microservices/client/client-tcp.d.ts | 27 +- lib/microservices/constants.d.ts | 8 +- lib/microservices/container.d.ts | 8 +- .../context/exception-filters-context.d.ts | 11 +- .../context/rpc-context-creator.d.ts | 40 +- lib/microservices/context/rpc-proxy.d.ts | 5 +- lib/microservices/enums/transport.enum.d.ts | 4 +- .../exceptions/invalid-message.exception.d.ts | 2 +- .../exceptions/rpc-exception.d.ts | 6 +- .../exceptions/rpc-exceptions-handler.d.ts | 10 +- .../interfaces/client-metadata.interface.d.ts | 8 +- .../interfaces/closeable.interface.d.ts | 2 +- .../custom-transport-strategy.interface.d.ts | 4 +- .../message-handlers.interface.d.ts | 2 +- .../microservice-configuration.interface.d.ts | 10 +- .../microservice-response.interface.d.ts | 6 +- .../pattern-metadata.interface.d.ts | 2 +- .../listener-metadata-explorer.d.ts | 22 +- lib/microservices/listeners-controller.d.ts | 19 +- lib/microservices/microservices-module.d.ts | 23 +- lib/microservices/nest-microservice.d.ts | 69 +- lib/microservices/server/server-factory.d.ts | 9 +- lib/microservices/server/server-redis.d.ts | 35 +- lib/microservices/server/server-tcp.d.ts | 30 +- lib/microservices/server/server.d.ts | 19 +- lib/microservices/utils/client.decorator.d.ts | 4 +- .../utils/pattern.decorator.d.ts | 4 +- .../errors/unknown-module.exception.d.ts | 2 +- ...override-by-factory-options.interface.d.ts | 4 +- .../interfaces/override-by.interface.d.ts | 6 +- lib/testing/test.d.ts | 6 +- lib/testing/testing-module.builder.d.ts | 26 +- lib/testing/testing-module.d.ts | 10 +- lib/websockets/adapters/io-adapter.d.ts | 22 +- lib/websockets/constants.d.ts | 18 +- lib/websockets/container.d.ts | 14 +- .../context/exception-filters-context.d.ts | 7 +- .../context/ws-context-creator.d.ts | 40 +- lib/websockets/context/ws-proxy.d.ts | 5 +- .../invalid-socket-port.exception.d.ts | 2 +- lib/websockets/exceptions/ws-exception.d.ts | 6 +- .../exceptions/ws-exceptions-handler.d.ts | 8 +- lib/websockets/gateway-metadata-explorer.d.ts | 17 +- .../gateway-metadata.interface.d.ts | 6 +- .../gateway-middleware.interface.d.ts | 2 +- .../interfaces/nest-gateway.interface.d.ts | 6 +- .../observable-socket-server.interface.d.ts | 8 +- .../on-gateway-connection.interface.d.ts | 2 +- .../on-gateway-disconnect.interface.d.ts | 2 +- .../interfaces/on-gateway-init.interface.d.ts | 2 +- .../web-socket-server.interface.d.ts | 4 +- .../interfaces/ws-response.interface.d.ts | 4 +- lib/websockets/middlewares-injector.d.ts | 28 +- lib/websockets/observable-socket.d.ts | 2 +- lib/websockets/socket-module.d.ts | 20 +- lib/websockets/socket-server-provider.d.ts | 19 +- .../utils/socket-gateway.decorator.d.ts | 4 +- .../utils/subscribe-message.decorator.d.ts | 10 +- lib/websockets/web-sockets-controller.d.ts | 74 +- package.json | 4 + src/common/constants.ts | 10 +- src/common/decorators/core/catch.decorator.ts | 6 +- .../decorators/core/component.decorator.ts | 18 +- .../decorators/core/controller.decorator.ts | 10 +- .../core/exception-filters.decorator.ts | 23 +- src/common/decorators/core/index.ts | 2 +- .../decorators/core/inject.decorator.ts | 14 +- .../core/reflect-metadata.decorator.ts | 18 +- .../decorators/core/use-guards.decorator.ts | 16 +- .../core/use-interceptors.decorator.ts | 20 +- .../decorators/core/use-pipes.decorator.ts | 16 +- .../create-route-param-metadata.decorator.ts | 66 +- .../decorators/http/http-code.decorator.ts | 8 +- src/common/decorators/http/index.ts | 2 +- .../http/request-mapping.decorator.ts | 35 +- .../decorators/http/route-params.decorator.ts | 28 +- src/common/decorators/index.ts | 2 +- .../modules/exceptions/constants.ts | 2 +- .../invalid-module-config.exception.ts | 8 +- .../decorators/modules/global.decorator.ts | 8 +- src/common/decorators/modules/index.ts | 2 +- .../decorators/modules/module.decorator.ts | 50 +- .../decorators/modules/shared.decorator.ts | 28 +- .../modules/single-scope.decorator.ts | 20 +- src/common/enums/http-status.enum.ts | 88 +- src/common/enums/index.ts | 2 +- src/common/enums/nest-environment.enum.ts | 6 +- src/common/enums/request-method.enum.ts | 18 +- src/common/enums/route-paramtypes.enum.ts | 18 +- src/common/enums/transport.enum.ts | 4 +- .../exceptions/bad-gateway.exception.ts | 12 +- .../exceptions/bad-request.exception.ts | 10 +- src/common/exceptions/conflict.exception.ts | 12 +- src/common/exceptions/forbidden.exception.ts | 10 +- .../exceptions/gateway-timeout.exception.ts | 10 +- src/common/exceptions/gone.exception.ts | 10 +- src/common/exceptions/http.exception.ts | 8 +- src/common/exceptions/index.ts | 2 +- .../internal-server-error.exception.ts | 15 +- .../method-not-allowed.exception.ts | 10 +- .../exceptions/not-acceptable.exception.ts | 10 +- src/common/exceptions/not-found.exception.ts | 10 +- .../exceptions/not-implemented.exception.ts | 10 +- .../exceptions/payload-too-large.exception.ts | 10 +- .../exceptions/request-timeout.exception.ts | 10 +- .../service-unavailable.exception.ts | 10 +- .../exceptions/unauthorized.exception.ts | 10 +- .../unprocessable-entity.exception.ts | 10 +- .../unsupported-media-type.exception.ts | 19 +- src/common/index.ts | 46 +- .../interfaces/can-activate.interface.ts | 7 +- .../configuration-provider.interface.ts | 6 +- .../controller-metadata.interface.ts | 2 +- src/common/interfaces/controllers/index.ts | 2 +- .../exception-filter-metadata.interface.ts | 4 +- .../exceptions/exception-filter.interface.ts | 4 +- src/common/interfaces/exceptions/index.ts | 2 +- ...rpc-exception-filter-metadata.interface.ts | 4 +- .../rpc-exception-filter.interface.ts | 4 +- .../ws-exception-filter.interface.ts | 4 +- .../interfaces/execution-context.interface.ts | 2 +- src/common/interfaces/index.ts | 2 +- src/common/interfaces/metatype.interface.ts | 4 +- .../microservice-configuration.interface.ts | 2 +- .../express-middleware.interface.ts | 4 +- .../middleware-config-proxy.interface.ts | 44 +- .../middleware-configuration.interface.ts | 6 +- .../middlewares-consumer.interface.ts | 18 +- .../middlewares/nest-middleware.interface.ts | 7 +- .../modules/dynamic-module.interface.ts | 2 +- src/common/interfaces/modules/index.ts | 2 +- .../modules/module-metadata.interface.ts | 8 +- .../modules/module-metatype.interface.ts | 2 +- .../modules/nest-module.interface.ts | 4 +- .../modules/on-destroy.interface.ts | 4 +- .../interfaces/modules/on-init.interface.ts | 4 +- .../nest-application-context.interface.ts | 22 +- .../interfaces/nest-application.interface.ts | 264 ++--- .../interfaces/nest-interceptor.interface.ts | 8 +- .../interfaces/nest-microservice.interface.ts | 94 +- src/common/interfaces/paramtype.interface.ts | 2 +- .../interfaces/pipe-transform.interface.ts | 10 +- .../request-mapping-metadata.interface.ts | 4 +- .../web-socket-adapter.interface.ts | 2 +- src/common/pipes/index.ts | 2 +- src/common/pipes/parse-int.pipe.ts | 2 +- src/common/pipes/validation.pipe.ts | 32 +- src/common/services/logger.service.ts | 101 +- .../test/decorators/bind.decorator.spec.ts | 31 +- .../test/decorators/catch.decorator.spec.ts | 16 +- .../decorators/component.decorator.spec.ts | 100 +- .../decorators/controller.decorator.spec.ts | 26 +- .../decorators/dependencies.decorator.spec.ts | 29 +- .../exception-filters.decorator.spec.ts | 35 +- .../test/decorators/global.decorator.spec.ts | 14 +- .../decorators/http-code.decorator.spec.ts | 21 +- .../test/decorators/inject.decorator.spec.ts | 36 +- .../test/decorators/module.decorator.spec.ts | 55 +- .../reflect-metadata.decorator.spec.ts | 33 +- .../request-mapping.decorator.spec.ts | 77 +- .../decorators/route-params.decorator.spec.ts | 332 +++--- .../test/decorators/shared.decorator.spec.ts | 28 +- .../decorators/use-guards.decorator.spec.ts | 32 +- .../use-interceptors.decorator.spec.ts | 35 +- .../decorators/use-pipes.decorator.spec.ts | 32 +- src/common/test/pipes/parse-int.pipe.spec.ts | 40 +- src/common/test/pipes/validation.pipe.spec.ts | 58 +- .../utils/bind-resolve-values.util.spec.ts | 38 +- .../test/utils/merge-with-values.util.spec.ts | 26 +- src/common/test/utils/shared.utils.spec.ts | 145 +-- src/common/utils/bind-resolve-values.util.ts | 28 +- src/common/utils/forward-ref.util.ts | 2 +- src/common/utils/http-exception-body.util.ts | 12 +- src/common/utils/index.ts | 2 +- src/common/utils/merge-with-values.util.ts | 26 +- src/common/utils/shared.utils.ts | 8 +- src/core/adapters/express-adapter.ts | 14 +- src/core/application-config.ts | 120 +- src/core/constants.ts | 10 +- src/core/errors/exception-handler.ts | 16 +- src/core/errors/exceptions-zone.ts | 34 +- .../invalid-exception-filter.exception.ts | 8 +- ...alid-middleware-configuration.exception.ts | 8 +- .../invalid-middleware.exception.ts | 8 +- .../exceptions/invalid-module.exception.ts | 4 +- ...croservices-package-not-found.exception.ts | 8 +- .../errors/exceptions/runtime.exception.ts | 22 +- .../undefined-dependency.exception.ts | 8 +- .../unknown-dependencies.exception.ts | 8 +- .../exceptions/unknown-export.exception.ts | 8 +- .../exceptions/unknown-module.exception.ts | 8 +- .../unknown-request-mapping.exception.ts | 8 +- src/core/errors/messages.ts | 14 +- .../base-exception-filter-context.ts | 47 +- src/core/exceptions/exceptions-handler.ts | 84 +- src/core/exceptions/http-exception.ts | 12 +- src/core/guards/constants.ts | 2 +- src/core/guards/guards-consumer.ts | 73 +- src/core/guards/guards-context-creator.ts | 103 +- src/core/helpers/context-creator.ts | 54 +- src/core/helpers/external-context-creator.ts | 118 +- src/core/helpers/messages.ts | 9 +- src/core/helpers/router-method-factory.ts | 35 +- src/core/index.ts | 2 +- src/core/injector/container.ts | 321 ++--- src/core/injector/index.ts | 2 +- src/core/injector/injector.ts | 238 ++-- src/core/injector/instance-loader.ts | 118 +- src/core/injector/module-ref.ts | 4 +- src/core/injector/module-token-factory.ts | 74 +- src/core/injector/module.ts | 446 +++---- .../interceptors/interceptors-consumer.ts | 69 +- .../interceptors-context-creator.ts | 107 +- src/core/metadata-scanner.ts | 38 +- src/core/middlewares/builder.ts | 130 +- src/core/middlewares/container.ts | 83 +- src/core/middlewares/middlewares-module.ts | 268 +++-- src/core/middlewares/resolver.ts | 42 +- src/core/middlewares/routes-mapper.ts | 60 +- src/core/middlewares/utils.ts | 36 +- src/core/nest-application-context.ts | 69 +- src/core/nest-application.ts | 479 ++++---- src/core/nest-factory.ts | 188 +-- src/core/pipes/params-token-factory.ts | 20 +- src/core/pipes/pipes-consumer.ts | 44 +- src/core/pipes/pipes-context-creator.ts | 56 +- .../interfaces/exceptions-filter.interface.ts | 4 +- .../router/interfaces/explorer.inteface.ts | 6 +- .../router/interfaces/resolver.interface.ts | 2 +- .../route-params-factory.interface.ts | 4 +- src/core/router/route-params-factory.ts | 39 +- src/core/router/router-exception-filters.ts | 48 +- src/core/router/router-execution-context.ts | 319 +++-- src/core/router/router-explorer.ts | 238 ++-- src/core/router/router-proxy.ts | 60 +- src/core/router/router-response-controller.ts | 22 +- src/core/router/routes-resolver.ts | 117 +- src/core/scanner.ts | 345 +++--- src/core/services/reflector.service.ts | 2 +- src/core/test/application-config.spec.ts | 10 +- .../errors/test/exception-handler.spec.ts | 47 +- .../test/errors/test/exceptions-zone.spec.ts | 107 +- .../exceptions/exceptions-handler.spec.ts | 209 ++-- src/core/test/guards/guards-consumer.spec.ts | 92 +- .../guards/guards-context-creator.spec.ts | 101 +- .../helpers/external-context-creator.spec.ts | 232 ++-- .../helpers/router-method-factory.spec.ts | 50 +- src/core/test/injector/container.spec.ts | 352 +++--- src/core/test/injector/injector.spec.ts | 1049 ++++++++++------- .../test/injector/instance-loader.spec.ts | 268 +++-- .../injector/module-token-factory.spec.ts | 142 +-- src/core/test/injector/module.spec.ts | 471 ++++---- .../interceptors-consumer.spec.ts | 147 ++- .../interceptors-context-creator.spec.ts | 108 +- src/core/test/metadata-scanner.spec.ts | 40 +- src/core/test/middlewares/builder.spec.ts | 143 ++- src/core/test/middlewares/container.spec.ts | 99 +- .../middlewares/middlewares-module.spec.ts | 236 ++-- src/core/test/middlewares/resolver.spec.ts | 82 +- .../test/middlewares/routes-mapper.spec.ts | 92 +- src/core/test/middlewares/utils.spec.ts | 111 +- .../test/pipes/params-token-factory.spec.ts | 60 +- src/core/test/pipes/pipes-consumer.spec.ts | 60 +- .../test/pipes/pipes-context-creator.spec.ts | 40 +- .../test/router/route-params-factory.spec.ts | 170 +-- .../router/router-exception-filters.spec.ts | 113 +- .../router/router-execution-context.spec.ts | 474 ++++---- src/core/test/router/router-explorer.spec.ts | 92 +- src/core/test/router/router-proxy.spec.ts | 124 +- .../router/router-response-controller.spec.ts | 148 ++- src/core/test/router/routes-resolver.spec.ts | 31 +- src/core/test/scanner.spec.ts | 255 ++-- .../test/services/reflector.service.spec.ts | 2 +- src/index.ts | 2 +- .../client/client-proxy-factory.ts | 16 +- src/microservices/client/client-proxy.ts | 52 +- src/microservices/client/client-redis.ts | 114 +- src/microservices/client/client-tcp.ts | 124 +- src/microservices/client/index.ts | 2 +- src/microservices/constants.ts | 2 +- src/microservices/container.ts | 22 +- .../context/exception-filters-context.ts | 48 +- .../context/rpc-context-creator.ts | 102 +- src/microservices/context/rpc-proxy.ts | 25 +- src/microservices/enums/index.ts | 2 +- src/microservices/enums/transport.enum.ts | 6 +- src/microservices/exceptions/index.ts | 2 +- .../exceptions/invalid-message.exception.ts | 8 +- src/microservices/exceptions/rpc-exception.ts | 8 +- .../exceptions/rpc-exceptions-handler.ts | 2 +- src/microservices/index.ts | 2 +- .../interfaces/client-metadata.interface.ts | 10 +- .../interfaces/closeable.interface.ts | 4 +- .../custom-transport-strategy.interface.ts | 6 +- src/microservices/interfaces/index.ts | 2 +- .../interfaces/message-handlers.interface.ts | 4 +- .../microservice-configuration.interface.ts | 12 +- .../microservice-response.interface.ts | 8 +- .../interfaces/pattern-metadata.interface.ts | 4 +- .../listener-metadata-explorer.ts | 93 +- src/microservices/listeners-controller.ts | 48 +- src/microservices/microservices-module.ts | 109 +- src/microservices/nest-microservice.ts | 284 ++--- src/microservices/server/index.ts | 2 +- src/microservices/server/server-factory.ts | 23 +- src/microservices/server/server-redis.ts | 167 +-- src/microservices/server/server-tcp.ts | 87 +- src/microservices/server/server.ts | 61 +- .../test/client/client-proxy-factory.spec.ts | 20 +- .../test/client/client-proxy.spec.ts | 100 +- .../test/client/client-redis.spec.ts | 295 ++--- .../test/client/client-tcp.spec.ts | 195 +-- src/microservices/test/container.spec.ts | 48 +- .../context/exception-filters-context.spec.ts | 68 +- .../test/context/rpc-context-creator.spec.ts | 215 ++-- .../test/context/rpc-proxy.spec.ts | 49 +- .../test/exceptions/rpc-exception.spec.ts | 18 +- .../exceptions/rpc-exceptions-handler.spec.ts | 196 +-- .../test/listeners-controller.spec.ts | 59 +- .../test/listeners-metadata-explorer.spec.ts | 126 +- .../test/server/server-factory.spec.ts | 19 +- .../test/server/server-redis.spec.ts | 288 ++--- .../test/server/server-tcp.spec.ts | 121 +- src/microservices/test/server/server.spec.ts | 134 ++- .../test/utils/client.decorator.spec.ts | 37 +- .../test/utils/pattern.decorator.spec.ts | 20 +- src/microservices/utils/client.decorator.ts | 17 +- src/microservices/utils/index.ts | 2 +- src/microservices/utils/pattern.decorator.ts | 16 +- src/testing/index.ts | 2 +- src/testing/interfaces/index.ts | 2 +- .../override-by-factory-options.interface.ts | 6 +- .../interfaces/override-by.interface.ts | 8 +- src/testing/test.ts | 22 +- src/testing/testing-module.builder.ts | 111 +- src/testing/testing-module.ts | 33 +- src/websockets/adapters/io-adapter.ts | 79 +- src/websockets/constants.ts | 2 +- src/websockets/container.ts | 41 +- .../context/exception-filters-context.ts | 42 +- src/websockets/context/ws-context-creator.ts | 102 +- src/websockets/context/ws-proxy.ts | 25 +- .../invalid-socket-port.exception.ts | 8 +- src/websockets/exceptions/ws-exception.ts | 8 +- .../exceptions/ws-exceptions-handler.ts | 62 +- src/websockets/gateway-metadata-explorer.ts | 84 +- src/websockets/index.ts | 2 +- .../interfaces/gateway-metadata.interface.ts | 8 +- .../gateway-middleware.interface.ts | 4 +- src/websockets/interfaces/index.ts | 2 +- .../interfaces/nest-gateway.interface.ts | 6 +- .../observable-socket-server.interface.ts | 9 +- .../on-gateway-connection.interface.ts | 2 +- .../on-gateway-disconnect.interface.ts | 2 +- .../interfaces/on-gateway-init.interface.ts | 2 +- .../interfaces/web-socket-server.interface.ts | 4 +- .../interfaces/ws-response.interface.ts | 2 +- src/websockets/middlewares-injector.ts | 98 +- src/websockets/observable-socket.ts | 18 +- src/websockets/socket-module.ts | 107 +- src/websockets/socket-server-provider.ts | 87 +- src/websockets/test/container.spec.ts | 51 +- .../context/exception-filters.context.spec.ts | 66 +- .../test/context/ws-context-creator.spec.ts | 213 ++-- src/websockets/test/context/ws-proxy.spec.ts | 49 +- .../test/exceptions/ws-exception.spec.ts | 18 +- .../exceptions/ws-exceptions-handler.spec.ts | 189 +-- .../test/gateway-metadata-explorer.spec.ts | 108 +- .../test/middlewares-injector.spec.ts | 209 ++-- src/websockets/test/observable-socket.spec.ts | 22 +- .../test/socket-server-provider.spec.ts | 62 +- .../utils/gateway-server.decorator.spec.ts | 29 +- .../utils/socket-gateway.decorator.spec.ts | 24 +- .../utils/subscribe-message.decorator.spec.ts | 27 +- .../test/web-sockets-controller.spec.ts | 556 ++++----- .../utils/gateway-server.decorator.ts | 10 +- src/websockets/utils/index.ts | 2 +- .../utils/socket-gateway.decorator.ts | 33 +- .../utils/subscribe-message.decorator.ts | 20 +- src/websockets/web-sockets-controller.ts | 258 ++-- 645 files changed, 13202 insertions(+), 10929 deletions(-) create mode 100644 .prettierrc diff --git a/.prettierrc b/.prettierrc new file mode 100644 index 00000000000..92cde390acf --- /dev/null +++ b/.prettierrc @@ -0,0 +1,3 @@ +{ + "singleQuote": true +} \ No newline at end of file diff --git a/examples/01-cats-app/e2e/cats/cats.e2e-spec.ts b/examples/01-cats-app/e2e/cats/cats.e2e-spec.ts index 9af3ed03742..aaf8a40172e 100644 --- a/examples/01-cats-app/e2e/cats/cats.e2e-spec.ts +++ b/examples/01-cats-app/e2e/cats/cats.e2e-spec.ts @@ -13,7 +13,7 @@ describe('Cats', () => { beforeAll(async () => { const module = await Test.createTestingModule({ - modules: [CatsModule], + modules: [CatsModule] }) .overrideComponent(CatsService) .useValue(catsService) @@ -29,7 +29,7 @@ describe('Cats', () => { .get('/cats') .expect(200) .expect({ - data: catsService.findAll(), + data: catsService.findAll() }); }); diff --git a/examples/01-cats-app/src/modules/app.module.ts b/examples/01-cats-app/src/modules/app.module.ts index 53d1912fb57..d156c828e14 100644 --- a/examples/01-cats-app/src/modules/app.module.ts +++ b/examples/01-cats-app/src/modules/app.module.ts @@ -4,12 +4,13 @@ import { CatsModule } from './cats/cats.module'; import { CatsController } from './cats/cats.controller'; @Module({ - modules: [CatsModule], + modules: [CatsModule] }) export class ApplicationModule implements NestModule { - configure(consumer: MiddlewaresConsumer): void { - consumer.apply(LoggerMiddleware) - .with('ApplicationModule') - .forRoutes(CatsController); - } -} \ No newline at end of file + configure(consumer: MiddlewaresConsumer): void { + consumer + .apply(LoggerMiddleware) + .with('ApplicationModule') + .forRoutes(CatsController); + } +} diff --git a/examples/01-cats-app/src/modules/cats/cats.controller.spec.ts b/examples/01-cats-app/src/modules/cats/cats.controller.spec.ts index 43bf835df72..541e78dff6a 100644 --- a/examples/01-cats-app/src/modules/cats/cats.controller.spec.ts +++ b/examples/01-cats-app/src/modules/cats/cats.controller.spec.ts @@ -8,9 +8,9 @@ describe('CatsController', () => { beforeEach(async () => { const module = await Test.createTestingModule({ - controllers: [CatsController], - components: [CatsService], - }).compile(); + controllers: [CatsController], + components: [CatsService] + }).compile(); catsService = module.get(CatsService); catsController = module.get(CatsController); @@ -24,4 +24,4 @@ describe('CatsController', () => { expect(await catsController.findAll()).toBe(result); }); }); -}); \ No newline at end of file +}); diff --git a/examples/01-cats-app/src/modules/cats/cats.controller.ts b/examples/01-cats-app/src/modules/cats/cats.controller.ts index 78d59786034..2eefc2948a7 100644 --- a/examples/01-cats-app/src/modules/cats/cats.controller.ts +++ b/examples/01-cats-app/src/modules/cats/cats.controller.ts @@ -1,4 +1,13 @@ -import { Controller, Get, Post, Body, UseGuards, ReflectMetadata, UseInterceptors, Param } from '@nestjs/common'; +import { + Controller, + Get, + Post, + Body, + UseGuards, + ReflectMetadata, + UseInterceptors, + Param +} from '@nestjs/common'; import { CreateCatDto } from './dto/create-cat.dto'; import { CatsService } from './cats.service'; import { Cat } from './interfaces/cat.interface'; @@ -26,7 +35,10 @@ export class CatsController { } @Get(':id') - findOne(@Param('id', new ParseIntPipe()) id) { + findOne( + @Param('id', new ParseIntPipe()) + id + ) { // logic } -} \ No newline at end of file +} diff --git a/examples/01-cats-app/src/modules/cats/cats.module.ts b/examples/01-cats-app/src/modules/cats/cats.module.ts index cece71d4664..1177abc4edb 100644 --- a/examples/01-cats-app/src/modules/cats/cats.module.ts +++ b/examples/01-cats-app/src/modules/cats/cats.module.ts @@ -3,7 +3,7 @@ import { CatsController } from './cats.controller'; import { CatsService } from './cats.service'; @Module({ - controllers: [CatsController], - components: [CatsService], + controllers: [CatsController], + components: [CatsService] }) -export class CatsModule {} \ No newline at end of file +export class CatsModule {} diff --git a/examples/01-cats-app/src/modules/cats/cats.service.ts b/examples/01-cats-app/src/modules/cats/cats.service.ts index 72f8fe21852..6aa983ad642 100644 --- a/examples/01-cats-app/src/modules/cats/cats.service.ts +++ b/examples/01-cats-app/src/modules/cats/cats.service.ts @@ -13,4 +13,4 @@ export class CatsService { findAll(): Cat[] { return this.cats; } -} \ No newline at end of file +} diff --git a/examples/01-cats-app/src/modules/cats/dto/create-cat.dto.ts b/examples/01-cats-app/src/modules/cats/dto/create-cat.dto.ts index 4abf2251ab2..02dc8f88c11 100644 --- a/examples/01-cats-app/src/modules/cats/dto/create-cat.dto.ts +++ b/examples/01-cats-app/src/modules/cats/dto/create-cat.dto.ts @@ -1,12 +1,9 @@ import { IsString, IsInt } from 'class-validator'; export class CreateCatDto { - @IsString() - readonly name: string; + @IsString() readonly name: string; - @IsInt() - readonly age: number; + @IsInt() readonly age: number; - @IsString() - readonly breed: string; -} \ No newline at end of file + @IsString() readonly breed: string; +} diff --git a/examples/01-cats-app/src/modules/cats/interfaces/cat.interface.ts b/examples/01-cats-app/src/modules/cats/interfaces/cat.interface.ts index 043779cd362..b3e66c4b676 100644 --- a/examples/01-cats-app/src/modules/cats/interfaces/cat.interface.ts +++ b/examples/01-cats-app/src/modules/cats/interfaces/cat.interface.ts @@ -2,4 +2,4 @@ export interface Cat { readonly name: string; readonly age: number; readonly breed: string; -} \ No newline at end of file +} diff --git a/examples/01-cats-app/src/modules/common/decorators/roles.decorator.ts b/examples/01-cats-app/src/modules/common/decorators/roles.decorator.ts index 91407a6e6a6..f58d46e6b3e 100644 --- a/examples/01-cats-app/src/modules/common/decorators/roles.decorator.ts +++ b/examples/01-cats-app/src/modules/common/decorators/roles.decorator.ts @@ -1,3 +1,3 @@ import { ReflectMetadata } from '@nestjs/common'; -export const Roles = (...roles: string[]) => ReflectMetadata('roles', roles); \ No newline at end of file +export const Roles = (...roles: string[]) => ReflectMetadata('roles', roles); diff --git a/examples/01-cats-app/src/modules/common/exceptions/forbidden.exception.ts b/examples/01-cats-app/src/modules/common/exceptions/forbidden.exception.ts index d615a19a63d..6f58d1a6706 100644 --- a/examples/01-cats-app/src/modules/common/exceptions/forbidden.exception.ts +++ b/examples/01-cats-app/src/modules/common/exceptions/forbidden.exception.ts @@ -5,4 +5,4 @@ export class ForbiddenException extends HttpException { constructor() { super('Forbidden', HttpStatus.FORBIDDEN); } -} \ No newline at end of file +} diff --git a/examples/01-cats-app/src/modules/common/filters/http-exception.filter.ts b/examples/01-cats-app/src/modules/common/filters/http-exception.filter.ts index 489ea32dd8b..be2a154618e 100644 --- a/examples/01-cats-app/src/modules/common/filters/http-exception.filter.ts +++ b/examples/01-cats-app/src/modules/common/filters/http-exception.filter.ts @@ -8,7 +8,7 @@ export class HttpExceptionFilter implements ExceptionFilter { response.status(status).json({ statusCode: status, - message: `It's a message from the exception filter`, + message: `It's a message from the exception filter` }); } -} \ No newline at end of file +} diff --git a/examples/01-cats-app/src/modules/common/guards/roles.guard.ts b/examples/01-cats-app/src/modules/common/guards/roles.guard.ts index bfc3d13f88e..d43454ab293 100644 --- a/examples/01-cats-app/src/modules/common/guards/roles.guard.ts +++ b/examples/01-cats-app/src/modules/common/guards/roles.guard.ts @@ -14,7 +14,8 @@ export class RolesGuard implements CanActivate { } const user = req.user; - const hasRole = () => !!user.roles.find((role) => !!roles.find((item) => item === role)); + const hasRole = () => + !!user.roles.find(role => !!roles.find(item => item === role)); return user && user.roles && hasRole(); } -} \ No newline at end of file +} diff --git a/examples/01-cats-app/src/modules/common/interceptors/cache.interceptor.ts b/examples/01-cats-app/src/modules/common/interceptors/cache.interceptor.ts index f0b1a2ea8f8..d083a3fde24 100644 --- a/examples/01-cats-app/src/modules/common/interceptors/cache.interceptor.ts +++ b/examples/01-cats-app/src/modules/common/interceptors/cache.interceptor.ts @@ -6,10 +6,14 @@ import 'rxjs/add/observable/of'; export abstract class CacheInterceptor implements NestInterceptor { protected abstract readonly isCached: () => boolean; - intercept(dataOrRequest, context: ExecutionContext, stream$: Observable): Observable { + intercept( + dataOrRequest, + context: ExecutionContext, + stream$: Observable + ): Observable { if (this.isCached()) { return Observable.of([]); } return stream$; } -} \ No newline at end of file +} diff --git a/examples/01-cats-app/src/modules/common/interceptors/exception.interceptor.ts b/examples/01-cats-app/src/modules/common/interceptors/exception.interceptor.ts index d9c462f5232..b37da0629d6 100644 --- a/examples/01-cats-app/src/modules/common/interceptors/exception.interceptor.ts +++ b/examples/01-cats-app/src/modules/common/interceptors/exception.interceptor.ts @@ -1,4 +1,9 @@ -import { Interceptor, NestInterceptor, ExecutionContext, HttpStatus } from '@nestjs/common'; +import { + Interceptor, + NestInterceptor, + ExecutionContext, + HttpStatus +} from '@nestjs/common'; import { HttpException } from '@nestjs/common'; import { Observable } from 'rxjs/Observable'; import 'rxjs/add/operator/catch'; @@ -6,9 +11,18 @@ import 'rxjs/add/observable/throw'; @Interceptor() export class ExceptionInterceptor implements NestInterceptor { - intercept(dataOrRequest, context: ExecutionContext, stream$: Observable): Observable { - return stream$.catch((err) => Observable.throw( - new HttpException('Exception interceptor message', HttpStatus.BAD_GATEWAY), - )); + intercept( + dataOrRequest, + context: ExecutionContext, + stream$: Observable + ): Observable { + return stream$.catch(err => + Observable.throw( + new HttpException( + 'Exception interceptor message', + HttpStatus.BAD_GATEWAY + ) + ) + ); } -} \ No newline at end of file +} diff --git a/examples/01-cats-app/src/modules/common/interceptors/logging.interceptor.ts b/examples/01-cats-app/src/modules/common/interceptors/logging.interceptor.ts index 8e26e797b1a..7176ce9363a 100644 --- a/examples/01-cats-app/src/modules/common/interceptors/logging.interceptor.ts +++ b/examples/01-cats-app/src/modules/common/interceptors/logging.interceptor.ts @@ -4,12 +4,14 @@ import 'rxjs/add/operator/do'; @Interceptor() export class LoggingInterceptor implements NestInterceptor { - intercept(dataOrRequest, context: ExecutionContext, stream$: Observable): Observable { + intercept( + dataOrRequest, + context: ExecutionContext, + stream$: Observable + ): Observable { console.log('Before...'); const now = Date.now(); - return stream$.do( - () => console.log(`After... ${Date.now() - now}ms`), - ); + return stream$.do(() => console.log(`After... ${Date.now() - now}ms`)); } -} \ No newline at end of file +} diff --git a/examples/01-cats-app/src/modules/common/interceptors/mixin-cache.interceptor.ts b/examples/01-cats-app/src/modules/common/interceptors/mixin-cache.interceptor.ts index 8ccb5ab4eee..2a1fe56a23a 100644 --- a/examples/01-cats-app/src/modules/common/interceptors/mixin-cache.interceptor.ts +++ b/examples/01-cats-app/src/modules/common/interceptors/mixin-cache.interceptor.ts @@ -2,7 +2,9 @@ import { mixin } from '@nestjs/common'; import { CacheInterceptor } from './cache.interceptor'; export function mixinCacheInterceptor(isCached: () => boolean) { - return mixin(class extends CacheInterceptor { - protected readonly isCached = isCached; - }); -} \ No newline at end of file + return mixin( + class extends CacheInterceptor { + protected readonly isCached = isCached; + } + ); +} diff --git a/examples/01-cats-app/src/modules/common/interceptors/transform.interceptor.ts b/examples/01-cats-app/src/modules/common/interceptors/transform.interceptor.ts index 792cc5464ed..35ec5c03a42 100644 --- a/examples/01-cats-app/src/modules/common/interceptors/transform.interceptor.ts +++ b/examples/01-cats-app/src/modules/common/interceptors/transform.interceptor.ts @@ -4,7 +4,11 @@ import 'rxjs/add/operator/map'; @Interceptor() export class TransformInterceptor implements NestInterceptor { - intercept(dataOrRequest, context: ExecutionContext, stream$: Observable): Observable { - return stream$.map((data) => ({ data })); + intercept( + dataOrRequest, + context: ExecutionContext, + stream$: Observable + ): Observable { + return stream$.map(data => ({ data })); } -} \ No newline at end of file +} diff --git a/examples/01-cats-app/src/modules/common/middlewares/logger.middleware.ts b/examples/01-cats-app/src/modules/common/middlewares/logger.middleware.ts index c11b358b808..479f9790237 100644 --- a/examples/01-cats-app/src/modules/common/middlewares/logger.middleware.ts +++ b/examples/01-cats-app/src/modules/common/middlewares/logger.middleware.ts @@ -7,5 +7,5 @@ export class LoggerMiddleware implements NestMiddleware { console.log(`[${name}] Request...`); // [ApplicationModule] Request... next(); }; - } -} \ No newline at end of file + } +} diff --git a/examples/01-cats-app/src/modules/common/pipes/parse-int.pipe.ts b/examples/01-cats-app/src/modules/common/pipes/parse-int.pipe.ts index 8406be8954e..5043c85572c 100644 --- a/examples/01-cats-app/src/modules/common/pipes/parse-int.pipe.ts +++ b/examples/01-cats-app/src/modules/common/pipes/parse-int.pipe.ts @@ -1,5 +1,10 @@ import { HttpException } from '@nestjs/common'; -import { PipeTransform, Pipe, ArgumentMetadata, HttpStatus } from '@nestjs/common'; +import { + PipeTransform, + Pipe, + ArgumentMetadata, + HttpStatus +} from '@nestjs/common'; @Pipe() export class ParseIntPipe implements PipeTransform { @@ -10,4 +15,4 @@ export class ParseIntPipe implements PipeTransform { } return val; } -} \ No newline at end of file +} diff --git a/examples/01-cats-app/src/modules/common/pipes/validation.pipe.ts b/examples/01-cats-app/src/modules/common/pipes/validation.pipe.ts index b0e140f4d53..2b1c6c67379 100644 --- a/examples/01-cats-app/src/modules/common/pipes/validation.pipe.ts +++ b/examples/01-cats-app/src/modules/common/pipes/validation.pipe.ts @@ -1,25 +1,30 @@ import { HttpException } from '@nestjs/common'; -import { PipeTransform, Pipe, ArgumentMetadata, HttpStatus } from '@nestjs/common'; +import { + PipeTransform, + Pipe, + ArgumentMetadata, + HttpStatus +} from '@nestjs/common'; import { validate } from 'class-validator'; import { plainToClass } from 'class-transformer'; @Pipe() export class ValidationPipe implements PipeTransform { - async transform(value, metadata: ArgumentMetadata) { - const { metatype } = metadata; - if (!metatype || !this.toValidate(metatype)) { - return value; - } - const object = plainToClass(metatype, value); - const errors = await validate(object); - if (errors.length > 0) { - throw new HttpException('Validation failed', HttpStatus.BAD_REQUEST); - } + async transform(value, metadata: ArgumentMetadata) { + const { metatype } = metadata; + if (!metatype || !this.toValidate(metatype)) { return value; } - - private toValidate(metatype): boolean { - const types = [String, Boolean, Number, Array, Object]; - return !types.find((type) => metatype === type); + const object = plainToClass(metatype, value); + const errors = await validate(object); + if (errors.length > 0) { + throw new HttpException('Validation failed', HttpStatus.BAD_REQUEST); } -} \ No newline at end of file + return value; + } + + private toValidate(metatype): boolean { + const types = [String, Boolean, Number, Array, Object]; + return !types.find(type => metatype === type); + } +} diff --git a/examples/02-gateways/src/modules/app.module.ts b/examples/02-gateways/src/modules/app.module.ts index 08b6b8d7435..05c1041f13d 100644 --- a/examples/02-gateways/src/modules/app.module.ts +++ b/examples/02-gateways/src/modules/app.module.ts @@ -2,6 +2,6 @@ import { Module } from '@nestjs/common'; import { EventsModule } from './events/events.module'; @Module({ - modules: [EventsModule], + modules: [EventsModule] }) -export class ApplicationModule {} \ No newline at end of file +export class ApplicationModule {} diff --git a/examples/02-gateways/src/modules/common/adapters/ws-adapter.ts b/examples/02-gateways/src/modules/common/adapters/ws-adapter.ts index 200cf6a09e5..7660edf25dd 100644 --- a/examples/02-gateways/src/modules/common/adapters/ws-adapter.ts +++ b/examples/02-gateways/src/modules/common/adapters/ws-adapter.ts @@ -19,25 +19,27 @@ export class WsAdapter implements WebSocketAdapter { public bindMessageHandlers( client: WebSocket, handlers: MessageMappingProperties[], - process: (data: any) => Observable, + process: (data: any) => Observable ) { Observable.fromEvent(client, 'message') - .switchMap((buffer) => this.bindMessageHandler(buffer, handlers, process)) - .filter((result) => !!result) - .subscribe((response) => client.send(JSON.stringify(response))); + .switchMap(buffer => this.bindMessageHandler(buffer, handlers, process)) + .filter(result => !!result) + .subscribe(response => client.send(JSON.stringify(response))); } public bindMessageHandler( buffer, handlers: MessageMappingProperties[], - process: (data: any) => Observable, + process: (data: any) => Observable ): Observable { const data = JSON.parse(buffer.data); - const messageHandler = handlers.find((handler) => handler.message === data.type); + const messageHandler = handlers.find( + handler => handler.message === data.type + ); if (!messageHandler) { return Observable.empty(); } const { callback } = messageHandler; return process(callback(data)); } -} \ No newline at end of file +} diff --git a/examples/02-gateways/src/modules/common/decorators/roles.decorator.ts b/examples/02-gateways/src/modules/common/decorators/roles.decorator.ts index 91407a6e6a6..f58d46e6b3e 100644 --- a/examples/02-gateways/src/modules/common/decorators/roles.decorator.ts +++ b/examples/02-gateways/src/modules/common/decorators/roles.decorator.ts @@ -1,3 +1,3 @@ import { ReflectMetadata } from '@nestjs/common'; -export const Roles = (...roles: string[]) => ReflectMetadata('roles', roles); \ No newline at end of file +export const Roles = (...roles: string[]) => ReflectMetadata('roles', roles); diff --git a/examples/02-gateways/src/modules/common/filters/ws-exception.filter.ts b/examples/02-gateways/src/modules/common/filters/ws-exception.filter.ts index e523c4e5f45..70baf48d8fa 100644 --- a/examples/02-gateways/src/modules/common/filters/ws-exception.filter.ts +++ b/examples/02-gateways/src/modules/common/filters/ws-exception.filter.ts @@ -6,7 +6,7 @@ export class ExceptionFilter implements WsExceptionFilter { catch(exception: WsException, client) { client.emit('exception', { status: 'error', - message: `It's a message from the exception filter`, + message: `It's a message from the exception filter` }); } -} \ No newline at end of file +} diff --git a/examples/02-gateways/src/modules/common/guards/roles.guard.ts b/examples/02-gateways/src/modules/common/guards/roles.guard.ts index b7511ff4239..a1c074a5923 100644 --- a/examples/02-gateways/src/modules/common/guards/roles.guard.ts +++ b/examples/02-gateways/src/modules/common/guards/roles.guard.ts @@ -14,7 +14,8 @@ export class RolesGuard implements CanActivate { } const user = data.user; - const hasRole = () => !!user.roles.find((role) => !!roles.find((item) => item === role)); + const hasRole = () => + !!user.roles.find(role => !!roles.find(item => item === role)); return user && user.roles && hasRole(); } -} \ No newline at end of file +} diff --git a/examples/02-gateways/src/modules/common/interceptors/cache.interceptor.ts b/examples/02-gateways/src/modules/common/interceptors/cache.interceptor.ts index 4baa6059acf..b645e2af6a5 100644 --- a/examples/02-gateways/src/modules/common/interceptors/cache.interceptor.ts +++ b/examples/02-gateways/src/modules/common/interceptors/cache.interceptor.ts @@ -4,11 +4,15 @@ import 'rxjs/add/observable/of'; @Interceptor() export class CacheInterceptor implements NestInterceptor { - intercept(dataOrRequest, context: ExecutionContext, stream$: Observable): Observable { + intercept( + dataOrRequest, + context: ExecutionContext, + stream$: Observable + ): Observable { const isCached = true; if (isCached) { return Observable.of([]); } return stream$; } -} \ No newline at end of file +} diff --git a/examples/02-gateways/src/modules/common/interceptors/logging.interceptor.ts b/examples/02-gateways/src/modules/common/interceptors/logging.interceptor.ts index 8e26e797b1a..7176ce9363a 100644 --- a/examples/02-gateways/src/modules/common/interceptors/logging.interceptor.ts +++ b/examples/02-gateways/src/modules/common/interceptors/logging.interceptor.ts @@ -4,12 +4,14 @@ import 'rxjs/add/operator/do'; @Interceptor() export class LoggingInterceptor implements NestInterceptor { - intercept(dataOrRequest, context: ExecutionContext, stream$: Observable): Observable { + intercept( + dataOrRequest, + context: ExecutionContext, + stream$: Observable + ): Observable { console.log('Before...'); const now = Date.now(); - return stream$.do( - () => console.log(`After... ${Date.now() - now}ms`), - ); + return stream$.do(() => console.log(`After... ${Date.now() - now}ms`)); } -} \ No newline at end of file +} diff --git a/examples/02-gateways/src/modules/common/interceptors/transform.interceptor.ts b/examples/02-gateways/src/modules/common/interceptors/transform.interceptor.ts index 792cc5464ed..35ec5c03a42 100644 --- a/examples/02-gateways/src/modules/common/interceptors/transform.interceptor.ts +++ b/examples/02-gateways/src/modules/common/interceptors/transform.interceptor.ts @@ -4,7 +4,11 @@ import 'rxjs/add/operator/map'; @Interceptor() export class TransformInterceptor implements NestInterceptor { - intercept(dataOrRequest, context: ExecutionContext, stream$: Observable): Observable { - return stream$.map((data) => ({ data })); + intercept( + dataOrRequest, + context: ExecutionContext, + stream$: Observable + ): Observable { + return stream$.map(data => ({ data })); } -} \ No newline at end of file +} diff --git a/examples/02-gateways/src/modules/common/pipes/validation.pipe.ts b/examples/02-gateways/src/modules/common/pipes/validation.pipe.ts index 1181681748d..ccad2bd6e66 100644 --- a/examples/02-gateways/src/modules/common/pipes/validation.pipe.ts +++ b/examples/02-gateways/src/modules/common/pipes/validation.pipe.ts @@ -1,25 +1,30 @@ -import { PipeTransform, Pipe, ArgumentMetadata, HttpStatus } from '@nestjs/common'; +import { + PipeTransform, + Pipe, + ArgumentMetadata, + HttpStatus +} from '@nestjs/common'; import { validate } from 'class-validator'; import { plainToClass } from 'class-transformer'; import { WsException } from '@nestjs/websockets'; @Pipe() export class ValidationPipe implements PipeTransform { - async transform(value, metadata: ArgumentMetadata) { - const { metatype } = metadata; - if (!metatype || !this.toValidate(metatype)) { - return value; - } - const object = plainToClass(metatype, value); - const errors = await validate(object); - if (errors.length > 0) { - throw new WsException('Validation failed'); - } + async transform(value, metadata: ArgumentMetadata) { + const { metatype } = metadata; + if (!metatype || !this.toValidate(metatype)) { return value; } - - private toValidate(metatype): boolean { - const types = [String, Boolean, Number, Array, Object]; - return !types.find((type) => metatype === type); + const object = plainToClass(metatype, value); + const errors = await validate(object); + if (errors.length > 0) { + throw new WsException('Validation failed'); } -} \ No newline at end of file + return value; + } + + private toValidate(metatype): boolean { + const types = [String, Boolean, Number, Array, Object]; + return !types.find(type => metatype === type); + } +} diff --git a/examples/02-gateways/src/modules/events/events.gateway.ts b/examples/02-gateways/src/modules/events/events.gateway.ts index 262ba540a24..ea9a1b95ba1 100644 --- a/examples/02-gateways/src/modules/events/events.gateway.ts +++ b/examples/02-gateways/src/modules/events/events.gateway.ts @@ -1,13 +1,16 @@ -import { WebSocketGateway, SubscribeMessage, WsResponse, WebSocketServer, WsException } from '@nestjs/websockets'; +import { + WebSocketGateway, + SubscribeMessage, + WsResponse, + WebSocketServer, + WsException +} from '@nestjs/websockets'; import { Observable } from 'rxjs/Observable'; import 'rxjs/add/observable/from'; import 'rxjs/add/operator/map'; - @WebSocketGateway({ namespace: 'events' }) -export class EventsGatewayxD { - -} +export class EventsGatewayxD {} @WebSocketGateway({ namespace: 'xd' }) export class EventsGateway { @WebSocketServer() server; @@ -17,7 +20,6 @@ export class EventsGateway { const event = 'events'; const response = [1, 2, 3]; - return Observable.from(response) - .map((res) => ({ event, data: res })); + return Observable.from(response).map(res => ({ event, data: res })); } -} \ No newline at end of file +} diff --git a/examples/02-gateways/src/modules/events/events.module.ts b/examples/02-gateways/src/modules/events/events.module.ts index 96fb8942c7c..a7549569d45 100644 --- a/examples/02-gateways/src/modules/events/events.module.ts +++ b/examples/02-gateways/src/modules/events/events.module.ts @@ -1,7 +1,7 @@ import { Module } from '@nestjs/common'; -import { EventsGateway, EventsGatewayxD} from './events.gateway'; +import { EventsGateway, EventsGatewayxD } from './events.gateway'; @Module({ - components: [EventsGateway, EventsGatewayxD], + components: [EventsGateway, EventsGatewayxD] }) -export class EventsModule {} \ No newline at end of file +export class EventsModule {} diff --git a/examples/03-microservices/src/modules/app.module.ts b/examples/03-microservices/src/modules/app.module.ts index 062de7e7f3a..88468ef1ad9 100644 --- a/examples/03-microservices/src/modules/app.module.ts +++ b/examples/03-microservices/src/modules/app.module.ts @@ -2,6 +2,6 @@ import { Module } from '@nestjs/common'; import { MathModule } from './math/math.module'; @Module({ - modules: [MathModule], + modules: [MathModule] }) -export class ApplicationModule {} \ No newline at end of file +export class ApplicationModule {} diff --git a/examples/03-microservices/src/modules/common/adapters/rabbitmq-client.ts b/examples/03-microservices/src/modules/common/adapters/rabbitmq-client.ts index 07414b3d2ff..570558b605c 100644 --- a/examples/03-microservices/src/modules/common/adapters/rabbitmq-client.ts +++ b/examples/03-microservices/src/modules/common/adapters/rabbitmq-client.ts @@ -2,13 +2,14 @@ import * as amqp from 'amqplib'; import { ClientProxy } from '@nestjs/microservices'; export class RabbitMQClient extends ClientProxy { - constructor( - private readonly host: string, - private readonly queue: string) { - super(); - } + constructor(private readonly host: string, private readonly queue: string) { + super(); + } - protected async sendSingleMessage(messageObj, callback: (err, result, disposed?: boolean) => void) { + protected async sendSingleMessage( + messageObj, + callback: (err, result, disposed?: boolean) => void + ) { const server = await amqp.connect(this.host); const channel = await server.createChannel(); const { sub, pub } = this.getQueues(); @@ -16,15 +17,23 @@ export class RabbitMQClient extends ClientProxy { channel.assertQueue(sub, { durable: false }); channel.assertQueue(pub, { durable: false }); - channel.consume(pub, (message) => this.handleMessage(message, server, callback), { noAck: true }); + channel.consume( + pub, + message => this.handleMessage(message, server, callback), + { noAck: true } + ); channel.sendToQueue(sub, Buffer.from(JSON.stringify(messageObj))); } - private handleMessage(message, server, callback: (err, result, disposed?: boolean) => void) { + private handleMessage( + message, + server, + callback: (err, result, disposed?: boolean) => void + ) { const { content } = message; const { err, response, disposed } = JSON.parse(content.toString()); if (disposed) { - server.close(); + server.close(); } callback(err, response, disposed); } @@ -32,4 +41,4 @@ export class RabbitMQClient extends ClientProxy { private getQueues() { return { pub: `${this.queue}_pub`, sub: `${this.queue}_sub` }; } -} \ No newline at end of file +} diff --git a/examples/03-microservices/src/modules/common/adapters/rabbitmq-server.ts b/examples/03-microservices/src/modules/common/adapters/rabbitmq-server.ts index 3098bddefaa..02b79fc1dda 100644 --- a/examples/03-microservices/src/modules/common/adapters/rabbitmq-server.ts +++ b/examples/03-microservices/src/modules/common/adapters/rabbitmq-server.ts @@ -3,19 +3,17 @@ import { Server, CustomTransportStrategy } from '@nestjs/microservices'; import { Observable } from 'rxjs/Observable'; export class RabbitMQServer extends Server implements CustomTransportStrategy { - private server: amqp.Connection = null; - private channel: amqp.Channel = null; + private server: amqp.Connection = null; + private channel: amqp.Channel = null; - constructor( - private readonly host: string, - private readonly queue: string) { - super(); - } + constructor(private readonly host: string, private readonly queue: string) { + super(); + } public async listen(callback: () => void) { await this.init(); this.channel.consume(`${this.queue}_sub`, this.handleMessage.bind(this), { - noAck: true, + noAck: true }); } @@ -31,12 +29,14 @@ export class RabbitMQServer extends Server implements CustomTransportStrategy { const handlers = this.getHandlers(); const pattern = JSON.stringify(messageObj.pattern); if (!this.messageHandlers[pattern]) { - return; + return; } const handler = this.messageHandlers[pattern]; - const response$ = this.transformToObservable(await handler(messageObj.data)) as Observable; - response$ && this.send(response$, (data) => this.sendMessage(data)); + const response$ = this.transformToObservable( + await handler(messageObj.data) + ) as Observable; + response$ && this.send(response$, data => this.sendMessage(data)); } private sendMessage(message) { @@ -50,4 +50,4 @@ export class RabbitMQServer extends Server implements CustomTransportStrategy { this.channel.assertQueue(`${this.queue}_sub`, { durable: false }); this.channel.assertQueue(`${this.queue}_pub`, { durable: false }); } -} \ No newline at end of file +} diff --git a/examples/03-microservices/src/modules/common/decorators/roles.decorator.ts b/examples/03-microservices/src/modules/common/decorators/roles.decorator.ts index 91407a6e6a6..f58d46e6b3e 100644 --- a/examples/03-microservices/src/modules/common/decorators/roles.decorator.ts +++ b/examples/03-microservices/src/modules/common/decorators/roles.decorator.ts @@ -1,3 +1,3 @@ import { ReflectMetadata } from '@nestjs/common'; -export const Roles = (...roles: string[]) => ReflectMetadata('roles', roles); \ No newline at end of file +export const Roles = (...roles: string[]) => ReflectMetadata('roles', roles); diff --git a/examples/03-microservices/src/modules/common/filters/rpc-exception.filter.ts b/examples/03-microservices/src/modules/common/filters/rpc-exception.filter.ts index 9d6751aed22..ff8a553d6c5 100644 --- a/examples/03-microservices/src/modules/common/filters/rpc-exception.filter.ts +++ b/examples/03-microservices/src/modules/common/filters/rpc-exception.filter.ts @@ -8,4 +8,4 @@ export class ExceptionFilter implements RpcExceptionFilter { catch(exception: RpcException): Observable { return Observable.throw(exception.getError()); } -} \ No newline at end of file +} diff --git a/examples/03-microservices/src/modules/common/guards/roles.guard.ts b/examples/03-microservices/src/modules/common/guards/roles.guard.ts index b7511ff4239..a1c074a5923 100644 --- a/examples/03-microservices/src/modules/common/guards/roles.guard.ts +++ b/examples/03-microservices/src/modules/common/guards/roles.guard.ts @@ -14,7 +14,8 @@ export class RolesGuard implements CanActivate { } const user = data.user; - const hasRole = () => !!user.roles.find((role) => !!roles.find((item) => item === role)); + const hasRole = () => + !!user.roles.find(role => !!roles.find(item => item === role)); return user && user.roles && hasRole(); } -} \ No newline at end of file +} diff --git a/examples/03-microservices/src/modules/common/interceptors/cache.interceptor.ts b/examples/03-microservices/src/modules/common/interceptors/cache.interceptor.ts index 4baa6059acf..b645e2af6a5 100644 --- a/examples/03-microservices/src/modules/common/interceptors/cache.interceptor.ts +++ b/examples/03-microservices/src/modules/common/interceptors/cache.interceptor.ts @@ -4,11 +4,15 @@ import 'rxjs/add/observable/of'; @Interceptor() export class CacheInterceptor implements NestInterceptor { - intercept(dataOrRequest, context: ExecutionContext, stream$: Observable): Observable { + intercept( + dataOrRequest, + context: ExecutionContext, + stream$: Observable + ): Observable { const isCached = true; if (isCached) { return Observable.of([]); } return stream$; } -} \ No newline at end of file +} diff --git a/examples/03-microservices/src/modules/common/interceptors/logging.interceptor.ts b/examples/03-microservices/src/modules/common/interceptors/logging.interceptor.ts index 8e26e797b1a..7176ce9363a 100644 --- a/examples/03-microservices/src/modules/common/interceptors/logging.interceptor.ts +++ b/examples/03-microservices/src/modules/common/interceptors/logging.interceptor.ts @@ -4,12 +4,14 @@ import 'rxjs/add/operator/do'; @Interceptor() export class LoggingInterceptor implements NestInterceptor { - intercept(dataOrRequest, context: ExecutionContext, stream$: Observable): Observable { + intercept( + dataOrRequest, + context: ExecutionContext, + stream$: Observable + ): Observable { console.log('Before...'); const now = Date.now(); - return stream$.do( - () => console.log(`After... ${Date.now() - now}ms`), - ); + return stream$.do(() => console.log(`After... ${Date.now() - now}ms`)); } -} \ No newline at end of file +} diff --git a/examples/03-microservices/src/modules/common/interceptors/transform.interceptor.ts b/examples/03-microservices/src/modules/common/interceptors/transform.interceptor.ts index 792cc5464ed..35ec5c03a42 100644 --- a/examples/03-microservices/src/modules/common/interceptors/transform.interceptor.ts +++ b/examples/03-microservices/src/modules/common/interceptors/transform.interceptor.ts @@ -4,7 +4,11 @@ import 'rxjs/add/operator/map'; @Interceptor() export class TransformInterceptor implements NestInterceptor { - intercept(dataOrRequest, context: ExecutionContext, stream$: Observable): Observable { - return stream$.map((data) => ({ data })); + intercept( + dataOrRequest, + context: ExecutionContext, + stream$: Observable + ): Observable { + return stream$.map(data => ({ data })); } -} \ No newline at end of file +} diff --git a/examples/03-microservices/src/modules/common/pipes/validation.pipe.ts b/examples/03-microservices/src/modules/common/pipes/validation.pipe.ts index ecd291c36f8..c8f09a275bd 100644 --- a/examples/03-microservices/src/modules/common/pipes/validation.pipe.ts +++ b/examples/03-microservices/src/modules/common/pipes/validation.pipe.ts @@ -5,21 +5,21 @@ import { RpcException } from '@nestjs/microservices'; @Pipe() export class ValidationPipe implements PipeTransform { - async transform(value, metadata: ArgumentMetadata) { - const { metatype } = metadata; - if (!metatype || !this.toValidate(metatype)) { - return value; - } - const object = plainToClass(metatype, value); - const errors = await validate(object); - if (errors.length > 0) { - throw new RpcException('Validation failed'); - } + async transform(value, metadata: ArgumentMetadata) { + const { metatype } = metadata; + if (!metatype || !this.toValidate(metatype)) { return value; } - - private toValidate(metatype): boolean { - const types = [String, Boolean, Number, Array, Object]; - return !types.find((type) => metatype === type); + const object = plainToClass(metatype, value); + const errors = await validate(object); + if (errors.length > 0) { + throw new RpcException('Validation failed'); } + return value; + } + + private toValidate(metatype): boolean { + const types = [String, Boolean, Number, Array, Object]; + return !types.find(type => metatype === type); + } } diff --git a/examples/03-microservices/src/modules/math/math.controller.ts b/examples/03-microservices/src/modules/math/math.controller.ts index d4d7fa39614..e8eb27d85b8 100644 --- a/examples/03-microservices/src/modules/math/math.controller.ts +++ b/examples/03-microservices/src/modules/math/math.controller.ts @@ -1,5 +1,10 @@ import { Controller, Get, UseInterceptors } from '@nestjs/common'; -import { ClientProxy, Client, Transport, MessagePattern } from '@nestjs/microservices'; +import { + ClientProxy, + Client, + Transport, + MessagePattern +} from '@nestjs/microservices'; import { Observable } from 'rxjs/Observable'; import { LoggingInterceptor } from '../common/interceptors/logging.interceptor'; @@ -20,4 +25,4 @@ export class MathController { sum(data: number[]): number { return (data || []).reduce((a, b) => a + b); } -} \ No newline at end of file +} diff --git a/examples/03-microservices/src/modules/math/math.module.ts b/examples/03-microservices/src/modules/math/math.module.ts index 403d2b3ac61..497cc4be71a 100644 --- a/examples/03-microservices/src/modules/math/math.module.ts +++ b/examples/03-microservices/src/modules/math/math.module.ts @@ -2,6 +2,6 @@ import { Module } from '@nestjs/common'; import { MathController } from './math.controller'; @Module({ - controllers: [MathController], + controllers: [MathController] }) -export class MathModule {} \ No newline at end of file +export class MathModule {} diff --git a/examples/03-microservices/src/server.ts b/examples/03-microservices/src/server.ts index b452b6d3509..aba3846b10f 100644 --- a/examples/03-microservices/src/server.ts +++ b/examples/03-microservices/src/server.ts @@ -5,7 +5,7 @@ import { Transport } from '@nestjs/microservices'; async function bootstrap() { const app = await NestFactory.create(ApplicationModule); app.connectMicroservice({ - transport: Transport.TCP, + transport: Transport.TCP }); await app.startAllMicroservicesAsync(); diff --git a/examples/04-injector/src/modules/app.module.ts b/examples/04-injector/src/modules/app.module.ts index 2a71b05334b..cd663a76953 100644 --- a/examples/04-injector/src/modules/app.module.ts +++ b/examples/04-injector/src/modules/app.module.ts @@ -3,6 +3,6 @@ import { CoreModule } from './core/core.module'; import { FeatureModule } from './feature/feature.module'; @Module({ - modules: [FeatureModule], + modules: [FeatureModule] }) -export class ApplicationModule {} \ No newline at end of file +export class ApplicationModule {} diff --git a/examples/04-injector/src/modules/common/common.module.ts b/examples/04-injector/src/modules/common/common.module.ts index 8e3f8233853..070d8465d59 100644 --- a/examples/04-injector/src/modules/common/common.module.ts +++ b/examples/04-injector/src/modules/common/common.module.ts @@ -3,6 +3,6 @@ import { CommonService } from './common.service'; @Module({ components: [CommonService], - exports: [CommonService], + exports: [CommonService] }) -export class CommonModule {} \ No newline at end of file +export class CommonModule {} diff --git a/examples/04-injector/src/modules/common/common.service.ts b/examples/04-injector/src/modules/common/common.service.ts index 76eefdc282e..0a2d931f3d9 100644 --- a/examples/04-injector/src/modules/common/common.service.ts +++ b/examples/04-injector/src/modules/common/common.service.ts @@ -6,4 +6,4 @@ export class CommonService { constructor(private readonly coreService: CoreService) { console.log('CommonService', coreService); } -} \ No newline at end of file +} diff --git a/examples/04-injector/src/modules/core/context.service.ts b/examples/04-injector/src/modules/core/context.service.ts index 804d87c8a02..e4b7949a203 100644 --- a/examples/04-injector/src/modules/core/context.service.ts +++ b/examples/04-injector/src/modules/core/context.service.ts @@ -7,4 +7,4 @@ export class ContextService { constructor(private readonly commonService: CoreService) { console.log('ContextService', commonService); } -} \ No newline at end of file +} diff --git a/examples/04-injector/src/modules/core/core.module.ts b/examples/04-injector/src/modules/core/core.module.ts index 72d874884a2..9df07c26ea3 100644 --- a/examples/04-injector/src/modules/core/core.module.ts +++ b/examples/04-injector/src/modules/core/core.module.ts @@ -7,6 +7,6 @@ import { FeatureModule } from '../feature/feature.module'; @Module({ modules: [CommonModule], components: [CoreService, ContextService], - exports: [CommonModule], + exports: [CommonModule] }) -export class CoreModule {} \ No newline at end of file +export class CoreModule {} diff --git a/examples/04-injector/src/modules/core/core.service.ts b/examples/04-injector/src/modules/core/core.service.ts index 778521907da..43b85d511ce 100644 --- a/examples/04-injector/src/modules/core/core.service.ts +++ b/examples/04-injector/src/modules/core/core.service.ts @@ -5,4 +5,4 @@ export class CoreService { constructor() { console.log('CoreService'); } -} \ No newline at end of file +} diff --git a/examples/04-injector/src/modules/feature/feature.module.ts b/examples/04-injector/src/modules/feature/feature.module.ts index 0e82632cf3d..0df45c9dd5e 100644 --- a/examples/04-injector/src/modules/feature/feature.module.ts +++ b/examples/04-injector/src/modules/feature/feature.module.ts @@ -4,6 +4,6 @@ import { CoreModule } from '../core/core.module'; @Module({ modules: [CoreModule], - components: [FeatureService], + components: [FeatureService] }) -export class FeatureModule {} \ No newline at end of file +export class FeatureModule {} diff --git a/examples/04-injector/src/modules/feature/feature.service.ts b/examples/04-injector/src/modules/feature/feature.service.ts index 0745f72e9fe..ac26b6d7fdf 100644 --- a/examples/04-injector/src/modules/feature/feature.service.ts +++ b/examples/04-injector/src/modules/feature/feature.service.ts @@ -3,8 +3,7 @@ import { CommonService } from '../common/common.service'; @Component() export class FeatureService { - constructor( - private readonly commonService: CommonService) { + constructor(private readonly commonService: CommonService) { console.log('FeatureService', commonService); } -} \ No newline at end of file +} diff --git a/examples/05-sql-typeorm/src/modules/app.module.ts b/examples/05-sql-typeorm/src/modules/app.module.ts index bc384852d73..b08d8174eb2 100644 --- a/examples/05-sql-typeorm/src/modules/app.module.ts +++ b/examples/05-sql-typeorm/src/modules/app.module.ts @@ -5,9 +5,6 @@ import { PhotoModule } from './photo/photo.module'; import { Photo } from './photo/photo.entity'; @Module({ - modules: [ - TypeOrmModule.forRoot([Photo]), - PhotoModule, - ], + modules: [TypeOrmModule.forRoot([Photo]), PhotoModule] }) export class ApplicationModule {} diff --git a/examples/05-sql-typeorm/src/modules/photo/photo.entity.ts b/examples/05-sql-typeorm/src/modules/photo/photo.entity.ts index 3e4cf93e07a..7f356a1fbea 100644 --- a/examples/05-sql-typeorm/src/modules/photo/photo.entity.ts +++ b/examples/05-sql-typeorm/src/modules/photo/photo.entity.ts @@ -2,21 +2,16 @@ import { Entity, Column, PrimaryGeneratedColumn } from 'typeorm'; @Entity() export class Photo { - @PrimaryGeneratedColumn() - id: number; + @PrimaryGeneratedColumn() id: number; @Column({ length: 500 }) name: string; - @Column('text') - description: string; + @Column('text') description: string; - @Column() - filename: string; + @Column() filename: string; - @Column('int') - views: number; + @Column('int') views: number; - @Column() - isPublished: boolean; -} \ No newline at end of file + @Column() isPublished: boolean; +} diff --git a/examples/05-sql-typeorm/src/modules/photo/photo.module.ts b/examples/05-sql-typeorm/src/modules/photo/photo.module.ts index 9e529240aa8..09079a63d2f 100644 --- a/examples/05-sql-typeorm/src/modules/photo/photo.module.ts +++ b/examples/05-sql-typeorm/src/modules/photo/photo.module.ts @@ -4,6 +4,6 @@ import { PhotoController } from './photo.controller'; @Module({ components: [PhotoService], - controllers: [PhotoController], + controllers: [PhotoController] }) export class PhotoModule {} diff --git a/examples/05-sql-typeorm/src/modules/photo/photo.service.ts b/examples/05-sql-typeorm/src/modules/photo/photo.service.ts index 363d2ed4f10..65052e64d68 100644 --- a/examples/05-sql-typeorm/src/modules/photo/photo.service.ts +++ b/examples/05-sql-typeorm/src/modules/photo/photo.service.ts @@ -7,8 +7,7 @@ import { Photo } from './photo.entity'; @Component() export class PhotoService { constructor( - @InjectRepository(Photo) - private readonly photoRepository: Repository, + @InjectRepository(Photo) private readonly photoRepository: Repository ) {} async findAll(): Promise { diff --git a/examples/06-mongoose/src/modules/app.module.ts b/examples/06-mongoose/src/modules/app.module.ts index 14755869bc6..dd2663a6a0b 100644 --- a/examples/06-mongoose/src/modules/app.module.ts +++ b/examples/06-mongoose/src/modules/app.module.ts @@ -2,6 +2,6 @@ import { Module } from '@nestjs/common'; import { CatsModule } from './cats/cats.module'; @Module({ - modules: [CatsModule], + modules: [CatsModule] }) -export class ApplicationModule {} \ No newline at end of file +export class ApplicationModule {} diff --git a/examples/06-mongoose/src/modules/cats/cats.controller.ts b/examples/06-mongoose/src/modules/cats/cats.controller.ts index b06d98534e9..f93379c60b4 100644 --- a/examples/06-mongoose/src/modules/cats/cats.controller.ts +++ b/examples/06-mongoose/src/modules/cats/cats.controller.ts @@ -16,4 +16,4 @@ export class CatsController { async findAll(): Promise { return this.catsService.findAll(); } -} \ No newline at end of file +} diff --git a/examples/06-mongoose/src/modules/cats/cats.module.ts b/examples/06-mongoose/src/modules/cats/cats.module.ts index 972b9721055..f45f6a8d89a 100644 --- a/examples/06-mongoose/src/modules/cats/cats.module.ts +++ b/examples/06-mongoose/src/modules/cats/cats.module.ts @@ -7,9 +7,6 @@ import { DatabaseModule } from '../database/database.module'; @Module({ modules: [DatabaseModule], controllers: [CatsController], - components: [ - CatsService, - ...catsProviders, - ], + components: [CatsService, ...catsProviders] }) -export class CatsModule {} \ No newline at end of file +export class CatsModule {} diff --git a/examples/06-mongoose/src/modules/cats/cats.providers.ts b/examples/06-mongoose/src/modules/cats/cats.providers.ts index 701057c3dfa..b9305dee5a8 100644 --- a/examples/06-mongoose/src/modules/cats/cats.providers.ts +++ b/examples/06-mongoose/src/modules/cats/cats.providers.ts @@ -5,6 +5,6 @@ export const catsProviders = [ { provide: 'CatModelToken', useFactory: (connection: Connection) => connection.model('Cat', CatSchema), - inject: ['DbConnectionToken'], - }, -]; \ No newline at end of file + inject: ['DbConnectionToken'] + } +]; diff --git a/examples/06-mongoose/src/modules/cats/cats.service.ts b/examples/06-mongoose/src/modules/cats/cats.service.ts index 4b7d224b88d..69e8e40794b 100644 --- a/examples/06-mongoose/src/modules/cats/cats.service.ts +++ b/examples/06-mongoose/src/modules/cats/cats.service.ts @@ -5,8 +5,7 @@ import { CreateCatDto } from './dto/create-cat.dto'; @Component() export class CatsService { - constructor( - @Inject('CatModelToken') private readonly catModel: Model) {} + constructor(@Inject('CatModelToken') private readonly catModel: Model) {} async create(createCatDto: CreateCatDto): Promise { const createdCat = new this.catModel(createCatDto); @@ -16,4 +15,4 @@ export class CatsService { async findAll(): Promise { return await this.catModel.find().exec(); } -} \ No newline at end of file +} diff --git a/examples/06-mongoose/src/modules/cats/dto/create-cat.dto.ts b/examples/06-mongoose/src/modules/cats/dto/create-cat.dto.ts index 59514abbd9b..28ec6466aa5 100644 --- a/examples/06-mongoose/src/modules/cats/dto/create-cat.dto.ts +++ b/examples/06-mongoose/src/modules/cats/dto/create-cat.dto.ts @@ -2,4 +2,4 @@ export class CreateCatDto { readonly name: string; readonly age: number; readonly breed: string; -} \ No newline at end of file +} diff --git a/examples/06-mongoose/src/modules/cats/interfaces/cat.interface.ts b/examples/06-mongoose/src/modules/cats/interfaces/cat.interface.ts index 6e44c728c3b..3aa4000d17f 100644 --- a/examples/06-mongoose/src/modules/cats/interfaces/cat.interface.ts +++ b/examples/06-mongoose/src/modules/cats/interfaces/cat.interface.ts @@ -4,4 +4,4 @@ export interface Cat extends Document { readonly name: string; readonly age: number; readonly breed: string; -} \ No newline at end of file +} diff --git a/examples/06-mongoose/src/modules/cats/schemas/cat.schema.ts b/examples/06-mongoose/src/modules/cats/schemas/cat.schema.ts index 113692bcb1f..731250c5ec2 100644 --- a/examples/06-mongoose/src/modules/cats/schemas/cat.schema.ts +++ b/examples/06-mongoose/src/modules/cats/schemas/cat.schema.ts @@ -3,5 +3,5 @@ import * as mongoose from 'mongoose'; export const CatSchema = new mongoose.Schema({ name: String, age: Number, - breed: String, -}); \ No newline at end of file + breed: String +}); diff --git a/examples/06-mongoose/src/modules/database/database.module.ts b/examples/06-mongoose/src/modules/database/database.module.ts index 39da71c4dd2..697b1d4b032 100644 --- a/examples/06-mongoose/src/modules/database/database.module.ts +++ b/examples/06-mongoose/src/modules/database/database.module.ts @@ -3,6 +3,6 @@ import { databaseProviders } from './database.providers'; @Module({ components: [...databaseProviders], - exports: [...databaseProviders], + exports: [...databaseProviders] }) -export class DatabaseModule {} \ No newline at end of file +export class DatabaseModule {} diff --git a/examples/06-mongoose/src/modules/database/database.providers.ts b/examples/06-mongoose/src/modules/database/database.providers.ts index cd26f47a0ab..541c6cd9093 100644 --- a/examples/06-mongoose/src/modules/database/database.providers.ts +++ b/examples/06-mongoose/src/modules/database/database.providers.ts @@ -6,8 +6,8 @@ export const databaseProviders = [ useFactory: async (): Promise => { (mongoose as any).Promise = global.Promise; return await mongoose.connect('mongodb://localhost/nest', { - useMongoClient: true, + useMongoClient: true }); - }, - }, -]; \ No newline at end of file + } + } +]; diff --git a/examples/07-sequelize/src/modules/app.module.ts b/examples/07-sequelize/src/modules/app.module.ts index 14755869bc6..dd2663a6a0b 100644 --- a/examples/07-sequelize/src/modules/app.module.ts +++ b/examples/07-sequelize/src/modules/app.module.ts @@ -2,6 +2,6 @@ import { Module } from '@nestjs/common'; import { CatsModule } from './cats/cats.module'; @Module({ - modules: [CatsModule], + modules: [CatsModule] }) -export class ApplicationModule {} \ No newline at end of file +export class ApplicationModule {} diff --git a/examples/07-sequelize/src/modules/cats/cat.entity.ts b/examples/07-sequelize/src/modules/cats/cat.entity.ts index d1ca8f4a956..89c19c8a9c0 100644 --- a/examples/07-sequelize/src/modules/cats/cat.entity.ts +++ b/examples/07-sequelize/src/modules/cats/cat.entity.ts @@ -2,12 +2,9 @@ import { Table, Column, Model } from 'sequelize-typescript'; @Table export class Cat extends Model { - @Column - name: string; + @Column name: string; - @Column - age: number; + @Column age: number; - @Column - breed: string; + @Column breed: string; } diff --git a/examples/07-sequelize/src/modules/cats/cats.controller.ts b/examples/07-sequelize/src/modules/cats/cats.controller.ts index 3237b5e6b64..c6643f687fa 100644 --- a/examples/07-sequelize/src/modules/cats/cats.controller.ts +++ b/examples/07-sequelize/src/modules/cats/cats.controller.ts @@ -16,4 +16,4 @@ export class CatsController { async findAll(): Promise { return await this.catsService.findAll(); } -} \ No newline at end of file +} diff --git a/examples/07-sequelize/src/modules/cats/cats.module.ts b/examples/07-sequelize/src/modules/cats/cats.module.ts index 972b9721055..f45f6a8d89a 100644 --- a/examples/07-sequelize/src/modules/cats/cats.module.ts +++ b/examples/07-sequelize/src/modules/cats/cats.module.ts @@ -7,9 +7,6 @@ import { DatabaseModule } from '../database/database.module'; @Module({ modules: [DatabaseModule], controllers: [CatsController], - components: [ - CatsService, - ...catsProviders, - ], + components: [CatsService, ...catsProviders] }) -export class CatsModule {} \ No newline at end of file +export class CatsModule {} diff --git a/examples/07-sequelize/src/modules/cats/cats.providers.ts b/examples/07-sequelize/src/modules/cats/cats.providers.ts index 123a4f73828..cde728f2b5c 100644 --- a/examples/07-sequelize/src/modules/cats/cats.providers.ts +++ b/examples/07-sequelize/src/modules/cats/cats.providers.ts @@ -3,6 +3,6 @@ import { Cat } from './cat.entity'; export const catsProviders = [ { provide: 'CatsRepository', - useValue: Cat, - }, -]; \ No newline at end of file + useValue: Cat + } +]; diff --git a/examples/07-sequelize/src/modules/cats/cats.service.ts b/examples/07-sequelize/src/modules/cats/cats.service.ts index 9c61c9f512d..cf08ea5530a 100644 --- a/examples/07-sequelize/src/modules/cats/cats.service.ts +++ b/examples/07-sequelize/src/modules/cats/cats.service.ts @@ -1,4 +1,3 @@ - import { Component, Inject } from '@nestjs/common'; import { CreateCatDto } from './dto/create-cat.dto'; import { Model } from 'sequelize-typescript'; @@ -7,7 +6,8 @@ import { Cat } from './cat.entity'; @Component() export class CatsService { constructor( - @Inject('CatsRepository') private readonly catsRepository: typeof Cat) {} + @Inject('CatsRepository') private readonly catsRepository: typeof Cat + ) {} async create(createCatDto: CreateCatDto): Promise { const cat = new Cat(); @@ -21,4 +21,4 @@ export class CatsService { async findAll(): Promise { return await this.catsRepository.findAll(); } -} \ No newline at end of file +} diff --git a/examples/07-sequelize/src/modules/cats/dto/create-cat.dto.ts b/examples/07-sequelize/src/modules/cats/dto/create-cat.dto.ts index 59514abbd9b..28ec6466aa5 100644 --- a/examples/07-sequelize/src/modules/cats/dto/create-cat.dto.ts +++ b/examples/07-sequelize/src/modules/cats/dto/create-cat.dto.ts @@ -2,4 +2,4 @@ export class CreateCatDto { readonly name: string; readonly age: number; readonly breed: string; -} \ No newline at end of file +} diff --git a/examples/07-sequelize/src/modules/database/database.module.ts b/examples/07-sequelize/src/modules/database/database.module.ts index 39da71c4dd2..697b1d4b032 100644 --- a/examples/07-sequelize/src/modules/database/database.module.ts +++ b/examples/07-sequelize/src/modules/database/database.module.ts @@ -3,6 +3,6 @@ import { databaseProviders } from './database.providers'; @Module({ components: [...databaseProviders], - exports: [...databaseProviders], + exports: [...databaseProviders] }) -export class DatabaseModule {} \ No newline at end of file +export class DatabaseModule {} diff --git a/examples/07-sequelize/src/modules/database/database.providers.ts b/examples/07-sequelize/src/modules/database/database.providers.ts index c1e48f40dd3..579e578c234 100644 --- a/examples/07-sequelize/src/modules/database/database.providers.ts +++ b/examples/07-sequelize/src/modules/database/database.providers.ts @@ -11,11 +11,11 @@ export const databaseProviders = [ port: 3306, username: 'root', password: '', - database: 'test', + database: 'test' }); sequelize.addModels([Cat]); await sequelize.sync(); return sequelize; - }, - }, -]; \ No newline at end of file + } + } +]; diff --git a/examples/08-passport/src/modules/app.module.ts b/examples/08-passport/src/modules/app.module.ts index a556b2b7980..22232064e36 100644 --- a/examples/08-passport/src/modules/app.module.ts +++ b/examples/08-passport/src/modules/app.module.ts @@ -2,6 +2,6 @@ import { Module } from '@nestjs/common'; import { AuthModule } from './auth/auth.module'; @Module({ - modules: [AuthModule], + modules: [AuthModule] }) -export class ApplicationModule {} \ No newline at end of file +export class ApplicationModule {} diff --git a/examples/08-passport/src/modules/auth/auth.module.ts b/examples/08-passport/src/modules/auth/auth.module.ts index 7d76a172b5f..8665a8ce7e5 100644 --- a/examples/08-passport/src/modules/auth/auth.module.ts +++ b/examples/08-passport/src/modules/auth/auth.module.ts @@ -3,18 +3,15 @@ import { Module, NestModule, MiddlewaresConsumer, - RequestMethod, + RequestMethod } from '@nestjs/common'; import { AuthService } from './auth.service'; import { JwtStrategy } from './passport/jwt.strategy'; import { AuthController } from './auth.controller'; @Module({ - components: [ - AuthService, - JwtStrategy, - ], - controllers: [AuthController], + components: [AuthService, JwtStrategy], + controllers: [AuthController] }) export class AuthModule implements NestModule { public configure(consumer: MiddlewaresConsumer) { diff --git a/examples/08-passport/src/modules/auth/auth.service.ts b/examples/08-passport/src/modules/auth/auth.service.ts index 590ae48c221..c9bcac714e5 100644 --- a/examples/08-passport/src/modules/auth/auth.service.ts +++ b/examples/08-passport/src/modules/auth/auth.service.ts @@ -4,12 +4,13 @@ import { Component, Inject } from '@nestjs/common'; @Component() export class AuthService { async createToken() { - const expiresIn = 60 * 60, secretOrKey = 'secret'; + const expiresIn = 60 * 60, + secretOrKey = 'secret'; const user = { email: 'thisis@example.com' }; const token = jwt.sign(user, secretOrKey, { expiresIn }); return { expires_in: expiresIn, - access_token: token, + access_token: token }; } diff --git a/examples/08-passport/src/modules/auth/passport/jwt.strategy.ts b/examples/08-passport/src/modules/auth/passport/jwt.strategy.ts index be460c4cfd2..48560eeb980 100644 --- a/examples/08-passport/src/modules/auth/passport/jwt.strategy.ts +++ b/examples/08-passport/src/modules/auth/passport/jwt.strategy.ts @@ -10,7 +10,7 @@ export class JwtStrategy extends Strategy { { jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(), passReqToCallback: true, - secretOrKey: 'secret', + secretOrKey: 'secret' }, async (req, payload, next) => await this.verify(req, payload, next) ); diff --git a/examples/10-mockgoose/e2e/cats/cats.e2e-spec.ts b/examples/10-mockgoose/e2e/cats/cats.e2e-spec.ts index 4eb5568d80b..64f93b17225 100644 --- a/examples/10-mockgoose/e2e/cats/cats.e2e-spec.ts +++ b/examples/10-mockgoose/e2e/cats/cats.e2e-spec.ts @@ -5,42 +5,40 @@ import { Test } from '@nestjs/testing'; import { CatsModule } from '../../src/modules/cats/cats.module'; describe('Cats', () => { - const server = express(); - server.use(bodyParser.json()); - - beforeAll(async () => { - const module = await Test.createTestingModule({ - modules: [CatsModule], - }) - .compile(); - - const app = module.createNestApplication(server); - await app.init(); - }); - - it(`/POST insert cat`, () => { - return request(server) - .post('/cats') - .send({ - name: 'Tiger', - age: 2, - breed: 'Russian Blue' - }) - .expect(201); - }); - - it(`/GET cats`, async (done) => { - - const cats = await request(server) - .get('/cats') - .expect(200); - - const [cat] = cats.body; - - expect(cat.name).toBe('Tiger'); - expect(cat.age).toBe(2); - expect(cat.breed).toBe('Russian Blue'); - - done(); - }); -}); \ No newline at end of file + const server = express(); + server.use(bodyParser.json()); + + beforeAll(async () => { + const module = await Test.createTestingModule({ + modules: [CatsModule] + }).compile(); + + const app = module.createNestApplication(server); + await app.init(); + }); + + it(`/POST insert cat`, () => { + return request(server) + .post('/cats') + .send({ + name: 'Tiger', + age: 2, + breed: 'Russian Blue' + }) + .expect(201); + }); + + it(`/GET cats`, async done => { + const cats = await request(server) + .get('/cats') + .expect(200); + + const [cat] = cats.body; + + expect(cat.name).toBe('Tiger'); + expect(cat.age).toBe(2); + expect(cat.breed).toBe('Russian Blue'); + + done(); + }); +}); diff --git a/examples/10-mockgoose/src/modules/app.module.ts b/examples/10-mockgoose/src/modules/app.module.ts index 14755869bc6..dd2663a6a0b 100644 --- a/examples/10-mockgoose/src/modules/app.module.ts +++ b/examples/10-mockgoose/src/modules/app.module.ts @@ -2,6 +2,6 @@ import { Module } from '@nestjs/common'; import { CatsModule } from './cats/cats.module'; @Module({ - modules: [CatsModule], + modules: [CatsModule] }) -export class ApplicationModule {} \ No newline at end of file +export class ApplicationModule {} diff --git a/examples/10-mockgoose/src/modules/cats/cats.controller.ts b/examples/10-mockgoose/src/modules/cats/cats.controller.ts index b06d98534e9..f93379c60b4 100644 --- a/examples/10-mockgoose/src/modules/cats/cats.controller.ts +++ b/examples/10-mockgoose/src/modules/cats/cats.controller.ts @@ -16,4 +16,4 @@ export class CatsController { async findAll(): Promise { return this.catsService.findAll(); } -} \ No newline at end of file +} diff --git a/examples/10-mockgoose/src/modules/cats/cats.module.ts b/examples/10-mockgoose/src/modules/cats/cats.module.ts index 972b9721055..f45f6a8d89a 100644 --- a/examples/10-mockgoose/src/modules/cats/cats.module.ts +++ b/examples/10-mockgoose/src/modules/cats/cats.module.ts @@ -7,9 +7,6 @@ import { DatabaseModule } from '../database/database.module'; @Module({ modules: [DatabaseModule], controllers: [CatsController], - components: [ - CatsService, - ...catsProviders, - ], + components: [CatsService, ...catsProviders] }) -export class CatsModule {} \ No newline at end of file +export class CatsModule {} diff --git a/examples/10-mockgoose/src/modules/cats/cats.providers.ts b/examples/10-mockgoose/src/modules/cats/cats.providers.ts index 1b9b060466d..ac928e92777 100644 --- a/examples/10-mockgoose/src/modules/cats/cats.providers.ts +++ b/examples/10-mockgoose/src/modules/cats/cats.providers.ts @@ -4,7 +4,7 @@ import { CatSchema } from './schemas/cat.schema'; export const catsProviders = [ { provide: 'CatModelToken', - useFactory: (mongoose) => mongoose.connection.model('Cat', CatSchema), - inject: ['DbToken'], - }, -]; \ No newline at end of file + useFactory: mongoose => mongoose.connection.model('Cat', CatSchema), + inject: ['DbToken'] + } +]; diff --git a/examples/10-mockgoose/src/modules/cats/cats.service.ts b/examples/10-mockgoose/src/modules/cats/cats.service.ts index 4b7d224b88d..69e8e40794b 100644 --- a/examples/10-mockgoose/src/modules/cats/cats.service.ts +++ b/examples/10-mockgoose/src/modules/cats/cats.service.ts @@ -5,8 +5,7 @@ import { CreateCatDto } from './dto/create-cat.dto'; @Component() export class CatsService { - constructor( - @Inject('CatModelToken') private readonly catModel: Model) {} + constructor(@Inject('CatModelToken') private readonly catModel: Model) {} async create(createCatDto: CreateCatDto): Promise { const createdCat = new this.catModel(createCatDto); @@ -16,4 +15,4 @@ export class CatsService { async findAll(): Promise { return await this.catModel.find().exec(); } -} \ No newline at end of file +} diff --git a/examples/10-mockgoose/src/modules/cats/dto/create-cat.dto.ts b/examples/10-mockgoose/src/modules/cats/dto/create-cat.dto.ts index 59514abbd9b..28ec6466aa5 100644 --- a/examples/10-mockgoose/src/modules/cats/dto/create-cat.dto.ts +++ b/examples/10-mockgoose/src/modules/cats/dto/create-cat.dto.ts @@ -2,4 +2,4 @@ export class CreateCatDto { readonly name: string; readonly age: number; readonly breed: string; -} \ No newline at end of file +} diff --git a/examples/10-mockgoose/src/modules/cats/interfaces/cat.interface.ts b/examples/10-mockgoose/src/modules/cats/interfaces/cat.interface.ts index 6e44c728c3b..3aa4000d17f 100644 --- a/examples/10-mockgoose/src/modules/cats/interfaces/cat.interface.ts +++ b/examples/10-mockgoose/src/modules/cats/interfaces/cat.interface.ts @@ -4,4 +4,4 @@ export interface Cat extends Document { readonly name: string; readonly age: number; readonly breed: string; -} \ No newline at end of file +} diff --git a/examples/10-mockgoose/src/modules/cats/schemas/cat.schema.ts b/examples/10-mockgoose/src/modules/cats/schemas/cat.schema.ts index 113692bcb1f..731250c5ec2 100644 --- a/examples/10-mockgoose/src/modules/cats/schemas/cat.schema.ts +++ b/examples/10-mockgoose/src/modules/cats/schemas/cat.schema.ts @@ -3,5 +3,5 @@ import * as mongoose from 'mongoose'; export const CatSchema = new mongoose.Schema({ name: String, age: Number, - breed: String, -}); \ No newline at end of file + breed: String +}); diff --git a/examples/10-mockgoose/src/modules/database/database.module.ts b/examples/10-mockgoose/src/modules/database/database.module.ts index 39da71c4dd2..697b1d4b032 100644 --- a/examples/10-mockgoose/src/modules/database/database.module.ts +++ b/examples/10-mockgoose/src/modules/database/database.module.ts @@ -3,6 +3,6 @@ import { databaseProviders } from './database.providers'; @Module({ components: [...databaseProviders], - exports: [...databaseProviders], + exports: [...databaseProviders] }) -export class DatabaseModule {} \ No newline at end of file +export class DatabaseModule {} diff --git a/examples/10-mockgoose/src/modules/database/database.providers.ts b/examples/10-mockgoose/src/modules/database/database.providers.ts index a2a76dddd10..f7c18455c86 100644 --- a/examples/10-mockgoose/src/modules/database/database.providers.ts +++ b/examples/10-mockgoose/src/modules/database/database.providers.ts @@ -8,25 +8,21 @@ export const databaseProviders = [ (mongoose as any).Promise = global.Promise; if (process.env.NODE_ENV === 'test') { + const mockgoose = new Mockgoose(mongoose); + mockgoose.helper.setDbVersion('3.4.3'); - const mockgoose = new Mockgoose(mongoose); - mockgoose.helper.setDbVersion('3.4.3'); - - mockgoose.prepareStorage() - .then(async () => { - await mongoose.connect('mongodb://example.com/TestingDB', { - useMongoClient: true, - }); - }); - - } else { - - await mongoose.connect('mongodb://localhost/nest', { - useMongoClient: true, + mockgoose.prepareStorage().then(async () => { + await mongoose.connect('mongodb://example.com/TestingDB', { + useMongoClient: true }); + }); + } else { + await mongoose.connect('mongodb://localhost/nest', { + useMongoClient: true + }); } return mongoose; - }, - }, -]; \ No newline at end of file + } + } +]; diff --git a/examples/11-swagger/src/modules/app.module.ts b/examples/11-swagger/src/modules/app.module.ts index 8254cc95c73..ec154e261a1 100644 --- a/examples/11-swagger/src/modules/app.module.ts +++ b/examples/11-swagger/src/modules/app.module.ts @@ -3,6 +3,6 @@ import { CatsModule } from './cats/cats.module'; import { CatsController } from './cats/cats.controller'; @Module({ - modules: [CatsModule], + modules: [CatsModule] }) -export class ApplicationModule {} \ No newline at end of file +export class ApplicationModule {} diff --git a/examples/11-swagger/src/modules/cats/cats.controller.ts b/examples/11-swagger/src/modules/cats/cats.controller.ts index ea919f1ecc4..f8619597f30 100644 --- a/examples/11-swagger/src/modules/cats/cats.controller.ts +++ b/examples/11-swagger/src/modules/cats/cats.controller.ts @@ -2,7 +2,12 @@ import { Controller, Get, Post, Body, Param } from '@nestjs/common'; import { CreateCatDto } from './dto/create-cat.dto'; import { CatsService } from './cats.service'; import { Cat } from './interfaces/cat.interface'; -import { ApiUseTags, ApiBearerAuth, ApiResponse, ApiOperation } from '@nestjs/swagger'; +import { + ApiUseTags, + ApiBearerAuth, + ApiResponse, + ApiOperation +} from '@nestjs/swagger'; @ApiBearerAuth() @ApiUseTags('cats') @@ -12,8 +17,11 @@ export class CatsController { @Post() @ApiOperation({ title: 'Create cat' }) - @ApiResponse({ status: 201, description: 'The record has been successfully created.'}) - @ApiResponse({ status: 403, description: 'Forbidden.'}) + @ApiResponse({ + status: 201, + description: 'The record has been successfully created.' + }) + @ApiResponse({ status: 403, description: 'Forbidden.' }) async create(@Body() createCatDto: CreateCatDto) { this.catsService.create(createCatDto); } @@ -22,4 +30,4 @@ export class CatsController { findOne(@Param('id') id: string): Cat { return this.catsService.findOne(+id); } -} \ No newline at end of file +} diff --git a/examples/11-swagger/src/modules/cats/cats.module.ts b/examples/11-swagger/src/modules/cats/cats.module.ts index cece71d4664..1177abc4edb 100644 --- a/examples/11-swagger/src/modules/cats/cats.module.ts +++ b/examples/11-swagger/src/modules/cats/cats.module.ts @@ -3,7 +3,7 @@ import { CatsController } from './cats.controller'; import { CatsService } from './cats.service'; @Module({ - controllers: [CatsController], - components: [CatsService], + controllers: [CatsController], + components: [CatsService] }) -export class CatsModule {} \ No newline at end of file +export class CatsModule {} diff --git a/examples/11-swagger/src/modules/cats/cats.service.ts b/examples/11-swagger/src/modules/cats/cats.service.ts index db000d62e61..0a4e9012a77 100644 --- a/examples/11-swagger/src/modules/cats/cats.service.ts +++ b/examples/11-swagger/src/modules/cats/cats.service.ts @@ -13,4 +13,4 @@ export class CatsService { findOne(id: number): Cat { return this.cats[id]; } -} \ No newline at end of file +} diff --git a/examples/11-swagger/src/modules/cats/dto/create-cat.dto.ts b/examples/11-swagger/src/modules/cats/dto/create-cat.dto.ts index 915c6d85a54..9fc801fd793 100644 --- a/examples/11-swagger/src/modules/cats/dto/create-cat.dto.ts +++ b/examples/11-swagger/src/modules/cats/dto/create-cat.dto.ts @@ -13,4 +13,4 @@ export class CreateCatDto { @ApiModelProperty({ type: String }) @IsString() readonly breed; -} \ No newline at end of file +} diff --git a/examples/11-swagger/src/modules/cats/interfaces/cat.interface.ts b/examples/11-swagger/src/modules/cats/interfaces/cat.interface.ts index 043779cd362..b3e66c4b676 100644 --- a/examples/11-swagger/src/modules/cats/interfaces/cat.interface.ts +++ b/examples/11-swagger/src/modules/cats/interfaces/cat.interface.ts @@ -2,4 +2,4 @@ export interface Cat { readonly name: string; readonly age: number; readonly breed: string; -} \ No newline at end of file +} diff --git a/examples/11-swagger/src/server.ts b/examples/11-swagger/src/server.ts index aeaedd5c9eb..dfdff369f53 100644 --- a/examples/11-swagger/src/server.ts +++ b/examples/11-swagger/src/server.ts @@ -3,18 +3,18 @@ import { SwaggerModule, DocumentBuilder } from '@nestjs/swagger'; import { ApplicationModule } from './modules/app.module'; async function bootstrap() { - const app = await NestFactory.create(ApplicationModule); + const app = await NestFactory.create(ApplicationModule); - const options = new DocumentBuilder() - .setTitle('Cats example') - .setDescription('The cats API description') - .setVersion('1.0') + const options = new DocumentBuilder() + .setTitle('Cats example') + .setDescription('The cats API description') + .setVersion('1.0') .addTag('cats') .addBearerAuth() - .build(); - const document = SwaggerModule.createDocument(app, options); - SwaggerModule.setup('/api', app, document); + .build(); + const document = SwaggerModule.createDocument(app, options); + SwaggerModule.setup('/api', app, document); - await app.listen(3001); + await app.listen(3001); } bootstrap(); diff --git a/examples/12-graphql-apollo/src/modules/app.module.ts b/examples/12-graphql-apollo/src/modules/app.module.ts index 0cae09c24ab..d233dab7461 100644 --- a/examples/12-graphql-apollo/src/modules/app.module.ts +++ b/examples/12-graphql-apollo/src/modules/app.module.ts @@ -2,20 +2,20 @@ import { Module, MiddlewaresConsumer, NestModule, - RequestMethod, + RequestMethod } from '@nestjs/common'; import { graphqlExpress, graphiqlExpress } from 'apollo-server-express'; import { makeExecutableSchema, addMockFunctionsToSchema, - mergeSchemas, + mergeSchemas } from 'graphql-tools'; import { GraphQLModule, GraphQLFactory } from '@nestjs/graphql'; import { CatsModule } from './cats/cats.module'; @Module({ - modules: [CatsModule, GraphQLModule], + modules: [CatsModule, GraphQLModule] }) export class ApplicationModule { constructor(private readonly graphQLFactory: GraphQLFactory) {} @@ -37,7 +37,7 @@ export class ApplicationModule { const { humanSchema, linkTypeDefs } = this.createDelegatedSchema(); return mergeSchemas({ schemas: [schema, humanSchema, linkTypeDefs], - resolvers: delegates, + resolvers: delegates }); } @@ -55,7 +55,7 @@ export class ApplicationModule { type Query { humanById(id: ID!): Human } - `, + ` }); addMockFunctionsToSchema({ schema: humanSchema }); return { humanSchema, linkTypeDefs }; diff --git a/examples/12-graphql-apollo/src/modules/cats/cats.module.ts b/examples/12-graphql-apollo/src/modules/cats/cats.module.ts index 8b7ee2c612d..fad2e0f2bd1 100644 --- a/examples/12-graphql-apollo/src/modules/cats/cats.module.ts +++ b/examples/12-graphql-apollo/src/modules/cats/cats.module.ts @@ -3,6 +3,6 @@ import { CatsService } from './cats.service'; import { CatsResolvers } from './cats.resolvers'; @Module({ - components: [CatsService, CatsResolvers], + components: [CatsService, CatsResolvers] }) export class CatsModule {} diff --git a/examples/12-graphql-apollo/src/modules/cats/cats.resolvers.ts b/examples/12-graphql-apollo/src/modules/cats/cats.resolvers.ts index 3d56c10986e..c2f555ea7a8 100644 --- a/examples/12-graphql-apollo/src/modules/cats/cats.resolvers.ts +++ b/examples/12-graphql-apollo/src/modules/cats/cats.resolvers.ts @@ -1,10 +1,5 @@ import { Component, UseGuards } from '@nestjs/common'; -import { - Query, - Mutation, - Resolver, - DelegateProperty, -} from '@nestjs/graphql'; +import { Query, Mutation, Resolver, DelegateProperty } from '@nestjs/graphql'; import { Cat } from './interfaces/cat.interface'; import { CatsService } from './cats.service'; @@ -41,12 +36,12 @@ export class CatsResolvers { 'query', 'humanById', { - id: humanId, + id: humanId }, context, - info, + info ); - }, + } }); } } diff --git a/examples/12-graphql-apollo/src/modules/cats/cats.service.ts b/examples/12-graphql-apollo/src/modules/cats/cats.service.ts index 71efe194c78..bfb8a7b7db0 100644 --- a/examples/12-graphql-apollo/src/modules/cats/cats.service.ts +++ b/examples/12-graphql-apollo/src/modules/cats/cats.service.ts @@ -3,9 +3,7 @@ import { Cat } from './interfaces/cat.interface'; @Component() export class CatsService { - private readonly cats: Cat[] = [ - { id: 1, name: 'Cat', age: 5 }, - ]; + private readonly cats: Cat[] = [{ id: 1, name: 'Cat', age: 5 }]; create(cat: Cat) { this.cats.push(cat); @@ -16,6 +14,6 @@ export class CatsService { } findOneById(id: number): Cat { - return this.cats.find((cat) => cat.id === id); + return this.cats.find(cat => cat.id === id); } } diff --git a/examples/12-graphql-apollo/src/modules/cats/interfaces/cat.interface.ts b/examples/12-graphql-apollo/src/modules/cats/interfaces/cat.interface.ts index dc63eae94d8..e0f9e0a73bb 100644 --- a/examples/12-graphql-apollo/src/modules/cats/interfaces/cat.interface.ts +++ b/examples/12-graphql-apollo/src/modules/cats/interfaces/cat.interface.ts @@ -2,4 +2,4 @@ export interface Cat { readonly id: number; readonly name: string; readonly age: number; -} \ No newline at end of file +} diff --git a/examples/13-mongo-typeorm/src/modules/app.module.ts b/examples/13-mongo-typeorm/src/modules/app.module.ts index bc384852d73..b08d8174eb2 100644 --- a/examples/13-mongo-typeorm/src/modules/app.module.ts +++ b/examples/13-mongo-typeorm/src/modules/app.module.ts @@ -5,9 +5,6 @@ import { PhotoModule } from './photo/photo.module'; import { Photo } from './photo/photo.entity'; @Module({ - modules: [ - TypeOrmModule.forRoot([Photo]), - PhotoModule, - ], + modules: [TypeOrmModule.forRoot([Photo]), PhotoModule] }) export class ApplicationModule {} diff --git a/examples/13-mongo-typeorm/src/modules/photo/photo.entity.ts b/examples/13-mongo-typeorm/src/modules/photo/photo.entity.ts index d15d040ea42..15feaeb87ee 100644 --- a/examples/13-mongo-typeorm/src/modules/photo/photo.entity.ts +++ b/examples/13-mongo-typeorm/src/modules/photo/photo.entity.ts @@ -1,19 +1,20 @@ -import { Entity, Column, PrimaryGeneratedColumn, ObjectIdColumn, ObjectID } from 'typeorm'; +import { + Entity, + Column, + PrimaryGeneratedColumn, + ObjectIdColumn, + ObjectID +} from 'typeorm'; @Entity() export class Photo { - @ObjectIdColumn() - id: ObjectID; + @ObjectIdColumn() id: ObjectID; - @Column() - name: string; + @Column() name: string; - @Column() - description: string; + @Column() description: string; - @Column() - filename: string; + @Column() filename: string; - @Column() - isPublished: boolean; -} \ No newline at end of file + @Column() isPublished: boolean; +} diff --git a/examples/13-mongo-typeorm/src/modules/photo/photo.module.ts b/examples/13-mongo-typeorm/src/modules/photo/photo.module.ts index 9e529240aa8..09079a63d2f 100644 --- a/examples/13-mongo-typeorm/src/modules/photo/photo.module.ts +++ b/examples/13-mongo-typeorm/src/modules/photo/photo.module.ts @@ -4,6 +4,6 @@ import { PhotoController } from './photo.controller'; @Module({ components: [PhotoService], - controllers: [PhotoController], + controllers: [PhotoController] }) export class PhotoModule {} diff --git a/examples/13-mongo-typeorm/src/modules/photo/photo.service.ts b/examples/13-mongo-typeorm/src/modules/photo/photo.service.ts index 363d2ed4f10..65052e64d68 100644 --- a/examples/13-mongo-typeorm/src/modules/photo/photo.service.ts +++ b/examples/13-mongo-typeorm/src/modules/photo/photo.service.ts @@ -7,8 +7,7 @@ import { Photo } from './photo.entity'; @Component() export class PhotoService { constructor( - @InjectRepository(Photo) - private readonly photoRepository: Repository, + @InjectRepository(Photo) private readonly photoRepository: Repository ) {} async findAll(): Promise { diff --git a/examples/14-mongoose-module/src/modules/app.module.ts b/examples/14-mongoose-module/src/modules/app.module.ts index 0b080ce0255..5dd3d47b43b 100644 --- a/examples/14-mongoose-module/src/modules/app.module.ts +++ b/examples/14-mongoose-module/src/modules/app.module.ts @@ -7,9 +7,9 @@ import { CatSchema } from './cats/schemas/cat.schema'; @Module({ modules: [ MongooseModule.forRoot('mongodb://localhost/nest', [ - { name: 'Cat', schema: CatSchema }, + { name: 'Cat', schema: CatSchema } ]), - CatsModule, - ], + CatsModule + ] }) export class ApplicationModule {} diff --git a/examples/14-mongoose-module/src/modules/cats/cats.controller.ts b/examples/14-mongoose-module/src/modules/cats/cats.controller.ts index b06d98534e9..f93379c60b4 100644 --- a/examples/14-mongoose-module/src/modules/cats/cats.controller.ts +++ b/examples/14-mongoose-module/src/modules/cats/cats.controller.ts @@ -16,4 +16,4 @@ export class CatsController { async findAll(): Promise { return this.catsService.findAll(); } -} \ No newline at end of file +} diff --git a/examples/14-mongoose-module/src/modules/cats/cats.module.ts b/examples/14-mongoose-module/src/modules/cats/cats.module.ts index 98c750033e4..1177abc4edb 100644 --- a/examples/14-mongoose-module/src/modules/cats/cats.module.ts +++ b/examples/14-mongoose-module/src/modules/cats/cats.module.ts @@ -4,6 +4,6 @@ import { CatsService } from './cats.service'; @Module({ controllers: [CatsController], - components: [CatsService], + components: [CatsService] }) export class CatsModule {} diff --git a/examples/14-mongoose-module/src/modules/cats/dto/create-cat.dto.ts b/examples/14-mongoose-module/src/modules/cats/dto/create-cat.dto.ts index 59514abbd9b..28ec6466aa5 100644 --- a/examples/14-mongoose-module/src/modules/cats/dto/create-cat.dto.ts +++ b/examples/14-mongoose-module/src/modules/cats/dto/create-cat.dto.ts @@ -2,4 +2,4 @@ export class CreateCatDto { readonly name: string; readonly age: number; readonly breed: string; -} \ No newline at end of file +} diff --git a/examples/14-mongoose-module/src/modules/cats/interfaces/cat.interface.ts b/examples/14-mongoose-module/src/modules/cats/interfaces/cat.interface.ts index 6e44c728c3b..3aa4000d17f 100644 --- a/examples/14-mongoose-module/src/modules/cats/interfaces/cat.interface.ts +++ b/examples/14-mongoose-module/src/modules/cats/interfaces/cat.interface.ts @@ -4,4 +4,4 @@ export interface Cat extends Document { readonly name: string; readonly age: number; readonly breed: string; -} \ No newline at end of file +} diff --git a/examples/14-mongoose-module/src/modules/cats/schemas/cat.schema.ts b/examples/14-mongoose-module/src/modules/cats/schemas/cat.schema.ts index 113692bcb1f..731250c5ec2 100644 --- a/examples/14-mongoose-module/src/modules/cats/schemas/cat.schema.ts +++ b/examples/14-mongoose-module/src/modules/cats/schemas/cat.schema.ts @@ -3,5 +3,5 @@ import * as mongoose from 'mongoose'; export const CatSchema = new mongoose.Schema({ name: String, age: Number, - breed: String, -}); \ No newline at end of file + breed: String +}); diff --git a/lib/common/constants.d.ts b/lib/common/constants.d.ts index b2aa2442ae9..e25eb0182b7 100644 --- a/lib/common/constants.d.ts +++ b/lib/common/constants.d.ts @@ -1,21 +1,21 @@ export declare const metadata: { - MODULES: string; - COMPONENTS: string; - CONTROLLERS: string; - EXPORTS: string; + MODULES: string; + COMPONENTS: string; + CONTROLLERS: string; + EXPORTS: string; }; -export declare const SHARED_MODULE_METADATA = "__sharedModule__"; -export declare const GLOBAL_MODULE_METADATA = "__globalModule__"; -export declare const PATH_METADATA = "path"; -export declare const PARAMTYPES_METADATA = "design:paramtypes"; -export declare const SELF_DECLARED_DEPS_METADATA = "self:paramtypes"; -export declare const METHOD_METADATA = "method"; -export declare const ROUTE_ARGS_METADATA = "__routeArguments__"; -export declare const CUSTOM_ROUTE_AGRS_METADATA = "__customRouteArgs__"; -export declare const EXCEPTION_FILTERS_METADATA = "__exceptionFilters__"; -export declare const FILTER_CATCH_EXCEPTIONS = "__filterCatchExceptions__"; -export declare const PIPES_METADATA = "__pipes__"; -export declare const GUARDS_METADATA = "__guards__"; -export declare const INTERCEPTORS_METADATA = "__interceptors__"; -export declare const HTTP_CODE_METADATA = "__httpCode__"; -export declare const GATEWAY_MIDDLEWARES = "__gatewayMiddlewares"; +export declare const SHARED_MODULE_METADATA = '__sharedModule__'; +export declare const GLOBAL_MODULE_METADATA = '__globalModule__'; +export declare const PATH_METADATA = 'path'; +export declare const PARAMTYPES_METADATA = 'design:paramtypes'; +export declare const SELF_DECLARED_DEPS_METADATA = 'self:paramtypes'; +export declare const METHOD_METADATA = 'method'; +export declare const ROUTE_ARGS_METADATA = '__routeArguments__'; +export declare const CUSTOM_ROUTE_AGRS_METADATA = '__customRouteArgs__'; +export declare const EXCEPTION_FILTERS_METADATA = '__exceptionFilters__'; +export declare const FILTER_CATCH_EXCEPTIONS = '__filterCatchExceptions__'; +export declare const PIPES_METADATA = '__pipes__'; +export declare const GUARDS_METADATA = '__guards__'; +export declare const INTERCEPTORS_METADATA = '__interceptors__'; +export declare const HTTP_CODE_METADATA = '__httpCode__'; +export declare const GATEWAY_MIDDLEWARES = '__gatewayMiddlewares'; diff --git a/lib/common/decorators/core/bind.decorator.d.ts b/lib/common/decorators/core/bind.decorator.d.ts index 0ef166a8ddb..972b73cfc5f 100644 --- a/lib/common/decorators/core/bind.decorator.d.ts +++ b/lib/common/decorators/core/bind.decorator.d.ts @@ -3,4 +3,6 @@ * Useful when the language doesn't provide a 'Parameter Decorators' feature * @param {} ...decorators */ -export declare function Bind(...decorators: any[]): (target: object, key: any, descriptor: any) => any; +export declare function Bind( + ...decorators: any[] +): (target: object, key: any, descriptor: any) => any; diff --git a/lib/common/decorators/core/exception-filters.decorator.d.ts b/lib/common/decorators/core/exception-filters.decorator.d.ts index 68f0c250bc1..10c89f1bbc8 100644 --- a/lib/common/decorators/core/exception-filters.decorator.d.ts +++ b/lib/common/decorators/core/exception-filters.decorator.d.ts @@ -10,4 +10,6 @@ import { ExceptionFilter } from '../../index'; * * @param {ExceptionFilter[]} ...filters (instances) */ -export declare const UseFilters: (...filters: ExceptionFilter[]) => (target: object, key?: any, descriptor?: any) => any; +export declare const UseFilters: ( + ...filters: ExceptionFilter[] +) => (target: object, key?: any, descriptor?: any) => any; diff --git a/lib/common/decorators/core/reflect-metadata.decorator.d.ts b/lib/common/decorators/core/reflect-metadata.decorator.d.ts index bd43ca76128..6e4cc8f9b4f 100644 --- a/lib/common/decorators/core/reflect-metadata.decorator.d.ts +++ b/lib/common/decorators/core/reflect-metadata.decorator.d.ts @@ -2,4 +2,7 @@ * Assigns the metadata to the class / function under specified `key`. * This metadata can be reflected using `Reflector` class. */ -export declare const ReflectMetadata: (metadataKey: any, metadataValue: any) => (target: object, key?: any, descriptor?: any) => any; +export declare const ReflectMetadata: ( + metadataKey: any, + metadataValue: any +) => (target: object, key?: any, descriptor?: any) => any; diff --git a/lib/common/decorators/core/use-guards.decorator.d.ts b/lib/common/decorators/core/use-guards.decorator.d.ts index 027fc210be4..db5b30a6165 100644 --- a/lib/common/decorators/core/use-guards.decorator.d.ts +++ b/lib/common/decorators/core/use-guards.decorator.d.ts @@ -8,4 +8,6 @@ * * @param {} ...guards (types) */ -export declare function UseGuards(...guards: any[]): (target: object, key?: any, descriptor?: any) => any; +export declare function UseGuards( + ...guards: any[] +): (target: object, key?: any, descriptor?: any) => any; diff --git a/lib/common/decorators/core/use-interceptors.decorator.d.ts b/lib/common/decorators/core/use-interceptors.decorator.d.ts index e9ced6e0de3..d0cb600249a 100644 --- a/lib/common/decorators/core/use-interceptors.decorator.d.ts +++ b/lib/common/decorators/core/use-interceptors.decorator.d.ts @@ -8,4 +8,6 @@ * * @param {} ...interceptors (types) */ -export declare function UseInterceptors(...interceptors: any[]): (target: object, key?: any, descriptor?: any) => any; +export declare function UseInterceptors( + ...interceptors: any[] +): (target: object, key?: any, descriptor?: any) => any; diff --git a/lib/common/decorators/core/use-pipes.decorator.d.ts b/lib/common/decorators/core/use-pipes.decorator.d.ts index f1d08216c45..f806c421181 100644 --- a/lib/common/decorators/core/use-pipes.decorator.d.ts +++ b/lib/common/decorators/core/use-pipes.decorator.d.ts @@ -9,4 +9,6 @@ import { PipeTransform } from '../../interfaces/index'; * * @param {PipeTransform[]} ...pipes (instances) */ -export declare function UsePipes(...pipes: PipeTransform[]): (target: object, key?: any, descriptor?: any) => any; +export declare function UsePipes( + ...pipes: PipeTransform[] +): (target: object, key?: any, descriptor?: any) => any; diff --git a/lib/common/decorators/http/create-route-param-metadata.decorator.d.ts b/lib/common/decorators/http/create-route-param-metadata.decorator.d.ts index 9867bcf2776..e0a608eb34a 100644 --- a/lib/common/decorators/http/create-route-param-metadata.decorator.d.ts +++ b/lib/common/decorators/http/create-route-param-metadata.decorator.d.ts @@ -4,4 +4,6 @@ import { PipeTransform } from '../../index'; * Create route params custom decorator * @param factory */ -export declare function createRouteParamDecorator(factory: CustomParamFactory): (data?: any, ...pipes: PipeTransform[]) => ParameterDecorator; +export declare function createRouteParamDecorator( + factory: CustomParamFactory +): (data?: any, ...pipes: PipeTransform[]) => ParameterDecorator; diff --git a/lib/common/decorators/http/request-mapping.decorator.d.ts b/lib/common/decorators/http/request-mapping.decorator.d.ts index 988e1e34310..4577c04a722 100644 --- a/lib/common/decorators/http/request-mapping.decorator.d.ts +++ b/lib/common/decorators/http/request-mapping.decorator.d.ts @@ -1,6 +1,8 @@ import 'reflect-metadata'; import { RequestMappingMetadata } from '../../interfaces/request-mapping-metadata.interface'; -export declare const RequestMapping: (metadata?: RequestMappingMetadata) => MethodDecorator; +export declare const RequestMapping: ( + metadata?: RequestMappingMetadata +) => MethodDecorator; /** * Routes HTTP POST requests to the specified path. */ diff --git a/lib/common/decorators/http/route-params.decorator.d.ts b/lib/common/decorators/http/route-params.decorator.d.ts index 087e01390e8..128257ba8fd 100644 --- a/lib/common/decorators/http/route-params.decorator.d.ts +++ b/lib/common/decorators/http/route-params.decorator.d.ts @@ -2,10 +2,10 @@ import 'reflect-metadata'; import { PipeTransform } from '../../index'; export declare type ParamData = object | string | number; export interface RouteParamsMetadata { - [prop: number]: { - index: number; - data?: ParamData; - }; + [prop: number]: { + index: number; + data?: ParamData; + }; } export declare const Request: () => ParameterDecorator; export declare const Response: () => ParameterDecorator; @@ -14,12 +14,21 @@ export declare const Session: () => ParameterDecorator; export declare const Headers: (property?: string) => ParameterDecorator; export declare function Query(): any; export declare function Query(...pipes: PipeTransform[]): any; -export declare function Query(property: string, ...pipes: PipeTransform[]): any; +export declare function Query( + property: string, + ...pipes: PipeTransform[] +): any; export declare function Body(): any; export declare function Body(...pipes: PipeTransform[]): any; -export declare function Body(property: string, ...pipes: PipeTransform[]): any; +export declare function Body( + property: string, + ...pipes: PipeTransform[] +): any; export declare function Param(): any; export declare function Param(...pipes: PipeTransform[]): any; -export declare function Param(property: string, ...pipes: PipeTransform[]): any; +export declare function Param( + property: string, + ...pipes: PipeTransform[] +): any; export declare const Req: () => ParameterDecorator; export declare const Res: () => ParameterDecorator; diff --git a/lib/common/decorators/modules/exceptions/invalid-module-config.exception.d.ts b/lib/common/decorators/modules/exceptions/invalid-module-config.exception.d.ts index 8d2a089ebf6..0d7dfbbf98c 100644 --- a/lib/common/decorators/modules/exceptions/invalid-module-config.exception.d.ts +++ b/lib/common/decorators/modules/exceptions/invalid-module-config.exception.d.ts @@ -1,3 +1,3 @@ export declare class InvalidModuleConfigException extends Error { - constructor(property: string); + constructor(property: string); } diff --git a/lib/common/decorators/modules/module.decorator.d.ts b/lib/common/decorators/modules/module.decorator.d.ts index 259210018d7..a9bdb3982ff 100644 --- a/lib/common/decorators/modules/module.decorator.d.ts +++ b/lib/common/decorators/modules/module.decorator.d.ts @@ -8,8 +8,8 @@ import 'reflect-metadata'; * @param obj {ModuleMetadata} Module metadata */ export declare function Module(obj: { - modules?: any[]; - controllers?: any[]; - components?: any[]; - exports?: any[]; + modules?: any[]; + controllers?: any[]; + components?: any[]; + exports?: any[]; }): ClassDecorator; diff --git a/lib/common/enums/http-status.enum.d.ts b/lib/common/enums/http-status.enum.d.ts index fe4ac614a6f..f6a21965a59 100644 --- a/lib/common/enums/http-status.enum.d.ts +++ b/lib/common/enums/http-status.enum.d.ts @@ -1,45 +1,45 @@ export declare enum HttpStatus { - CONTINUE = 100, - SWITCHING_PROTOCOLS = 101, - PROCESSING = 102, - OK = 200, - CREATED = 201, - ACCEPTED = 202, - NON_AUTHORITATIVE_INFORMATION = 203, - NO_CONTENT = 204, - RESET_CONTENT = 205, - PARTIAL_CONTENT = 206, - AMBIGUOUS = 300, - MOVED_PERMANENTLY = 301, - FOUND = 302, - SEE_OTHER = 303, - NOT_MODIFIED = 304, - TEMPORARY_REDIRECT = 307, - PERMANENT_REDIRECT = 308, - BAD_REQUEST = 400, - UNAUTHORIZED = 401, - PAYMENT_REQUIRED = 402, - FORBIDDEN = 403, - NOT_FOUND = 404, - METHOD_NOT_ALLOWED = 405, - NOT_ACCEPTABLE = 406, - PROXY_AUTHENTICATION_REQUIRED = 407, - REQUEST_TIMEOUT = 408, - CONFLICT = 409, - GONE = 410, - LENGTH_REQUIRED = 411, - PRECONDITION_FAILED = 412, - PAYLOAD_TOO_LARGE = 413, - URI_TOO_LONG = 414, - UNSUPPORTED_MEDIA_TYPE = 415, - REQUESTED_RANGE_NOT_SATISFIABLE = 416, - EXPECTATION_FAILED = 417, - UNPROCESSABLE_ENTITY = 422, - TOO_MANY_REQUESTS = 429, - INTERNAL_SERVER_ERROR = 500, - NOT_IMPLEMENTED = 501, - BAD_GATEWAY = 502, - SERVICE_UNAVAILABLE = 503, - GATEWAY_TIMEOUT = 504, - HTTP_VERSION_NOT_SUPPORTED = 505, + CONTINUE = 100, + SWITCHING_PROTOCOLS = 101, + PROCESSING = 102, + OK = 200, + CREATED = 201, + ACCEPTED = 202, + NON_AUTHORITATIVE_INFORMATION = 203, + NO_CONTENT = 204, + RESET_CONTENT = 205, + PARTIAL_CONTENT = 206, + AMBIGUOUS = 300, + MOVED_PERMANENTLY = 301, + FOUND = 302, + SEE_OTHER = 303, + NOT_MODIFIED = 304, + TEMPORARY_REDIRECT = 307, + PERMANENT_REDIRECT = 308, + BAD_REQUEST = 400, + UNAUTHORIZED = 401, + PAYMENT_REQUIRED = 402, + FORBIDDEN = 403, + NOT_FOUND = 404, + METHOD_NOT_ALLOWED = 405, + NOT_ACCEPTABLE = 406, + PROXY_AUTHENTICATION_REQUIRED = 407, + REQUEST_TIMEOUT = 408, + CONFLICT = 409, + GONE = 410, + LENGTH_REQUIRED = 411, + PRECONDITION_FAILED = 412, + PAYLOAD_TOO_LARGE = 413, + URI_TOO_LONG = 414, + UNSUPPORTED_MEDIA_TYPE = 415, + REQUESTED_RANGE_NOT_SATISFIABLE = 416, + EXPECTATION_FAILED = 417, + UNPROCESSABLE_ENTITY = 422, + TOO_MANY_REQUESTS = 429, + INTERNAL_SERVER_ERROR = 500, + NOT_IMPLEMENTED = 501, + BAD_GATEWAY = 502, + SERVICE_UNAVAILABLE = 503, + GATEWAY_TIMEOUT = 504, + HTTP_VERSION_NOT_SUPPORTED = 505 } diff --git a/lib/common/enums/nest-environment.enum.d.ts b/lib/common/enums/nest-environment.enum.d.ts index 8d006ea1a55..9d4f071fc24 100644 --- a/lib/common/enums/nest-environment.enum.d.ts +++ b/lib/common/enums/nest-environment.enum.d.ts @@ -1,4 +1,4 @@ export declare enum NestEnvironment { - RUN = 0, - TEST = 1, + RUN = 0, + TEST = 1 } diff --git a/lib/common/enums/request-method.enum.d.ts b/lib/common/enums/request-method.enum.d.ts index 476c9cb3f0a..df4b2e0cebe 100644 --- a/lib/common/enums/request-method.enum.d.ts +++ b/lib/common/enums/request-method.enum.d.ts @@ -1,10 +1,10 @@ export declare enum RequestMethod { - GET = 0, - POST = 1, - PUT = 2, - DELETE = 3, - PATCH = 4, - ALL = 5, - OPTIONS = 6, - HEAD = 7, + GET = 0, + POST = 1, + PUT = 2, + DELETE = 3, + PATCH = 4, + ALL = 5, + OPTIONS = 6, + HEAD = 7 } diff --git a/lib/common/enums/route-paramtypes.enum.d.ts b/lib/common/enums/route-paramtypes.enum.d.ts index d5451e82953..b729b48bc61 100644 --- a/lib/common/enums/route-paramtypes.enum.d.ts +++ b/lib/common/enums/route-paramtypes.enum.d.ts @@ -1,10 +1,10 @@ export declare enum RouteParamtypes { - REQUEST = 0, - RESPONSE = 1, - NEXT = 2, - BODY = 3, - QUERY = 4, - PARAM = 5, - HEADERS = 6, - SESSION = 7, + REQUEST = 0, + RESPONSE = 1, + NEXT = 2, + BODY = 3, + QUERY = 4, + PARAM = 5, + HEADERS = 6, + SESSION = 7 } diff --git a/lib/common/enums/transport.enum.d.ts b/lib/common/enums/transport.enum.d.ts index 5f116ab7c12..9de93a8b408 100644 --- a/lib/common/enums/transport.enum.d.ts +++ b/lib/common/enums/transport.enum.d.ts @@ -1,4 +1,4 @@ export declare enum Transport { - TCP = 0, - REDIS = 1, + TCP = 0, + REDIS = 1 } diff --git a/lib/common/exceptions/bad-gateway.exception.d.ts b/lib/common/exceptions/bad-gateway.exception.d.ts index 9acc902803a..70ff89f17f2 100644 --- a/lib/common/exceptions/bad-gateway.exception.d.ts +++ b/lib/common/exceptions/bad-gateway.exception.d.ts @@ -1,4 +1,4 @@ import { HttpException } from './http.exception'; export declare class BadGatewayException extends HttpException { - constructor(message?: string | object | any, error?: string); + constructor(message?: string | object | any, error?: string); } diff --git a/lib/common/exceptions/bad-request.exception.d.ts b/lib/common/exceptions/bad-request.exception.d.ts index 0359c2836c4..4170e99270b 100644 --- a/lib/common/exceptions/bad-request.exception.d.ts +++ b/lib/common/exceptions/bad-request.exception.d.ts @@ -1,4 +1,4 @@ import { HttpException } from './http.exception'; export declare class BadRequestException extends HttpException { - constructor(message?: string | object | any, error?: string); + constructor(message?: string | object | any, error?: string); } diff --git a/lib/common/exceptions/conflict.exception.d.ts b/lib/common/exceptions/conflict.exception.d.ts index c9cf4bc6adc..33028a97345 100644 --- a/lib/common/exceptions/conflict.exception.d.ts +++ b/lib/common/exceptions/conflict.exception.d.ts @@ -1,4 +1,4 @@ import { HttpException } from './http.exception'; export declare class ConflictException extends HttpException { - constructor(message?: string | object | any, error?: string); + constructor(message?: string | object | any, error?: string); } diff --git a/lib/common/exceptions/forbidden.exception.d.ts b/lib/common/exceptions/forbidden.exception.d.ts index 88f6b75e958..900c1f7e7af 100644 --- a/lib/common/exceptions/forbidden.exception.d.ts +++ b/lib/common/exceptions/forbidden.exception.d.ts @@ -1,4 +1,4 @@ import { HttpException } from './http.exception'; export declare class ForbiddenException extends HttpException { - constructor(message?: string | object | any, error?: string); + constructor(message?: string | object | any, error?: string); } diff --git a/lib/common/exceptions/gateway-timeout.exception.d.ts b/lib/common/exceptions/gateway-timeout.exception.d.ts index 43bf13db9d3..876d6964830 100644 --- a/lib/common/exceptions/gateway-timeout.exception.d.ts +++ b/lib/common/exceptions/gateway-timeout.exception.d.ts @@ -1,4 +1,4 @@ import { HttpException } from './http.exception'; export declare class GatewayTimeoutException extends HttpException { - constructor(message?: string | object | any, error?: string); + constructor(message?: string | object | any, error?: string); } diff --git a/lib/common/exceptions/gone.exception.d.ts b/lib/common/exceptions/gone.exception.d.ts index bf163313a92..1b00919feba 100644 --- a/lib/common/exceptions/gone.exception.d.ts +++ b/lib/common/exceptions/gone.exception.d.ts @@ -1,4 +1,4 @@ import { HttpException } from './http.exception'; export declare class GoneException extends HttpException { - constructor(message?: string | object | any, error?: string); + constructor(message?: string | object | any, error?: string); } diff --git a/lib/common/exceptions/http.exception.d.ts b/lib/common/exceptions/http.exception.d.ts index 38b764b895b..15d865c63bf 100644 --- a/lib/common/exceptions/http.exception.d.ts +++ b/lib/common/exceptions/http.exception.d.ts @@ -1,22 +1,22 @@ export declare class HttpException { - private readonly response; - private readonly status; - private readonly message; - /** - * The base Nest Application exception, which is handled by the default Exceptions Handler. - * If you throw an exception from your HTTP route handlers, Nest will map them to the appropriate HTTP response and send to the client. - * - * When `response` is an object: - * - object will be stringified and returned to the user as a JSON response, - * - * When `response` is a string: - * - Nest will create a response with two properties: - * ``` - * message: response, - * statusCode: X - * ``` - */ - constructor(response: string | object, status: number); - getResponse(): string | object; - getStatus(): number; + private readonly response; + private readonly status; + private readonly message; + /** + * The base Nest Application exception, which is handled by the default Exceptions Handler. + * If you throw an exception from your HTTP route handlers, Nest will map them to the appropriate HTTP response and send to the client. + * + * When `response` is an object: + * - object will be stringified and returned to the user as a JSON response, + * + * When `response` is a string: + * - Nest will create a response with two properties: + * ``` + * message: response, + * statusCode: X + * ``` + */ + constructor(response: string | object, status: number); + getResponse(): string | object; + getStatus(): number; } diff --git a/lib/common/exceptions/internal-server-error.exception.d.ts b/lib/common/exceptions/internal-server-error.exception.d.ts index af854728daf..6ea1c207df5 100644 --- a/lib/common/exceptions/internal-server-error.exception.d.ts +++ b/lib/common/exceptions/internal-server-error.exception.d.ts @@ -1,4 +1,4 @@ import { HttpException } from './http.exception'; export declare class InternalServerErrorException extends HttpException { - constructor(message?: string | object | any, error?: string); + constructor(message?: string | object | any, error?: string); } diff --git a/lib/common/exceptions/invalid-module-config.exception.d.ts b/lib/common/exceptions/invalid-module-config.exception.d.ts index 8d2a089ebf6..0d7dfbbf98c 100644 --- a/lib/common/exceptions/invalid-module-config.exception.d.ts +++ b/lib/common/exceptions/invalid-module-config.exception.d.ts @@ -1,3 +1,3 @@ export declare class InvalidModuleConfigException extends Error { - constructor(property: string); + constructor(property: string); } diff --git a/lib/common/exceptions/method-not-allowed.exception.d.ts b/lib/common/exceptions/method-not-allowed.exception.d.ts index b53c4e3b7e5..3d9b3b78f0e 100644 --- a/lib/common/exceptions/method-not-allowed.exception.d.ts +++ b/lib/common/exceptions/method-not-allowed.exception.d.ts @@ -1,4 +1,4 @@ import { HttpException } from './http.exception'; export declare class MethodNotAllowedException extends HttpException { - constructor(message?: string | object | any, error?: string); + constructor(message?: string | object | any, error?: string); } diff --git a/lib/common/exceptions/not-acceptable.exception.d.ts b/lib/common/exceptions/not-acceptable.exception.d.ts index aedd756ea5c..4921c15e0b4 100644 --- a/lib/common/exceptions/not-acceptable.exception.d.ts +++ b/lib/common/exceptions/not-acceptable.exception.d.ts @@ -1,4 +1,4 @@ import { HttpException } from './http.exception'; export declare class NotAcceptableException extends HttpException { - constructor(message?: string | object | any, error?: string); + constructor(message?: string | object | any, error?: string); } diff --git a/lib/common/exceptions/not-found.exception.d.ts b/lib/common/exceptions/not-found.exception.d.ts index 45847ad6911..84ddc8e47fc 100644 --- a/lib/common/exceptions/not-found.exception.d.ts +++ b/lib/common/exceptions/not-found.exception.d.ts @@ -1,4 +1,4 @@ import { HttpException } from './http.exception'; export declare class NotFoundException extends HttpException { - constructor(message?: string | object | any, error?: string); + constructor(message?: string | object | any, error?: string); } diff --git a/lib/common/exceptions/not-implemented.exception.d.ts b/lib/common/exceptions/not-implemented.exception.d.ts index 8b1d49255b4..0d0c1f5e1b4 100644 --- a/lib/common/exceptions/not-implemented.exception.d.ts +++ b/lib/common/exceptions/not-implemented.exception.d.ts @@ -1,4 +1,4 @@ import { HttpException } from './http.exception'; export declare class NotImplementedException extends HttpException { - constructor(message?: string | object | any, error?: string); + constructor(message?: string | object | any, error?: string); } diff --git a/lib/common/exceptions/payload-too-large.exception.d.ts b/lib/common/exceptions/payload-too-large.exception.d.ts index 050c6776743..808b8d7e179 100644 --- a/lib/common/exceptions/payload-too-large.exception.d.ts +++ b/lib/common/exceptions/payload-too-large.exception.d.ts @@ -1,4 +1,4 @@ import { HttpException } from './http.exception'; export declare class PayloadTooLargeException extends HttpException { - constructor(message?: string | object | any, error?: string); + constructor(message?: string | object | any, error?: string); } diff --git a/lib/common/exceptions/request-timeout.exception.d.ts b/lib/common/exceptions/request-timeout.exception.d.ts index ae1bf4f1c79..e12fca810f5 100644 --- a/lib/common/exceptions/request-timeout.exception.d.ts +++ b/lib/common/exceptions/request-timeout.exception.d.ts @@ -1,4 +1,4 @@ import { HttpException } from './http.exception'; export declare class RequestTimeoutException extends HttpException { - constructor(message?: string | object | any, error?: string); + constructor(message?: string | object | any, error?: string); } diff --git a/lib/common/exceptions/service-unavailable.exception.d.ts b/lib/common/exceptions/service-unavailable.exception.d.ts index 43cae5f5a12..eef882d789a 100644 --- a/lib/common/exceptions/service-unavailable.exception.d.ts +++ b/lib/common/exceptions/service-unavailable.exception.d.ts @@ -1,4 +1,4 @@ import { HttpException } from './http.exception'; export declare class ServiceUnavailableException extends HttpException { - constructor(message?: string | object | any, error?: string); + constructor(message?: string | object | any, error?: string); } diff --git a/lib/common/exceptions/unauthorized.exception.d.ts b/lib/common/exceptions/unauthorized.exception.d.ts index 798da7f425b..a70bef07e4e 100644 --- a/lib/common/exceptions/unauthorized.exception.d.ts +++ b/lib/common/exceptions/unauthorized.exception.d.ts @@ -1,4 +1,4 @@ import { HttpException } from './http.exception'; export declare class UnauthorizedException extends HttpException { - constructor(message?: string | object | any, error?: string); + constructor(message?: string | object | any, error?: string); } diff --git a/lib/common/exceptions/unprocessable-entity.exception.d.ts b/lib/common/exceptions/unprocessable-entity.exception.d.ts index cf1a7d530c3..a5fd76711cb 100644 --- a/lib/common/exceptions/unprocessable-entity.exception.d.ts +++ b/lib/common/exceptions/unprocessable-entity.exception.d.ts @@ -1,4 +1,4 @@ import { HttpException } from './http.exception'; export declare class UnprocessableEntityException extends HttpException { - constructor(message?: string | object | any, error?: string); + constructor(message?: string | object | any, error?: string); } diff --git a/lib/common/exceptions/unsupported-media-type.exception.d.ts b/lib/common/exceptions/unsupported-media-type.exception.d.ts index 5f777fdb7d9..5f0921b12be 100644 --- a/lib/common/exceptions/unsupported-media-type.exception.d.ts +++ b/lib/common/exceptions/unsupported-media-type.exception.d.ts @@ -1,4 +1,4 @@ import { HttpException } from './http.exception'; export declare class UnsupportedMediaTypeException extends HttpException { - constructor(message?: string | object | any, error?: string); + constructor(message?: string | object | any, error?: string); } diff --git a/lib/common/index.d.ts b/lib/common/index.d.ts index 55831c7fc19..49c72b24031 100644 --- a/lib/common/index.d.ts +++ b/lib/common/index.d.ts @@ -1,6 +1,29 @@ export * from './decorators'; export * from './enums'; -export { NestModule, INestApplication, INestMicroservice, MiddlewareConfigProxy, MiddlewareConfiguration, NestMiddleware, ExpressMiddleware, MiddlewaresConsumer, OnModuleInit, ExceptionFilter, WebSocketAdapter, PipeTransform, Paramtype, ArgumentMetadata, OnModuleDestroy, ExecutionContext, CanActivate, RpcExceptionFilter, WsExceptionFilter, NestInterceptor, DynamicModule, INestApplicationContext } from './interfaces'; +export { + NestModule, + INestApplication, + INestMicroservice, + MiddlewareConfigProxy, + MiddlewareConfiguration, + NestMiddleware, + ExpressMiddleware, + MiddlewaresConsumer, + OnModuleInit, + ExceptionFilter, + WebSocketAdapter, + PipeTransform, + Paramtype, + ArgumentMetadata, + OnModuleDestroy, + ExecutionContext, + CanActivate, + RpcExceptionFilter, + WsExceptionFilter, + NestInterceptor, + DynamicModule, + INestApplicationContext +} from './interfaces'; export * from './services/logger.service'; export * from './pipes'; export * from './utils'; diff --git a/lib/common/interfaces/can-activate.interface.d.ts b/lib/common/interfaces/can-activate.interface.d.ts index bf4497a0ff3..d8b29495e5f 100644 --- a/lib/common/interfaces/can-activate.interface.d.ts +++ b/lib/common/interfaces/can-activate.interface.d.ts @@ -1,5 +1,8 @@ import { Observable } from 'rxjs/Observable'; import { ExecutionContext } from './execution-context.interface'; export interface CanActivate { - canActivate(request: any, context: ExecutionContext): boolean | Promise | Observable; + canActivate( + request: any, + context: ExecutionContext + ): boolean | Promise | Observable; } diff --git a/lib/common/interfaces/configuration-provider.interface.d.ts b/lib/common/interfaces/configuration-provider.interface.d.ts index effec1ee21a..8b429118451 100644 --- a/lib/common/interfaces/configuration-provider.interface.d.ts +++ b/lib/common/interfaces/configuration-provider.interface.d.ts @@ -1,6 +1,6 @@ import { NestInterceptor } from './nest-interceptor.interface'; import { CanActivate } from './can-activate.interface'; export interface ConfigurationProvider { - getGlobalInterceptors(): NestInterceptor[]; - getGlobalGuards(): CanActivate[]; + getGlobalInterceptors(): NestInterceptor[]; + getGlobalGuards(): CanActivate[]; } diff --git a/lib/common/interfaces/controllers/controller-metadata.interface.d.ts b/lib/common/interfaces/controllers/controller-metadata.interface.d.ts index b816bf9aafb..593c4054e95 100644 --- a/lib/common/interfaces/controllers/controller-metadata.interface.d.ts +++ b/lib/common/interfaces/controllers/controller-metadata.interface.d.ts @@ -1,3 +1,3 @@ export interface ControllerMetadata { - path?: string; + path?: string; } diff --git a/lib/common/interfaces/controllers/controller.interface.d.ts b/lib/common/interfaces/controllers/controller.interface.d.ts index 9089f280240..30fb9c54b43 100644 --- a/lib/common/interfaces/controllers/controller.interface.d.ts +++ b/lib/common/interfaces/controllers/controller.interface.d.ts @@ -1,2 +1 @@ -export interface Controller { -} +export interface Controller {} diff --git a/lib/common/interfaces/exceptions/exception-filter-metadata.interface.d.ts b/lib/common/interfaces/exceptions/exception-filter-metadata.interface.d.ts index 664df291cae..9fdc4997882 100644 --- a/lib/common/interfaces/exceptions/exception-filter-metadata.interface.d.ts +++ b/lib/common/interfaces/exceptions/exception-filter-metadata.interface.d.ts @@ -1,6 +1,6 @@ import { ExceptionFilter } from './exception-filter.interface'; import { Metatype } from '../metatype.interface'; export interface ExceptionFilterMetadata { - func: ExceptionFilter['catch']; - exceptionMetatypes: Metatype[]; + func: ExceptionFilter['catch']; + exceptionMetatypes: Metatype[]; } diff --git a/lib/common/interfaces/exceptions/exception-filter.interface.d.ts b/lib/common/interfaces/exceptions/exception-filter.interface.d.ts index 1c3df01069c..c7dc768c2a3 100644 --- a/lib/common/interfaces/exceptions/exception-filter.interface.d.ts +++ b/lib/common/interfaces/exceptions/exception-filter.interface.d.ts @@ -1,3 +1,3 @@ export interface ExceptionFilter { - catch(exception: any, response: any): any; + catch(exception: any, response: any): any; } diff --git a/lib/common/interfaces/exceptions/rpc-exception-filter-metadata.interface.d.ts b/lib/common/interfaces/exceptions/rpc-exception-filter-metadata.interface.d.ts index 85679224e67..fd9c0a28464 100644 --- a/lib/common/interfaces/exceptions/rpc-exception-filter-metadata.interface.d.ts +++ b/lib/common/interfaces/exceptions/rpc-exception-filter-metadata.interface.d.ts @@ -1,6 +1,6 @@ import { RpcExceptionFilter } from './rpc-exception-filter.interface'; import { Metatype } from '../metatype.interface'; export interface RpcExceptionFilterMetadata { - func: RpcExceptionFilter['catch']; - exceptionMetatypes: Metatype[]; + func: RpcExceptionFilter['catch']; + exceptionMetatypes: Metatype[]; } diff --git a/lib/common/interfaces/exceptions/rpc-exception-filter.interface.d.ts b/lib/common/interfaces/exceptions/rpc-exception-filter.interface.d.ts index e73474c1012..428ba34a1a5 100644 --- a/lib/common/interfaces/exceptions/rpc-exception-filter.interface.d.ts +++ b/lib/common/interfaces/exceptions/rpc-exception-filter.interface.d.ts @@ -1,4 +1,4 @@ import { Observable } from 'rxjs/Observable'; export interface RpcExceptionFilter { - catch(exception: any): Observable; + catch(exception: any): Observable; } diff --git a/lib/common/interfaces/exceptions/ws-exception-filter.interface.d.ts b/lib/common/interfaces/exceptions/ws-exception-filter.interface.d.ts index 1d1994d342b..75aecdf9f03 100644 --- a/lib/common/interfaces/exceptions/ws-exception-filter.interface.d.ts +++ b/lib/common/interfaces/exceptions/ws-exception-filter.interface.d.ts @@ -1,3 +1,3 @@ export interface WsExceptionFilter { - catch(exception: any, client: any): any; + catch(exception: any, client: any): any; } diff --git a/lib/common/interfaces/execution-context.interface.d.ts b/lib/common/interfaces/execution-context.interface.d.ts index c174b8d0861..2084f61e189 100644 --- a/lib/common/interfaces/execution-context.interface.d.ts +++ b/lib/common/interfaces/execution-context.interface.d.ts @@ -1,4 +1,4 @@ export interface ExecutionContext { - parent: Function; - handler: (...args) => any; + parent: Function; + handler: (...args) => any; } diff --git a/lib/common/interfaces/injectable.interface.d.ts b/lib/common/interfaces/injectable.interface.d.ts index 390800ab267..a9e2b48fa51 100644 --- a/lib/common/interfaces/injectable.interface.d.ts +++ b/lib/common/interfaces/injectable.interface.d.ts @@ -1,2 +1 @@ -export interface Injectable { -} +export interface Injectable {} diff --git a/lib/common/interfaces/metatype.interface.d.ts b/lib/common/interfaces/metatype.interface.d.ts index 957b2991608..e614c6c62af 100644 --- a/lib/common/interfaces/metatype.interface.d.ts +++ b/lib/common/interfaces/metatype.interface.d.ts @@ -1,3 +1,3 @@ export interface Metatype { - new (...args: any[]): T; + new (...args: any[]): T; } diff --git a/lib/common/interfaces/microservices/custom-transport-strategy.interface.d.ts b/lib/common/interfaces/microservices/custom-transport-strategy.interface.d.ts index b743506b902..15072dab2f7 100644 --- a/lib/common/interfaces/microservices/custom-transport-strategy.interface.d.ts +++ b/lib/common/interfaces/microservices/custom-transport-strategy.interface.d.ts @@ -1,4 +1,4 @@ export interface CustomTransportStrategy { - listen(callback: () => void): any; - close(): any; + listen(callback: () => void): any; + close(): any; } diff --git a/lib/common/interfaces/microservices/microservice-configuration.interface.d.ts b/lib/common/interfaces/microservices/microservice-configuration.interface.d.ts index 831a3208d78..fab9742a3e0 100644 --- a/lib/common/interfaces/microservices/microservice-configuration.interface.d.ts +++ b/lib/common/interfaces/microservices/microservice-configuration.interface.d.ts @@ -1,9 +1,9 @@ import { CustomTransportStrategy } from './custom-transport-strategy.interface'; import { Transport } from './../../enums/transport.enum'; export interface MicroserviceConfiguration { - transport?: Transport; - url?: string; - port?: number; - host?: string; - strategy?: CustomTransportStrategy; + transport?: Transport; + url?: string; + port?: number; + host?: string; + strategy?: CustomTransportStrategy; } diff --git a/lib/common/interfaces/middlewares/express-middleware.interface.d.ts b/lib/common/interfaces/middlewares/express-middleware.interface.d.ts index e79f9ccec25..df15c941d17 100644 --- a/lib/common/interfaces/middlewares/express-middleware.interface.d.ts +++ b/lib/common/interfaces/middlewares/express-middleware.interface.d.ts @@ -1,3 +1,3 @@ export interface ExpressMiddleware { - (req?: any, res?: any, next?: any): void; + (req?: any, res?: any, next?: any): void; } diff --git a/lib/common/interfaces/middlewares/express-midleware.interface.d.ts b/lib/common/interfaces/middlewares/express-midleware.interface.d.ts index e79f9ccec25..df15c941d17 100644 --- a/lib/common/interfaces/middlewares/express-midleware.interface.d.ts +++ b/lib/common/interfaces/middlewares/express-midleware.interface.d.ts @@ -1,3 +1,3 @@ export interface ExpressMiddleware { - (req?: any, res?: any, next?: any): void; + (req?: any, res?: any, next?: any): void; } diff --git a/lib/common/interfaces/middlewares/middleware-config-proxy.interface.d.ts b/lib/common/interfaces/middlewares/middleware-config-proxy.interface.d.ts index 71a0338caa9..9a4b0c1da3b 100644 --- a/lib/common/interfaces/middlewares/middleware-config-proxy.interface.d.ts +++ b/lib/common/interfaces/middlewares/middleware-config-proxy.interface.d.ts @@ -1,24 +1,24 @@ import { MiddlewaresConsumer } from './middlewares-consumer.interface'; export interface MiddlewareConfigProxy { - /** - * Passes custom arguments to `resolve()` method of the middleware - * - * @param {} ...data - * @returns MiddlewareConfigProxy - */ - with(...data: any[]): MiddlewareConfigProxy; - /** - * Attaches passed routes / controllers to the processed middleware(s). - * Single route can be defined as a literal object: - * ``` - * path: string; - * method: RequestMethod; - * ``` - * - * When you passed Controller class, Nest will attach middleware to every HTTP route handler inside this controller. - * - * @param {} ...routes - * @returns MiddlewaresConsumer - */ - forRoutes(...routes: any[]): MiddlewaresConsumer; + /** + * Passes custom arguments to `resolve()` method of the middleware + * + * @param {} ...data + * @returns MiddlewareConfigProxy + */ + with(...data: any[]): MiddlewareConfigProxy; + /** + * Attaches passed routes / controllers to the processed middleware(s). + * Single route can be defined as a literal object: + * ``` + * path: string; + * method: RequestMethod; + * ``` + * + * When you passed Controller class, Nest will attach middleware to every HTTP route handler inside this controller. + * + * @param {} ...routes + * @returns MiddlewaresConsumer + */ + forRoutes(...routes: any[]): MiddlewaresConsumer; } diff --git a/lib/common/interfaces/middlewares/middleware-configuration.interface.d.ts b/lib/common/interfaces/middlewares/middleware-configuration.interface.d.ts index fd0be7e0223..665f6092cfa 100644 --- a/lib/common/interfaces/middlewares/middleware-configuration.interface.d.ts +++ b/lib/common/interfaces/middlewares/middleware-configuration.interface.d.ts @@ -2,8 +2,10 @@ import { ControllerMetadata } from '../controllers/controller-metadata.interface import { Controller } from '../controllers/controller.interface'; import { RequestMethod } from '../../enums/request-method.enum'; export interface MiddlewareConfiguration { - middlewares: any; - forRoutes: (Controller | ControllerMetadata & { + middlewares: any; + forRoutes: ( + | Controller + | ControllerMetadata & { method?: RequestMethod; - })[]; + })[]; } diff --git a/lib/common/interfaces/middlewares/middlewares-consumer.interface.d.ts b/lib/common/interfaces/middlewares/middlewares-consumer.interface.d.ts index 149efde4e53..d3f3d1d4d7d 100644 --- a/lib/common/interfaces/middlewares/middlewares-consumer.interface.d.ts +++ b/lib/common/interfaces/middlewares/middlewares-consumer.interface.d.ts @@ -1,11 +1,11 @@ import { MiddlewareConfigProxy } from './middleware-config-proxy.interface'; export interface MiddlewaresConsumer { - /** - * Takes single middleware class or array of classes, - * which subsequently can be attached to the passed routes / controllers. - * - * @param {any|any[]} middlewares - * @returns MiddlewareConfigProxy - */ - apply(middlewares: any | any[]): MiddlewareConfigProxy; + /** + * Takes single middleware class or array of classes, + * which subsequently can be attached to the passed routes / controllers. + * + * @param {any|any[]} middlewares + * @returns MiddlewareConfigProxy + */ + apply(middlewares: any | any[]): MiddlewareConfigProxy; } diff --git a/lib/common/interfaces/middlewares/nest-middleware.interface.d.ts b/lib/common/interfaces/middlewares/nest-middleware.interface.d.ts index 4656c6b5ea5..2d76a9dc4a4 100644 --- a/lib/common/interfaces/middlewares/nest-middleware.interface.d.ts +++ b/lib/common/interfaces/middlewares/nest-middleware.interface.d.ts @@ -1,5 +1,10 @@ import { ExpressMiddleware } from './express-middleware.interface'; export declare type AsyncExpressMiddleware = Promise; export interface NestMiddleware { - resolve(...args: any[]): ExpressMiddleware | AsyncExpressMiddleware | Promise; + resolve( + ...args: any[] + ): + | ExpressMiddleware + | AsyncExpressMiddleware + | Promise; } diff --git a/lib/common/interfaces/modules/dynamic-module.interface.d.ts b/lib/common/interfaces/modules/dynamic-module.interface.d.ts index d8711251720..7f5b45ec0f8 100644 --- a/lib/common/interfaces/modules/dynamic-module.interface.d.ts +++ b/lib/common/interfaces/modules/dynamic-module.interface.d.ts @@ -1,4 +1,4 @@ import { ModuleMetadata } from './module-metadata.interface'; export interface DynamicModule extends ModuleMetadata { - module: any; + module: any; } diff --git a/lib/common/interfaces/modules/module-metadata.interface.d.ts b/lib/common/interfaces/modules/module-metadata.interface.d.ts index b3c8d1ae2d1..e03a625d00b 100644 --- a/lib/common/interfaces/modules/module-metadata.interface.d.ts +++ b/lib/common/interfaces/modules/module-metadata.interface.d.ts @@ -1,8 +1,8 @@ import { NestModule } from './nest-module.interface'; import { Controller } from '../controllers/controller.interface'; export interface ModuleMetadata { - modules?: NestModule[] | any[]; - components?: any[]; - controllers?: Controller[] | any[]; - exports?: any[]; + modules?: NestModule[] | any[]; + components?: any[]; + controllers?: Controller[] | any[]; + exports?: any[]; } diff --git a/lib/common/interfaces/modules/module-metatype.interface.d.ts b/lib/common/interfaces/modules/module-metatype.interface.d.ts index 4ecb8cd0333..5fb08492244 100644 --- a/lib/common/interfaces/modules/module-metatype.interface.d.ts +++ b/lib/common/interfaces/modules/module-metatype.interface.d.ts @@ -1,4 +1,3 @@ import { NestModule } from './nest-module.interface'; import { Metatype } from '../metatype.interface'; -export interface NestModuleMetatype extends Metatype { -} +export interface NestModuleMetatype extends Metatype {} diff --git a/lib/common/interfaces/modules/nest-module.interface.d.ts b/lib/common/interfaces/modules/nest-module.interface.d.ts index a18f1212b13..13c0747ab43 100644 --- a/lib/common/interfaces/modules/nest-module.interface.d.ts +++ b/lib/common/interfaces/modules/nest-module.interface.d.ts @@ -1,4 +1,4 @@ import { MiddlewaresConsumer } from '../middlewares/middlewares-consumer.interface'; export interface NestModule { - configure(consumer: MiddlewaresConsumer): MiddlewaresConsumer | void; + configure(consumer: MiddlewaresConsumer): MiddlewaresConsumer | void; } diff --git a/lib/common/interfaces/modules/on-destroy.interface.d.ts b/lib/common/interfaces/modules/on-destroy.interface.d.ts index 1ac3e2cf665..d778b2b9c42 100644 --- a/lib/common/interfaces/modules/on-destroy.interface.d.ts +++ b/lib/common/interfaces/modules/on-destroy.interface.d.ts @@ -1,3 +1,3 @@ export interface OnModuleDestroy { - onModuleDestroy(): any; + onModuleDestroy(): any; } diff --git a/lib/common/interfaces/modules/on-init.interface.d.ts b/lib/common/interfaces/modules/on-init.interface.d.ts index 2647a33334b..a59b767e974 100644 --- a/lib/common/interfaces/modules/on-init.interface.d.ts +++ b/lib/common/interfaces/modules/on-init.interface.d.ts @@ -1,3 +1,3 @@ export interface OnModuleInit { - onModuleInit(): any; + onModuleInit(): any; } diff --git a/lib/common/interfaces/nest-application-context.interface.d.ts b/lib/common/interfaces/nest-application-context.interface.d.ts index b4700c08b2a..39b0be97698 100644 --- a/lib/common/interfaces/nest-application-context.interface.d.ts +++ b/lib/common/interfaces/nest-application-context.interface.d.ts @@ -1,13 +1,13 @@ import { Metatype } from './metatype.interface'; export interface INestApplicationContext { - /** - * Allows you to navigate through the modules tree, for example, to pull out a specific instance from the selected module. - * @returns INestApplicationContext - */ - select(module: Metatype): INestApplicationContext; - /** - * Makes possible to retrieve the instance of the component or controller available inside the processed module. - * @returns T - */ - get(metatypeOrToken: Metatype | string): T; + /** + * Allows you to navigate through the modules tree, for example, to pull out a specific instance from the selected module. + * @returns INestApplicationContext + */ + select(module: Metatype): INestApplicationContext; + /** + * Makes possible to retrieve the instance of the component or controller available inside the processed module. + * @returns T + */ + get(metatypeOrToken: Metatype | string): T; } diff --git a/lib/common/interfaces/nest-application.interface.d.ts b/lib/common/interfaces/nest-application.interface.d.ts index 36b558911af..d1d679fd6c3 100644 --- a/lib/common/interfaces/nest-application.interface.d.ts +++ b/lib/common/interfaces/nest-application.interface.d.ts @@ -4,119 +4,119 @@ import { CanActivate } from './can-activate.interface'; import { NestInterceptor } from './nest-interceptor.interface'; import { INestApplicationContext } from './nest-application-context.interface'; export interface INestApplication extends INestApplicationContext { - /** - * Initializes application. It is not necessary to call this method directly. - * - * @returns Promise - */ - init(): Promise; - /** - * The wrapper function around native `express.use()` method. - * Example `app.use(cors())` - * - * @returns void - */ - use(...args: any[]): void; - /** - * The wrapper function around native `express.set()` method. - * Example `app.set('trust proxy', 'loopback')` - * - * @returns void - */ - set(...args: any[]): void; - /** - * Starts the application. - * - * @param {number} port - * @param {string} hostname - * @param {Function} callback Optional callback - * @returns Promise - */ - listen(port: number, callback?: () => void): Promise; - listen(port: number, hostname: string, callback?: () => void): Promise; - /** - * Starts the application and can be awaited. - * - * @param {number} port - * @param {string} hostname (optional) - * @returns Promise - */ - listenAsync(port: number, hostname?: string): Promise; - /** - * Setups the prefix for the every HTTP route path - * - * @param {string} prefix The prefix for the every HTTP route path (for example `/v1/api`) - * @returns void - */ - setGlobalPrefix(prefix: string): void; - /** - * Setup Web Sockets Adapter, which will be used inside Gateways. - * Use, when you want to override default `socket.io` library. - * - * @param {WebSocketAdapter} adapter - * @returns void - */ - useWebSocketAdapter(adapter: WebSocketAdapter): void; - /** - * Connects microservice to the NestApplication instance. It transforms application to the hybrid instance. - * - * @param {MicroserviceConfiguration} config Microservice configuration objet - * @returns INestMicroservice - */ - connectMicroservice(config: any): INestMicroservice; - /** - * Returns array of the connected microservices to the NestApplication. - * - * @returns INestMicroservice[] - */ - getMicroservices(): INestMicroservice[]; - /** - * Returns underlying native HTTP server. - * - * @returns http.Server - */ - getHttpServer(): any; - /** - * Starts all the connected microservices asynchronously - * - * @param {Function} callback Optional callback function - * @returns void - */ - startAllMicroservices(callback?: () => void): void; - /** - * Starts all the connected microservices and can be awaited - * - * @returns Promise - */ - startAllMicroservicesAsync(): Promise; - /** - * Setups exception filters as a global filters (will be used within every HTTP route handler) - * - * @param {ExceptionFilter[]} ...filters - */ - useGlobalFilters(...filters: ExceptionFilter[]): any; - /** - * Setups pipes as a global pipes (will be used within every HTTP route handler) - * - * @param {PipeTransform[]} ...pipes - */ - useGlobalPipes(...pipes: PipeTransform[]): any; - /** - * Setups interceptors as a global interceptors (will be used within every HTTP route handler) - * - * @param {NestInterceptor[]} ...interceptors - */ - useGlobalInterceptors(...interceptors: NestInterceptor[]): any; - /** - * Setups guards as a global guards (will be used within every HTTP route handler) - * - * @param {CanActivate[]} ...guards - */ - useGlobalGuards(...guards: CanActivate[]): any; - /** - * Terminates the application (both NestApplication, Web Socket Gateways and every connected microservice) - * - * @returns void - */ - close(): void; + /** + * Initializes application. It is not necessary to call this method directly. + * + * @returns Promise + */ + init(): Promise; + /** + * The wrapper function around native `express.use()` method. + * Example `app.use(cors())` + * + * @returns void + */ + use(...args: any[]): void; + /** + * The wrapper function around native `express.set()` method. + * Example `app.set('trust proxy', 'loopback')` + * + * @returns void + */ + set(...args: any[]): void; + /** + * Starts the application. + * + * @param {number} port + * @param {string} hostname + * @param {Function} callback Optional callback + * @returns Promise + */ + listen(port: number, callback?: () => void): Promise; + listen(port: number, hostname: string, callback?: () => void): Promise; + /** + * Starts the application and can be awaited. + * + * @param {number} port + * @param {string} hostname (optional) + * @returns Promise + */ + listenAsync(port: number, hostname?: string): Promise; + /** + * Setups the prefix for the every HTTP route path + * + * @param {string} prefix The prefix for the every HTTP route path (for example `/v1/api`) + * @returns void + */ + setGlobalPrefix(prefix: string): void; + /** + * Setup Web Sockets Adapter, which will be used inside Gateways. + * Use, when you want to override default `socket.io` library. + * + * @param {WebSocketAdapter} adapter + * @returns void + */ + useWebSocketAdapter(adapter: WebSocketAdapter): void; + /** + * Connects microservice to the NestApplication instance. It transforms application to the hybrid instance. + * + * @param {MicroserviceConfiguration} config Microservice configuration objet + * @returns INestMicroservice + */ + connectMicroservice(config: any): INestMicroservice; + /** + * Returns array of the connected microservices to the NestApplication. + * + * @returns INestMicroservice[] + */ + getMicroservices(): INestMicroservice[]; + /** + * Returns underlying native HTTP server. + * + * @returns http.Server + */ + getHttpServer(): any; + /** + * Starts all the connected microservices asynchronously + * + * @param {Function} callback Optional callback function + * @returns void + */ + startAllMicroservices(callback?: () => void): void; + /** + * Starts all the connected microservices and can be awaited + * + * @returns Promise + */ + startAllMicroservicesAsync(): Promise; + /** + * Setups exception filters as a global filters (will be used within every HTTP route handler) + * + * @param {ExceptionFilter[]} ...filters + */ + useGlobalFilters(...filters: ExceptionFilter[]): any; + /** + * Setups pipes as a global pipes (will be used within every HTTP route handler) + * + * @param {PipeTransform[]} ...pipes + */ + useGlobalPipes(...pipes: PipeTransform[]): any; + /** + * Setups interceptors as a global interceptors (will be used within every HTTP route handler) + * + * @param {NestInterceptor[]} ...interceptors + */ + useGlobalInterceptors(...interceptors: NestInterceptor[]): any; + /** + * Setups guards as a global guards (will be used within every HTTP route handler) + * + * @param {CanActivate[]} ...guards + */ + useGlobalGuards(...guards: CanActivate[]): any; + /** + * Terminates the application (both NestApplication, Web Socket Gateways and every connected microservice) + * + * @returns void + */ + close(): void; } diff --git a/lib/common/interfaces/nest-interceptor.interface.d.ts b/lib/common/interfaces/nest-interceptor.interface.d.ts index dc3cc95f815..47547b7bcef 100644 --- a/lib/common/interfaces/nest-interceptor.interface.d.ts +++ b/lib/common/interfaces/nest-interceptor.interface.d.ts @@ -1,5 +1,9 @@ import { Observable } from 'rxjs/Observable'; import { ExecutionContext } from './execution-context.interface'; export interface NestInterceptor { - intercept(dataOrRequest: any, context: ExecutionContext, stream$: Observable): Observable | Promise>; + intercept( + dataOrRequest: any, + context: ExecutionContext, + stream$: Observable + ): Observable | Promise>; } diff --git a/lib/common/interfaces/nest-microservice.interface.d.ts b/lib/common/interfaces/nest-microservice.interface.d.ts index e9cf7001905..63a73662bf2 100644 --- a/lib/common/interfaces/nest-microservice.interface.d.ts +++ b/lib/common/interfaces/nest-microservice.interface.d.ts @@ -4,49 +4,49 @@ import { PipeTransform } from './pipe-transform.interface'; import { NestInterceptor } from './nest-interceptor.interface'; import { CanActivate } from './can-activate.interface'; export interface INestMicroservice { - /** - * Starts the microservice. - * - * @param {Function} callback Callback called after instant - * @returns Promise - */ - listen(callback: () => void): any; - /** - * Setup Web Sockets Adapter, which will be used inside Gateways. - * Use, when you want to override default `socket.io` library. - * - * @param {WebSocketAdapter} adapter - * @returns void - */ - useWebSocketAdapter(adapter: WebSocketAdapter): void; - /** - * Setups exception filters as a global filters (will be used within every message pattern handler) - * - * @param {ExceptionFilter[]} ...filters - */ - useGlobalFilters(...filters: ExceptionFilter[]): any; - /** - * Setups pipes as a global pipes (will be used within every message pattern handler) - * - * @param {PipeTransform[]} ...pipes - */ - useGlobalPipes(...pipes: PipeTransform[]): any; - /** - * Setups interceptors as a global interceptors (will be used within every message pattern handler) - * - * @param {NestInterceptor[]} ...interceptors - */ - useGlobalInterceptors(...interceptors: NestInterceptor[]): any; - /** - * Setups guards as a global guards (will be used within every message pattern handler) - * - * @param {CanActivate[]} ...guards - */ - useGlobalGuards(...guards: CanActivate[]): any; - /** - * Terminates the application (both NestMicroservice and every Web Socket Gateway) - * - * @returns void - */ - close(): void; + /** + * Starts the microservice. + * + * @param {Function} callback Callback called after instant + * @returns Promise + */ + listen(callback: () => void): any; + /** + * Setup Web Sockets Adapter, which will be used inside Gateways. + * Use, when you want to override default `socket.io` library. + * + * @param {WebSocketAdapter} adapter + * @returns void + */ + useWebSocketAdapter(adapter: WebSocketAdapter): void; + /** + * Setups exception filters as a global filters (will be used within every message pattern handler) + * + * @param {ExceptionFilter[]} ...filters + */ + useGlobalFilters(...filters: ExceptionFilter[]): any; + /** + * Setups pipes as a global pipes (will be used within every message pattern handler) + * + * @param {PipeTransform[]} ...pipes + */ + useGlobalPipes(...pipes: PipeTransform[]): any; + /** + * Setups interceptors as a global interceptors (will be used within every message pattern handler) + * + * @param {NestInterceptor[]} ...interceptors + */ + useGlobalInterceptors(...interceptors: NestInterceptor[]): any; + /** + * Setups guards as a global guards (will be used within every message pattern handler) + * + * @param {CanActivate[]} ...guards + */ + useGlobalGuards(...guards: CanActivate[]): any; + /** + * Terminates the application (both NestMicroservice and every Web Socket Gateway) + * + * @returns void + */ + close(): void; } diff --git a/lib/common/interfaces/pipe-transform.interface.d.ts b/lib/common/interfaces/pipe-transform.interface.d.ts index dcd5d1141f6..f6ef78a1060 100644 --- a/lib/common/interfaces/pipe-transform.interface.d.ts +++ b/lib/common/interfaces/pipe-transform.interface.d.ts @@ -1,10 +1,13 @@ import { Paramtype } from './paramtype.interface'; -export declare type Transform = (value: T, metadata: ArgumentMetadata) => any; +export declare type Transform = ( + value: T, + metadata: ArgumentMetadata +) => any; export interface ArgumentMetadata { - type: Paramtype; - metatype?: new (...args) => any; - data?: string; + type: Paramtype; + metatype?: new (...args) => any; + data?: string; } export interface PipeTransform { - transform(value: T, metadata: ArgumentMetadata): any; + transform(value: T, metadata: ArgumentMetadata): any; } diff --git a/lib/common/interfaces/request-mapping-metadata.interface.d.ts b/lib/common/interfaces/request-mapping-metadata.interface.d.ts index 36a1950eaf8..ebf0ef32111 100644 --- a/lib/common/interfaces/request-mapping-metadata.interface.d.ts +++ b/lib/common/interfaces/request-mapping-metadata.interface.d.ts @@ -1,5 +1,5 @@ import { RequestMethod } from '../enums/request-method.enum'; export interface RequestMappingMetadata { - path?: string; - method?: RequestMethod; + path?: string; + method?: RequestMethod; } diff --git a/lib/common/interfaces/web-socket-adapter.interface.d.ts b/lib/common/interfaces/web-socket-adapter.interface.d.ts index a970782c776..61532ce1da3 100644 --- a/lib/common/interfaces/web-socket-adapter.interface.d.ts +++ b/lib/common/interfaces/web-socket-adapter.interface.d.ts @@ -1,12 +1,16 @@ import { Observable } from 'rxjs/Observable'; export interface WebSocketAdapter { - create(port: number): any; - createWithNamespace?(port: number, namespace: string, server?: any): any; - bindClientConnect(server: any, callback: (...args) => void): any; - bindClientDisconnect?(client: any, callback: (...args) => void): any; - bindMessageHandlers(client: any, handler: { - message: string; - callback: (...args) => Observable | Promise | void; - }[], process: (data) => Observable): any; - bindMiddleware?(server: any, middleware: (socket, next) => void): any; + create(port: number): any; + createWithNamespace?(port: number, namespace: string, server?: any): any; + bindClientConnect(server: any, callback: (...args) => void): any; + bindClientDisconnect?(client: any, callback: (...args) => void): any; + bindMessageHandlers( + client: any, + handler: { + message: string; + callback: (...args) => Observable | Promise | void; + }[], + process: (data) => Observable + ): any; + bindMiddleware?(server: any, middleware: (socket, next) => void): any; } diff --git a/lib/common/pipes/parse-int.pipe.d.ts b/lib/common/pipes/parse-int.pipe.d.ts index c6bb2904048..60c20269f42 100644 --- a/lib/common/pipes/parse-int.pipe.d.ts +++ b/lib/common/pipes/parse-int.pipe.d.ts @@ -1,5 +1,5 @@ import { PipeTransform } from '../interfaces/pipe-transform.interface'; import { ArgumentMetadata } from '../index'; export declare class ParseIntPipe implements PipeTransform { - transform(value: string, metadata: ArgumentMetadata): Promise; + transform(value: string, metadata: ArgumentMetadata): Promise; } diff --git a/lib/common/pipes/validation.pipe.d.ts b/lib/common/pipes/validation.pipe.d.ts index 813b7b00c57..ba88b4d96bb 100644 --- a/lib/common/pipes/validation.pipe.d.ts +++ b/lib/common/pipes/validation.pipe.d.ts @@ -1,6 +1,6 @@ import { PipeTransform } from '../interfaces/pipe-transform.interface'; import { ArgumentMetadata } from '../index'; export declare class ValidationPipe implements PipeTransform { - transform(value: any, metadata: ArgumentMetadata): Promise; - private toValidate(metatype); + transform(value: any, metadata: ArgumentMetadata): Promise; + private toValidate(metatype); } diff --git a/lib/common/services/logger.service.d.ts b/lib/common/services/logger.service.d.ts index 41131ae9d1e..917f355849c 100644 --- a/lib/common/services/logger.service.d.ts +++ b/lib/common/services/logger.service.d.ts @@ -1,16 +1,16 @@ import { NestEnvironment } from '../enums/nest-environment.enum'; export declare class Logger { - private readonly context; - private readonly printTimestamps; - private static lastTimestamp; - private static contextEnv; - private readonly yellow; - constructor(context: string, printTimestamps?: boolean); - static setMode(mode: NestEnvironment): void; - log(message: string): void; - error(message: string, trace?: string): void; - warn(message: string): void; - private printMessage(message, color); - private printTimestamp(); - private printStackTrace(trace); + private readonly context; + private readonly printTimestamps; + private static lastTimestamp; + private static contextEnv; + private readonly yellow; + constructor(context: string, printTimestamps?: boolean); + static setMode(mode: NestEnvironment): void; + log(message: string): void; + error(message: string, trace?: string): void; + warn(message: string): void; + private printMessage(message, color); + private printTimestamp(); + private printStackTrace(trace); } diff --git a/lib/common/utils/bind-resolve-values.util.d.ts b/lib/common/utils/bind-resolve-values.util.d.ts index 0a42d3550ff..b81b906f09b 100644 --- a/lib/common/utils/bind-resolve-values.util.d.ts +++ b/lib/common/utils/bind-resolve-values.util.d.ts @@ -1,3 +1,7 @@ import { Constructor } from './merge-with-values.util'; import { NestMiddleware } from '../interfaces/middlewares/nest-middleware.interface'; -export declare const BindResolveMiddlewareValues: >(data: any[]) => (Metatype: T) => any; +export declare const BindResolveMiddlewareValues: < + T extends Constructor +>( + data: any[] +) => (Metatype: T) => any; diff --git a/lib/common/utils/decorators/bind.decorator.d.ts b/lib/common/utils/decorators/bind.decorator.d.ts index 0ef166a8ddb..972b73cfc5f 100644 --- a/lib/common/utils/decorators/bind.decorator.d.ts +++ b/lib/common/utils/decorators/bind.decorator.d.ts @@ -3,4 +3,6 @@ * Useful when the language doesn't provide a 'Parameter Decorators' feature * @param {} ...decorators */ -export declare function Bind(...decorators: any[]): (target: object, key: any, descriptor: any) => any; +export declare function Bind( + ...decorators: any[] +): (target: object, key: any, descriptor: any) => any; diff --git a/lib/common/utils/decorators/create-route-param-metadata.decorator.d.ts b/lib/common/utils/decorators/create-route-param-metadata.decorator.d.ts index 9867bcf2776..e0a608eb34a 100644 --- a/lib/common/utils/decorators/create-route-param-metadata.decorator.d.ts +++ b/lib/common/utils/decorators/create-route-param-metadata.decorator.d.ts @@ -4,4 +4,6 @@ import { PipeTransform } from '../../index'; * Create route params custom decorator * @param factory */ -export declare function createRouteParamDecorator(factory: CustomParamFactory): (data?: any, ...pipes: PipeTransform[]) => ParameterDecorator; +export declare function createRouteParamDecorator( + factory: CustomParamFactory +): (data?: any, ...pipes: PipeTransform[]) => ParameterDecorator; diff --git a/lib/common/utils/decorators/exception-filters.decorator.d.ts b/lib/common/utils/decorators/exception-filters.decorator.d.ts index 68f0c250bc1..10c89f1bbc8 100644 --- a/lib/common/utils/decorators/exception-filters.decorator.d.ts +++ b/lib/common/utils/decorators/exception-filters.decorator.d.ts @@ -10,4 +10,6 @@ import { ExceptionFilter } from '../../index'; * * @param {ExceptionFilter[]} ...filters (instances) */ -export declare const UseFilters: (...filters: ExceptionFilter[]) => (target: object, key?: any, descriptor?: any) => any; +export declare const UseFilters: ( + ...filters: ExceptionFilter[] +) => (target: object, key?: any, descriptor?: any) => any; diff --git a/lib/common/utils/decorators/exceptions/invalid-module-config.exception.d.ts b/lib/common/utils/decorators/exceptions/invalid-module-config.exception.d.ts index 8d2a089ebf6..0d7dfbbf98c 100644 --- a/lib/common/utils/decorators/exceptions/invalid-module-config.exception.d.ts +++ b/lib/common/utils/decorators/exceptions/invalid-module-config.exception.d.ts @@ -1,3 +1,3 @@ export declare class InvalidModuleConfigException extends Error { - constructor(property: string); + constructor(property: string); } diff --git a/lib/common/utils/decorators/module.decorator.d.ts b/lib/common/utils/decorators/module.decorator.d.ts index 259210018d7..a9bdb3982ff 100644 --- a/lib/common/utils/decorators/module.decorator.d.ts +++ b/lib/common/utils/decorators/module.decorator.d.ts @@ -8,8 +8,8 @@ import 'reflect-metadata'; * @param obj {ModuleMetadata} Module metadata */ export declare function Module(obj: { - modules?: any[]; - controllers?: any[]; - components?: any[]; - exports?: any[]; + modules?: any[]; + controllers?: any[]; + components?: any[]; + exports?: any[]; }): ClassDecorator; diff --git a/lib/common/utils/decorators/reflect-metadata.decorator.d.ts b/lib/common/utils/decorators/reflect-metadata.decorator.d.ts index bd43ca76128..6e4cc8f9b4f 100644 --- a/lib/common/utils/decorators/reflect-metadata.decorator.d.ts +++ b/lib/common/utils/decorators/reflect-metadata.decorator.d.ts @@ -2,4 +2,7 @@ * Assigns the metadata to the class / function under specified `key`. * This metadata can be reflected using `Reflector` class. */ -export declare const ReflectMetadata: (metadataKey: any, metadataValue: any) => (target: object, key?: any, descriptor?: any) => any; +export declare const ReflectMetadata: ( + metadataKey: any, + metadataValue: any +) => (target: object, key?: any, descriptor?: any) => any; diff --git a/lib/common/utils/decorators/request-mapping.decorator.d.ts b/lib/common/utils/decorators/request-mapping.decorator.d.ts index 988e1e34310..4577c04a722 100644 --- a/lib/common/utils/decorators/request-mapping.decorator.d.ts +++ b/lib/common/utils/decorators/request-mapping.decorator.d.ts @@ -1,6 +1,8 @@ import 'reflect-metadata'; import { RequestMappingMetadata } from '../../interfaces/request-mapping-metadata.interface'; -export declare const RequestMapping: (metadata?: RequestMappingMetadata) => MethodDecorator; +export declare const RequestMapping: ( + metadata?: RequestMappingMetadata +) => MethodDecorator; /** * Routes HTTP POST requests to the specified path. */ diff --git a/lib/common/utils/decorators/route-params.decorator.d.ts b/lib/common/utils/decorators/route-params.decorator.d.ts index 087e01390e8..128257ba8fd 100644 --- a/lib/common/utils/decorators/route-params.decorator.d.ts +++ b/lib/common/utils/decorators/route-params.decorator.d.ts @@ -2,10 +2,10 @@ import 'reflect-metadata'; import { PipeTransform } from '../../index'; export declare type ParamData = object | string | number; export interface RouteParamsMetadata { - [prop: number]: { - index: number; - data?: ParamData; - }; + [prop: number]: { + index: number; + data?: ParamData; + }; } export declare const Request: () => ParameterDecorator; export declare const Response: () => ParameterDecorator; @@ -14,12 +14,21 @@ export declare const Session: () => ParameterDecorator; export declare const Headers: (property?: string) => ParameterDecorator; export declare function Query(): any; export declare function Query(...pipes: PipeTransform[]): any; -export declare function Query(property: string, ...pipes: PipeTransform[]): any; +export declare function Query( + property: string, + ...pipes: PipeTransform[] +): any; export declare function Body(): any; export declare function Body(...pipes: PipeTransform[]): any; -export declare function Body(property: string, ...pipes: PipeTransform[]): any; +export declare function Body( + property: string, + ...pipes: PipeTransform[] +): any; export declare function Param(): any; export declare function Param(...pipes: PipeTransform[]): any; -export declare function Param(property: string, ...pipes: PipeTransform[]): any; +export declare function Param( + property: string, + ...pipes: PipeTransform[] +): any; export declare const Req: () => ParameterDecorator; export declare const Res: () => ParameterDecorator; diff --git a/lib/common/utils/decorators/use-guards.decorator.d.ts b/lib/common/utils/decorators/use-guards.decorator.d.ts index 027fc210be4..db5b30a6165 100644 --- a/lib/common/utils/decorators/use-guards.decorator.d.ts +++ b/lib/common/utils/decorators/use-guards.decorator.d.ts @@ -8,4 +8,6 @@ * * @param {} ...guards (types) */ -export declare function UseGuards(...guards: any[]): (target: object, key?: any, descriptor?: any) => any; +export declare function UseGuards( + ...guards: any[] +): (target: object, key?: any, descriptor?: any) => any; diff --git a/lib/common/utils/decorators/use-interceptors.decorator.d.ts b/lib/common/utils/decorators/use-interceptors.decorator.d.ts index e9ced6e0de3..d0cb600249a 100644 --- a/lib/common/utils/decorators/use-interceptors.decorator.d.ts +++ b/lib/common/utils/decorators/use-interceptors.decorator.d.ts @@ -8,4 +8,6 @@ * * @param {} ...interceptors (types) */ -export declare function UseInterceptors(...interceptors: any[]): (target: object, key?: any, descriptor?: any) => any; +export declare function UseInterceptors( + ...interceptors: any[] +): (target: object, key?: any, descriptor?: any) => any; diff --git a/lib/common/utils/decorators/use-pipes.decorator.d.ts b/lib/common/utils/decorators/use-pipes.decorator.d.ts index f1d08216c45..f806c421181 100644 --- a/lib/common/utils/decorators/use-pipes.decorator.d.ts +++ b/lib/common/utils/decorators/use-pipes.decorator.d.ts @@ -9,4 +9,6 @@ import { PipeTransform } from '../../interfaces/index'; * * @param {PipeTransform[]} ...pipes (instances) */ -export declare function UsePipes(...pipes: PipeTransform[]): (target: object, key?: any, descriptor?: any) => any; +export declare function UsePipes( + ...pipes: PipeTransform[] +): (target: object, key?: any, descriptor?: any) => any; diff --git a/lib/common/utils/forward-ref.util.d.ts b/lib/common/utils/forward-ref.util.d.ts index 33bde634545..d568ed96d44 100644 --- a/lib/common/utils/forward-ref.util.d.ts +++ b/lib/common/utils/forward-ref.util.d.ts @@ -1,3 +1,5 @@ -export declare function forwardRef(fn: () => any): { - forwardRef: () => any; +export declare function forwardRef( + fn: () => any +): { + forwardRef: () => any; }; diff --git a/lib/common/utils/http-exception-body.util.d.ts b/lib/common/utils/http-exception-body.util.d.ts index 32944fa29c8..16308843b0a 100644 --- a/lib/common/utils/http-exception-body.util.d.ts +++ b/lib/common/utils/http-exception-body.util.d.ts @@ -1,8 +1,14 @@ -export declare const createHttpExceptionBody: (message: any, error: string, status: number) => { - statusCode: number; - error: string; - message: any; -} | { - statusCode: number; - error: string; -}; +export declare const createHttpExceptionBody: ( + message: any, + error: string, + status: number +) => + | { + statusCode: number; + error: string; + message: any; + } + | { + statusCode: number; + error: string; + }; diff --git a/lib/common/utils/merge-with-values.util.d.ts b/lib/common/utils/merge-with-values.util.d.ts index 49a2ea3e6e3..1884390e4cb 100644 --- a/lib/common/utils/merge-with-values.util.d.ts +++ b/lib/common/utils/merge-with-values.util.d.ts @@ -1,7 +1,9 @@ import 'reflect-metadata'; export interface Constructor { - new (...args: any[]): T; + new (...args: any[]): T; } -export declare const MergeWithValues: >(data: { +export declare const MergeWithValues: >( + data: { [param: string]: any; -}) => (Metatype: T) => any; + } +) => (Metatype: T) => any; diff --git a/lib/core/adapters/express-adapter.d.ts b/lib/core/adapters/express-adapter.d.ts index 72b914eba11..164dade757e 100644 --- a/lib/core/adapters/express-adapter.d.ts +++ b/lib/core/adapters/express-adapter.d.ts @@ -1,4 +1,4 @@ export declare class ExpressAdapter { - static create(): any; - static createRouter(): any; + static create(): any; + static createRouter(): any; } diff --git a/lib/core/application-config.d.ts b/lib/core/application-config.d.ts index 0454f6337a1..59ff9090792 100644 --- a/lib/core/application-config.d.ts +++ b/lib/core/application-config.d.ts @@ -1,23 +1,29 @@ -import { PipeTransform, WebSocketAdapter, ExceptionFilter, NestInterceptor, CanActivate } from '@nestjs/common'; +import { + PipeTransform, + WebSocketAdapter, + ExceptionFilter, + NestInterceptor, + CanActivate +} from '@nestjs/common'; import { ConfigurationProvider } from '@nestjs/common/interfaces/configuration-provider.interface'; export declare class ApplicationConfig implements ConfigurationProvider { - private ioAdapter; - private globalPipes; - private globalFilters; - private globalInterceptors; - private globalGuards; - private globalPrefix; - constructor(ioAdapter?: WebSocketAdapter | null); - setGlobalPrefix(prefix: string): void; - getGlobalPrefix(): string; - setIoAdapter(ioAdapter: WebSocketAdapter): void; - getIoAdapter(): WebSocketAdapter; - useGlobalPipes(...pipes: PipeTransform[]): void; - getGlobalFilters(): ExceptionFilter[]; - useGlobalFilters(...filters: ExceptionFilter[]): void; - getGlobalPipes(): PipeTransform[]; - getGlobalInterceptors(): NestInterceptor[]; - useGlobalInterceptors(...interceptors: NestInterceptor[]): void; - getGlobalGuards(): CanActivate[]; - useGlobalGuards(...guards: CanActivate[]): void; + private ioAdapter; + private globalPipes; + private globalFilters; + private globalInterceptors; + private globalGuards; + private globalPrefix; + constructor(ioAdapter?: WebSocketAdapter | null); + setGlobalPrefix(prefix: string): void; + getGlobalPrefix(): string; + setIoAdapter(ioAdapter: WebSocketAdapter): void; + getIoAdapter(): WebSocketAdapter; + useGlobalPipes(...pipes: PipeTransform[]): void; + getGlobalFilters(): ExceptionFilter[]; + useGlobalFilters(...filters: ExceptionFilter[]): void; + getGlobalPipes(): PipeTransform[]; + getGlobalInterceptors(): NestInterceptor[]; + useGlobalInterceptors(...interceptors: NestInterceptor[]): void; + getGlobalGuards(): CanActivate[]; + useGlobalGuards(...guards: CanActivate[]): void; } diff --git a/lib/core/constants.d.ts b/lib/core/constants.d.ts index 56bf39c8193..ec6b37c92f0 100644 --- a/lib/core/constants.d.ts +++ b/lib/core/constants.d.ts @@ -1,6 +1,6 @@ export declare const messages: { - APPLICATION_START: string; - APPLICATION_READY: string; - MICROSERVICE_READY: string; - UNKNOWN_EXCEPTION_MESSAGE: string; + APPLICATION_START: string; + APPLICATION_READY: string; + MICROSERVICE_READY: string; + UNKNOWN_EXCEPTION_MESSAGE: string; }; diff --git a/lib/core/errors/exception-handler.d.ts b/lib/core/errors/exception-handler.d.ts index 25d8ab523a8..1dc7eb8ee15 100644 --- a/lib/core/errors/exception-handler.d.ts +++ b/lib/core/errors/exception-handler.d.ts @@ -1,5 +1,5 @@ import { RuntimeException } from './exceptions/runtime.exception'; export declare class ExceptionHandler { - private static readonly logger; - handle(exception: RuntimeException | Error): void; + private static readonly logger; + handle(exception: RuntimeException | Error): void; } diff --git a/lib/core/errors/exceptions-zone.d.ts b/lib/core/errors/exceptions-zone.d.ts index 06d4efeccee..b3beb201c7e 100644 --- a/lib/core/errors/exceptions-zone.d.ts +++ b/lib/core/errors/exceptions-zone.d.ts @@ -1,5 +1,5 @@ export declare class ExceptionsZone { - private static readonly exceptionHandler; - static run(fn: () => void): void; - static asyncRun(fn: () => Promise): Promise; + private static readonly exceptionHandler; + static run(fn: () => void): void; + static asyncRun(fn: () => Promise): Promise; } diff --git a/lib/core/errors/exceptions/invalid-exception-filter.exception.d.ts b/lib/core/errors/exceptions/invalid-exception-filter.exception.d.ts index a2ed936da89..6fe54055b75 100644 --- a/lib/core/errors/exceptions/invalid-exception-filter.exception.d.ts +++ b/lib/core/errors/exceptions/invalid-exception-filter.exception.d.ts @@ -1,4 +1,4 @@ import { RuntimeException } from './runtime.exception'; export declare class InvalidExceptionFilterException extends RuntimeException { - constructor(); + constructor(); } diff --git a/lib/core/errors/exceptions/invalid-middleware-configuration.exception.d.ts b/lib/core/errors/exceptions/invalid-middleware-configuration.exception.d.ts index a4bbaaa03ea..dcc64b11599 100644 --- a/lib/core/errors/exceptions/invalid-middleware-configuration.exception.d.ts +++ b/lib/core/errors/exceptions/invalid-middleware-configuration.exception.d.ts @@ -1,4 +1,4 @@ import { RuntimeException } from './runtime.exception'; export declare class InvalidMiddlewareConfigurationException extends RuntimeException { - constructor(); + constructor(); } diff --git a/lib/core/errors/exceptions/invalid-middleware.exception.d.ts b/lib/core/errors/exceptions/invalid-middleware.exception.d.ts index acb777c38ac..0ea67d77198 100644 --- a/lib/core/errors/exceptions/invalid-middleware.exception.d.ts +++ b/lib/core/errors/exceptions/invalid-middleware.exception.d.ts @@ -1,4 +1,4 @@ import { RuntimeException } from './runtime.exception'; export declare class InvalidMiddlewareException extends RuntimeException { - constructor(name: string); + constructor(name: string); } diff --git a/lib/core/errors/exceptions/invalid-module.exception.d.ts b/lib/core/errors/exceptions/invalid-module.exception.d.ts index 3cd8c0093f8..9bcbe8fa646 100644 --- a/lib/core/errors/exceptions/invalid-module.exception.d.ts +++ b/lib/core/errors/exceptions/invalid-module.exception.d.ts @@ -1,4 +1,4 @@ import { RuntimeException } from './runtime.exception'; export declare class InvalidModuleException extends RuntimeException { - constructor(trace: any[]); + constructor(trace: any[]); } diff --git a/lib/core/errors/exceptions/microservices-package-not-found.exception.d.ts b/lib/core/errors/exceptions/microservices-package-not-found.exception.d.ts index 97c847a0c18..cdc117e8f3b 100644 --- a/lib/core/errors/exceptions/microservices-package-not-found.exception.d.ts +++ b/lib/core/errors/exceptions/microservices-package-not-found.exception.d.ts @@ -1,4 +1,4 @@ import { RuntimeException } from './runtime.exception'; export declare class MicroservicesPackageNotFoundException extends RuntimeException { - constructor(); + constructor(); } diff --git a/lib/core/errors/exceptions/runtime.exception.d.ts b/lib/core/errors/exceptions/runtime.exception.d.ts index 2e5b6489f54..9258ce67eb3 100644 --- a/lib/core/errors/exceptions/runtime.exception.d.ts +++ b/lib/core/errors/exceptions/runtime.exception.d.ts @@ -1,11 +1,11 @@ export declare class Error { - name: string; - message: string; - stack: string; - constructor(message?: string); + name: string; + message: string; + stack: string; + constructor(message?: string); } export declare class RuntimeException extends Error { - private msg; - constructor(msg?: string); - what(): string; + private msg; + constructor(msg?: string); + what(): string; } diff --git a/lib/core/errors/exceptions/undefined-dependency.exception.d.ts b/lib/core/errors/exceptions/undefined-dependency.exception.d.ts index 70e2ef7641e..967fde9fbf6 100644 --- a/lib/core/errors/exceptions/undefined-dependency.exception.d.ts +++ b/lib/core/errors/exceptions/undefined-dependency.exception.d.ts @@ -1,4 +1,4 @@ import { RuntimeException } from './runtime.exception'; export declare class UndefinedDependencyException extends RuntimeException { - constructor(type: string, index: number, length: number); + constructor(type: string, index: number, length: number); } diff --git a/lib/core/errors/exceptions/unknown-dependencies.exception.d.ts b/lib/core/errors/exceptions/unknown-dependencies.exception.d.ts index f1627c9ba3c..4c096594781 100644 --- a/lib/core/errors/exceptions/unknown-dependencies.exception.d.ts +++ b/lib/core/errors/exceptions/unknown-dependencies.exception.d.ts @@ -1,4 +1,4 @@ import { RuntimeException } from './runtime.exception'; export declare class UnknownDependenciesException extends RuntimeException { - constructor(type: string, index: number, length: number); + constructor(type: string, index: number, length: number); } diff --git a/lib/core/errors/exceptions/unknown-export.exception.d.ts b/lib/core/errors/exceptions/unknown-export.exception.d.ts index 5246b262f5d..8d61d96b9ca 100644 --- a/lib/core/errors/exceptions/unknown-export.exception.d.ts +++ b/lib/core/errors/exceptions/unknown-export.exception.d.ts @@ -1,4 +1,4 @@ import { RuntimeException } from './runtime.exception'; export declare class UnknownExportException extends RuntimeException { - constructor(name: string); + constructor(name: string); } diff --git a/lib/core/errors/exceptions/unknown-module.exception.d.ts b/lib/core/errors/exceptions/unknown-module.exception.d.ts index effb1a0e67f..02ad09d0b1d 100644 --- a/lib/core/errors/exceptions/unknown-module.exception.d.ts +++ b/lib/core/errors/exceptions/unknown-module.exception.d.ts @@ -1,4 +1,4 @@ import { RuntimeException } from './runtime.exception'; export declare class UnknownModuleException extends RuntimeException { - constructor(); + constructor(); } diff --git a/lib/core/errors/exceptions/unknown-request-mapping.exception.d.ts b/lib/core/errors/exceptions/unknown-request-mapping.exception.d.ts index 283340c2bde..b7276d884d7 100644 --- a/lib/core/errors/exceptions/unknown-request-mapping.exception.d.ts +++ b/lib/core/errors/exceptions/unknown-request-mapping.exception.d.ts @@ -1,4 +1,4 @@ import { RuntimeException } from './runtime.exception'; export declare class UnknownRequestMappingException extends RuntimeException { - constructor(); + constructor(); } diff --git a/lib/core/errors/messages.d.ts b/lib/core/errors/messages.d.ts index ea0d35215d2..1a3a879fe34 100644 --- a/lib/core/errors/messages.d.ts +++ b/lib/core/errors/messages.d.ts @@ -1,4 +1,8 @@ -export declare const UnknownDependenciesMessage: (type: string, index: number, length: number) => string; +export declare const UnknownDependenciesMessage: ( + type: string, + index: number, + length: number +) => string; export declare const InvalidMiddlewareMessage: (name: string) => string; export declare const InvalidModuleMessage: (scope: string) => string; export declare const UnknownExportMessage: (name: string) => string; diff --git a/lib/core/exceptions/base-exception-filter-context.d.ts b/lib/core/exceptions/base-exception-filter-context.d.ts index 9bf124e6835..87e9d646e03 100644 --- a/lib/core/exceptions/base-exception-filter-context.d.ts +++ b/lib/core/exceptions/base-exception-filter-context.d.ts @@ -3,6 +3,6 @@ import { Metatype } from '@nestjs/common/interfaces/index'; import { ExceptionFilter } from '@nestjs/common/interfaces/exceptions/exception-filter.interface'; import { ContextCreator } from './../helpers/context-creator'; export declare class BaseExceptionFilterContext extends ContextCreator { - createConcreteContext(metadata: T): R; - reflectCatchExceptions(instance: ExceptionFilter): Metatype[]; + createConcreteContext(metadata: T): R; + reflectCatchExceptions(instance: ExceptionFilter): Metatype[]; } diff --git a/lib/core/exceptions/exceptions-handler.d.ts b/lib/core/exceptions/exceptions-handler.d.ts index 477dbe85fbb..299bc3f8d0e 100644 --- a/lib/core/exceptions/exceptions-handler.d.ts +++ b/lib/core/exceptions/exceptions-handler.d.ts @@ -1,9 +1,9 @@ import { ExceptionFilterMetadata } from '@nestjs/common/interfaces/exceptions/exception-filter-metadata.interface'; import { HttpException } from '@nestjs/common'; export declare class ExceptionsHandler { - private static readonly logger; - private filters; - next(exception: Error | HttpException | any, response: any): void; - setCustomFilters(filters: ExceptionFilterMetadata[]): void; - invokeCustomFilters(exception: any, response: any): boolean; + private static readonly logger; + private filters; + next(exception: Error | HttpException | any, response: any): void; + setCustomFilters(filters: ExceptionFilterMetadata[]): void; + invokeCustomFilters(exception: any, response: any): boolean; } diff --git a/lib/core/exceptions/http-exception.d.ts b/lib/core/exceptions/http-exception.d.ts index 99c459e6476..66ff927bbcb 100644 --- a/lib/core/exceptions/http-exception.d.ts +++ b/lib/core/exceptions/http-exception.d.ts @@ -1,23 +1,23 @@ export declare class HttpException { - private readonly response; - private readonly status; - private readonly logger; - /** - * The base Nest Application exception, which is handled by the default Exceptions Handler. - * If you throw an exception from your HTTP route handlers, Nest will map them to the appropriate HTTP response and send to the client. - * - * When `response` is an object: - * - object will be stringified and returned to the user as a JSON response, - * - * When `response` is a string: - * - Nest will create a response with two properties: - * ``` - * message: response, - * statusCode: X - * ``` - * @deprecated - */ - constructor(response: string | object, status: number); - getResponse(): string | object; - getStatus(): number; + private readonly response; + private readonly status; + private readonly logger; + /** + * The base Nest Application exception, which is handled by the default Exceptions Handler. + * If you throw an exception from your HTTP route handlers, Nest will map them to the appropriate HTTP response and send to the client. + * + * When `response` is an object: + * - object will be stringified and returned to the user as a JSON response, + * + * When `response` is a string: + * - Nest will create a response with two properties: + * ``` + * message: response, + * statusCode: X + * ``` + * @deprecated + */ + constructor(response: string | object, status: number); + getResponse(): string | object; + getStatus(): number; } diff --git a/lib/core/guards/constants.d.ts b/lib/core/guards/constants.d.ts index f4c98c0f485..a2f6cc39193 100644 --- a/lib/core/guards/constants.d.ts +++ b/lib/core/guards/constants.d.ts @@ -1 +1 @@ -export declare const FORBIDDEN_MESSAGE = "Forbidden resource"; +export declare const FORBIDDEN_MESSAGE = 'Forbidden resource'; diff --git a/lib/core/guards/guards-consumer.d.ts b/lib/core/guards/guards-consumer.d.ts index a165b68b249..e9bba1635eb 100644 --- a/lib/core/guards/guards-consumer.d.ts +++ b/lib/core/guards/guards-consumer.d.ts @@ -3,7 +3,17 @@ import { CanActivate, ExecutionContext } from '@nestjs/common'; import { Observable } from 'rxjs/Observable'; import 'rxjs/add/operator/toPromise'; export declare class GuardsConsumer { - tryActivate(guards: CanActivate[], data: any, instance: Controller, callback: (...args) => any): Promise; - createContext(instance: Controller, callback: (...args) => any): ExecutionContext; - pickResult(result: boolean | Promise | Observable): Promise; + tryActivate( + guards: CanActivate[], + data: any, + instance: Controller, + callback: (...args) => any + ): Promise; + createContext( + instance: Controller, + callback: (...args) => any + ): ExecutionContext; + pickResult( + result: boolean | Promise | Observable + ): Promise; } diff --git a/lib/core/guards/guards-context-creator.d.ts b/lib/core/guards/guards-context-creator.d.ts index c8e643e8ccb..5754c5c5bfa 100644 --- a/lib/core/guards/guards-context-creator.d.ts +++ b/lib/core/guards/guards-context-creator.d.ts @@ -5,15 +5,23 @@ import { NestContainer } from '../injector/container'; import { CanActivate } from '@nestjs/common'; import { ConfigurationProvider } from '@nestjs/common/interfaces/configuration-provider.interface'; export declare class GuardsContextCreator extends ContextCreator { - private readonly container; - private readonly config; - private moduleContext; - constructor(container: NestContainer, config?: ConfigurationProvider); - create(instance: Controller, callback: (...args) => any, module: string): CanActivate[]; - createConcreteContext(metadata: T): R; - createGlobalMetadataContext(metadata: T): R; - getInstanceByMetatype(metatype: any): { + private readonly container; + private readonly config; + private moduleContext; + constructor(container: NestContainer, config?: ConfigurationProvider); + create( + instance: Controller, + callback: (...args) => any, + module: string + ): CanActivate[]; + createConcreteContext(metadata: T): R; + createGlobalMetadataContext(metadata: T): R; + getInstanceByMetatype( + metatype: any + ): + | { instance: any; - } | undefined; - getGlobalMetadata(): T; + } + | undefined; + getGlobalMetadata(): T; } diff --git a/lib/core/helpers/context-creator.d.ts b/lib/core/helpers/context-creator.d.ts index 118262b9a0c..16d75041f20 100644 --- a/lib/core/helpers/context-creator.d.ts +++ b/lib/core/helpers/context-creator.d.ts @@ -1,9 +1,15 @@ import 'reflect-metadata'; import { Controller } from '@nestjs/common/interfaces'; -export declare abstract class ContextCreator { - abstract createConcreteContext(metadata: T): R; - getGlobalMetadata?(): T; - createContext(instance: Controller, callback: (...args) => any, metadataKey: string): R; - reflectClassMetadata(instance: Controller, metadataKey: string): T; - reflectMethodMetadata(callback: (...args) => any, metadataKey: string): T; +export abstract class ContextCreator { + abstract createConcreteContext( + metadata: T + ): R; + getGlobalMetadata?(): T; + createContext( + instance: Controller, + callback: (...args) => any, + metadataKey: string + ): R; + reflectClassMetadata(instance: Controller, metadataKey: string): T; + reflectMethodMetadata(callback: (...args) => any, metadataKey: string): T; } diff --git a/lib/core/helpers/external-context-creator.d.ts b/lib/core/helpers/external-context-creator.d.ts index b63eb0846a0..742b14d289f 100644 --- a/lib/core/helpers/external-context-creator.d.ts +++ b/lib/core/helpers/external-context-creator.d.ts @@ -7,13 +7,23 @@ import { Controller } from '@nestjs/common/interfaces'; import { Module } from './../injector/module'; import { ModulesContainer } from './../injector/modules-container'; export declare class ExternalContextCreator { - private readonly guardsContextCreator; - private readonly guardsConsumer; - private readonly interceptorsContextCreator; - private readonly interceptorsConsumer; - private readonly modulesContainer; - constructor(guardsContextCreator: GuardsContextCreator, guardsConsumer: GuardsConsumer, interceptorsContextCreator: InterceptorsContextCreator, interceptorsConsumer: InterceptorsConsumer, modulesContainer: ModulesContainer); - create(instance: Controller, callback: (...args) => any, methodName: string): (...args: any[]) => Promise; - findContextModuleName(constructor: Function): string; - findComponentByClassName(module: Module, className: string): boolean; + private readonly guardsContextCreator; + private readonly guardsConsumer; + private readonly interceptorsContextCreator; + private readonly interceptorsConsumer; + private readonly modulesContainer; + constructor( + guardsContextCreator: GuardsContextCreator, + guardsConsumer: GuardsConsumer, + interceptorsContextCreator: InterceptorsContextCreator, + interceptorsConsumer: InterceptorsConsumer, + modulesContainer: ModulesContainer + ); + create( + instance: Controller, + callback: (...args) => any, + methodName: string + ): (...args: any[]) => Promise; + findContextModuleName(constructor: Function): string; + findComponentByClassName(module: Module, className: string): boolean; } diff --git a/lib/core/helpers/messages.d.ts b/lib/core/helpers/messages.d.ts index 4f0f5732314..af068cc61db 100644 --- a/lib/core/helpers/messages.d.ts +++ b/lib/core/helpers/messages.d.ts @@ -1,3 +1,6 @@ export declare const ModuleInitMessage: (module: string) => string; export declare const RouteMappedMessage: (path: string, method: any) => string; -export declare const ControllerMappingMessage: (name: string, path: string) => string; +export declare const ControllerMappingMessage: ( + name: string, + path: string +) => string; diff --git a/lib/core/helpers/router-method-factory.d.ts b/lib/core/helpers/router-method-factory.d.ts index f0f487eb0ee..26fa697789f 100644 --- a/lib/core/helpers/router-method-factory.d.ts +++ b/lib/core/helpers/router-method-factory.d.ts @@ -1,4 +1,4 @@ import { RequestMethod } from '@nestjs/common/enums/request-method.enum'; export declare class RouterMethodFactory { - get(target: any, requestMethod: RequestMethod): any; + get(target: any, requestMethod: RequestMethod): any; } diff --git a/lib/core/injector/container.d.ts b/lib/core/injector/container.d.ts index 6c143350104..0925b7e8f0d 100644 --- a/lib/core/injector/container.d.ts +++ b/lib/core/injector/container.d.ts @@ -6,43 +6,65 @@ import { Module } from './module'; import { DynamicModule } from '@nestjs/common'; import { ModulesContainer } from './modules-container'; export declare class NestContainer { - private readonly globalModules; - private readonly modules; - private readonly dynamicModulesMetadata; - private readonly moduleTokenFactory; - addModule(metatype: NestModuleMetatype | DynamicModule, scope: NestModuleMetatype[]): void; - extractMetadata(metatype: NestModuleMetatype | DynamicModule): { - type: NestModuleMetatype; - dynamicMetadata?: Partial | undefined; - }; - isDynamicModule(module: NestModuleMetatype | DynamicModule): module is DynamicModule; - addDynamicMetadata(token: string, dynamicModuleMetadata: Partial): any; - isGlobalModule(metatype: NestModuleMetatype): boolean; - addGlobalModule(module: Module): void; - getModules(): ModulesContainer; - addRelatedModule(relatedModule: NestModuleMetatype | DynamicModule, token: string): void; - addComponent(component: Metatype, token: string): void; - addInjectable(injectable: Metatype, token: string): void; - addExportedComponent(exportedComponent: Metatype, token: string): void; - addController(controller: Metatype, token: string): void; - clear(): void; - replace(toReplace: any, options: any & { - scope: any[] | null; - }): void; - bindGlobalScope(): void; - bindGlobalsToRelatedModules(module: Module): void; - bindGlobalModuleToModule(module: Module, globalModule: Module): any; - getDynamicMetadataByToken(token: string, metadataKey: keyof DynamicModule): any[]; + private readonly globalModules; + private readonly modules; + private readonly dynamicModulesMetadata; + private readonly moduleTokenFactory; + addModule( + metatype: NestModuleMetatype | DynamicModule, + scope: NestModuleMetatype[] + ): void; + extractMetadata( + metatype: NestModuleMetatype | DynamicModule + ): { + type: NestModuleMetatype; + dynamicMetadata?: Partial | undefined; + }; + isDynamicModule( + module: NestModuleMetatype | DynamicModule + ): module is DynamicModule; + addDynamicMetadata( + token: string, + dynamicModuleMetadata: Partial + ): any; + isGlobalModule(metatype: NestModuleMetatype): boolean; + addGlobalModule(module: Module): void; + getModules(): ModulesContainer; + addRelatedModule( + relatedModule: NestModuleMetatype | DynamicModule, + token: string + ): void; + addComponent(component: Metatype, token: string): void; + addInjectable(injectable: Metatype, token: string): void; + addExportedComponent( + exportedComponent: Metatype, + token: string + ): void; + addController(controller: Metatype, token: string): void; + clear(): void; + replace( + toReplace: any, + options: any & { + scope: any[] | null; + } + ): void; + bindGlobalScope(): void; + bindGlobalsToRelatedModules(module: Module): void; + bindGlobalModuleToModule(module: Module, globalModule: Module): any; + getDynamicMetadataByToken( + token: string, + metadataKey: keyof DynamicModule + ): any[]; } export interface InstanceWrapper { - name: any; - metatype: Metatype; - instance: T; - isResolved: boolean; - isPending?: boolean; - done$?: Promise; - inject?: Metatype[]; - isNotMetatype?: boolean; - forwardRef?: boolean; - async?: boolean; + name: any; + metatype: Metatype; + instance: T; + isResolved: boolean; + isPending?: boolean; + done$?: Promise; + inject?: Metatype[]; + isNotMetatype?: boolean; + forwardRef?: boolean; + async?: boolean; } diff --git a/lib/core/injector/injector.d.ts b/lib/core/injector/injector.d.ts index 792feb155bc..a2fc84ffab5 100644 --- a/lib/core/injector/injector.d.ts +++ b/lib/core/injector/injector.d.ts @@ -6,48 +6,139 @@ import { Controller } from '@nestjs/common/interfaces/controllers/controller.int import { Injectable } from '@nestjs/common/interfaces/injectable.interface'; import { MiddlewareWrapper } from '../middlewares/container'; export declare class Injector { - loadInstanceOfMiddleware(wrapper: MiddlewareWrapper, collection: Map, module: Module): Promise; - loadInstanceOfRoute(wrapper: InstanceWrapper, module: Module): Promise; - loadInstanceOfInjectable(wrapper: InstanceWrapper, module: Module): Promise; - loadPrototypeOfInstance({metatype, name}: InstanceWrapper, collection: Map>): any; - loadInstanceOfComponent(wrapper: InstanceWrapper, module: Module, context?: Module[]): Promise; - applyDoneSubject(wrapper: InstanceWrapper): () => void; - loadInstance(wrapper: InstanceWrapper, collection: any, module: Module, context?: Module[]): Promise; - resolveConstructorParams(wrapper: InstanceWrapper, module: Module, inject: any[], context: Module[], callback: (args) => void): Promise; - reflectConstructorParams(type: Metatype): any[]; - reflectSelfParams(type: Metatype): any[]; - resolveSingleParam(wrapper: InstanceWrapper, param: Metatype | string | symbol | any, {index, length}: { - index: number; - length: number; - }, module: Module, context: Module[]): Promise; - resolveParamToken(wrapper: InstanceWrapper, param: Metatype | string | symbol | any): any; - resolveComponentInstance(module: Module, name: any, {index, length}: { - index: number; - length: number; - }, wrapper: InstanceWrapper, context: Module[]): Promise; - scanForComponent(components: Map, module: Module, {name, index, length}: { - name: any; - index: number; - length: number; - }, {metatype}: { - metatype: any; - }, context?: Module[]): any; - scanForComponentInExports(components: Map, {name, index, length}: { - name: any; - index: number; - length: number; - }, module: Module, metatype: any, context?: Module[]): Promise; - scanForComponentInScopes(context: Module[], {name, index, length}: { - name: any; - index: number; - length: number; - }, metatype: any): any; - scanForComponentInScope(context: Module, {name, index, length}: { - name: any; - index: number; - length: number; - }, metatype: any): any; - scanForComponentInRelatedModules(module: Module, name: any, context: Module[]): Promise; - resolveFactoryInstance(factoryResult: any): Promise; - flatMap(modules: Module[]): Module[]; + loadInstanceOfMiddleware( + wrapper: MiddlewareWrapper, + collection: Map, + module: Module + ): Promise; + loadInstanceOfRoute( + wrapper: InstanceWrapper, + module: Module + ): Promise; + loadInstanceOfInjectable( + wrapper: InstanceWrapper, + module: Module + ): Promise; + loadPrototypeOfInstance( + { metatype, name }: InstanceWrapper, + collection: Map> + ): any; + loadInstanceOfComponent( + wrapper: InstanceWrapper, + module: Module, + context?: Module[] + ): Promise; + applyDoneSubject(wrapper: InstanceWrapper): () => void; + loadInstance( + wrapper: InstanceWrapper, + collection: any, + module: Module, + context?: Module[] + ): Promise; + resolveConstructorParams( + wrapper: InstanceWrapper, + module: Module, + inject: any[], + context: Module[], + callback: (args) => void + ): Promise; + reflectConstructorParams(type: Metatype): any[]; + reflectSelfParams(type: Metatype): any[]; + resolveSingleParam( + wrapper: InstanceWrapper, + param: Metatype | string | symbol | any, + { + index, + length + }: { + index: number; + length: number; + }, + module: Module, + context: Module[] + ): Promise; + resolveParamToken( + wrapper: InstanceWrapper, + param: Metatype | string | symbol | any + ): any; + resolveComponentInstance( + module: Module, + name: any, + { + index, + length + }: { + index: number; + length: number; + }, + wrapper: InstanceWrapper, + context: Module[] + ): Promise; + scanForComponent( + components: Map, + module: Module, + { + name, + index, + length + }: { + name: any; + index: number; + length: number; + }, + { + metatype + }: { + metatype: any; + }, + context?: Module[] + ): any; + scanForComponentInExports( + components: Map, + { + name, + index, + length + }: { + name: any; + index: number; + length: number; + }, + module: Module, + metatype: any, + context?: Module[] + ): Promise; + scanForComponentInScopes( + context: Module[], + { + name, + index, + length + }: { + name: any; + index: number; + length: number; + }, + metatype: any + ): any; + scanForComponentInScope( + context: Module, + { + name, + index, + length + }: { + name: any; + index: number; + length: number; + }, + metatype: any + ): any; + scanForComponentInRelatedModules( + module: Module, + name: any, + context: Module[] + ): Promise; + resolveFactoryInstance(factoryResult: any): Promise; + flatMap(modules: Module[]): Module[]; } diff --git a/lib/core/injector/instance-loader.d.ts b/lib/core/injector/instance-loader.d.ts index 71a0fea8d66..2494741b86c 100644 --- a/lib/core/injector/instance-loader.d.ts +++ b/lib/core/injector/instance-loader.d.ts @@ -1,16 +1,16 @@ import { NestContainer } from './container'; export declare class InstanceLoader { - private readonly container; - private readonly injector; - private readonly logger; - constructor(container: NestContainer); - createInstancesOfDependencies(): Promise; - private createPrototypes(modules); - private createInstances(modules); - private createPrototypesOfComponents(module); - private createInstancesOfComponents(module); - private createPrototypesOfRoutes(module); - private createInstancesOfRoutes(module); - private createPrototypesOfInjectables(module); - private createInstancesOfInjectables(module); + private readonly container; + private readonly injector; + private readonly logger; + constructor(container: NestContainer); + createInstancesOfDependencies(): Promise; + private createPrototypes(modules); + private createInstances(modules); + private createPrototypesOfComponents(module); + private createInstancesOfComponents(module); + private createPrototypesOfRoutes(module); + private createInstancesOfRoutes(module); + private createPrototypesOfInjectables(module); + private createInstancesOfInjectables(module); } diff --git a/lib/core/injector/module-ref.d.ts b/lib/core/injector/module-ref.d.ts index eefe16c7326..8c4ada880b8 100644 --- a/lib/core/injector/module-ref.d.ts +++ b/lib/core/injector/module-ref.d.ts @@ -1,4 +1,4 @@ import { OpaqueToken } from './module'; -export declare abstract class ModuleRef { - abstract get(type: OpaqueToken): T; +export abstract class ModuleRef { + abstract get(type: OpaqueToken): T; } diff --git a/lib/core/injector/module-token-factory.d.ts b/lib/core/injector/module-token-factory.d.ts index 6e4713d0d02..b0e6637e802 100644 --- a/lib/core/injector/module-token-factory.d.ts +++ b/lib/core/injector/module-token-factory.d.ts @@ -1,9 +1,15 @@ import { NestModuleMetatype } from '@nestjs/common/interfaces/modules/module-metatype.interface'; import { DynamicModule } from '@nestjs/common'; export declare class ModuleTokenFactory { - create(metatype: NestModuleMetatype, scope: NestModuleMetatype[], dynamicModuleMetadata?: Partial | undefined): string; - getDynamicMetadataToken(dynamicModuleMetadata: Partial | undefined): string; - getModuleName(metatype: NestModuleMetatype): string; - getScopeStack(scope: NestModuleMetatype[]): string[]; - private reflectScope(metatype); + create( + metatype: NestModuleMetatype, + scope: NestModuleMetatype[], + dynamicModuleMetadata?: Partial | undefined + ): string; + getDynamicMetadataToken( + dynamicModuleMetadata: Partial | undefined + ): string; + getModuleName(metatype: NestModuleMetatype): string; + getScopeStack(scope: NestModuleMetatype[]): string[]; + private reflectScope(metatype); } diff --git a/lib/core/injector/module.d.ts b/lib/core/injector/module.d.ts index ce6a63e0107..b49dfb3efe6 100644 --- a/lib/core/injector/module.d.ts +++ b/lib/core/injector/module.d.ts @@ -3,63 +3,83 @@ import { Injectable, Controller, NestModule } from '@nestjs/common/interfaces'; import { NestModuleMetatype } from '@nestjs/common/interfaces/modules/module-metatype.interface'; import { Metatype } from '@nestjs/common/interfaces/metatype.interface'; export interface CustomComponent { - provide: any; - name: string; + provide: any; + name: string; } export declare type OpaqueToken = string | symbol | object | Metatype; export declare type CustomClass = CustomComponent & { - useClass: Metatype; + useClass: Metatype; }; export declare type CustomFactory = CustomComponent & { - useFactory: (...args) => any; - inject?: Metatype[]; + useFactory: (...args) => any; + inject?: Metatype[]; }; export declare type CustomValue = CustomComponent & { - useValue: any; + useValue: any; }; -export declare type ComponentMetatype = Metatype | CustomFactory | CustomValue | CustomClass; +export declare type ComponentMetatype = + | Metatype + | CustomFactory + | CustomValue + | CustomClass; export declare class Module { - private _metatype; - private _scope; - private _relatedModules; - private _components; - private _injectables; - private _routes; - private _exports; - constructor(_metatype: NestModuleMetatype, _scope: NestModuleMetatype[], container: NestContainer); - readonly scope: NestModuleMetatype[]; - readonly relatedModules: Set; - readonly components: Map>; - readonly injectables: Map>; - readonly routes: Map>; - readonly exports: Set; - readonly instance: NestModule; - readonly metatype: NestModuleMetatype; - addCoreInjectables(container: NestContainer): void; - addModuleRef(): void; - addModuleAsComponent(): void; - addReflector(): void; - addExternalContextCreator(container: NestContainer): void; - addModulesContainer(container: NestContainer): void; - addInjectable(injectable: Metatype): void; - addComponent(component: ComponentMetatype): void; - isCustomProvider(component: ComponentMetatype): component is CustomClass | CustomFactory | CustomValue; - addCustomProvider(component: CustomFactory | CustomValue | CustomClass, collection: Map): void; - isCustomClass(component: any): component is CustomClass; - isCustomValue(component: any): component is CustomValue; - isCustomFactory(component: any): component is CustomFactory; - addCustomClass(component: CustomClass, collection: Map): void; - addCustomValue(component: CustomValue, collection: Map): void; - addCustomFactory(component: CustomFactory, collection: Map): void; - addExportedComponent(exportedComponent: ComponentMetatype): void; - addCustomExportedComponent(exportedComponent: CustomFactory | CustomValue | CustomClass): void; - addRoute(route: Metatype): void; - addRelatedModule(relatedModule: any): void; - replace(toReplace: any, options: any): void; - createModuleRefMetatype(components: any): { - new (): { - readonly components: any; - get(type: OpaqueToken): T; - }; + private _metatype; + private _scope; + private _relatedModules; + private _components; + private _injectables; + private _routes; + private _exports; + constructor( + _metatype: NestModuleMetatype, + _scope: NestModuleMetatype[], + container: NestContainer + ); + readonly scope: NestModuleMetatype[]; + readonly relatedModules: Set; + readonly components: Map>; + readonly injectables: Map>; + readonly routes: Map>; + readonly exports: Set; + readonly instance: NestModule; + readonly metatype: NestModuleMetatype; + addCoreInjectables(container: NestContainer): void; + addModuleRef(): void; + addModuleAsComponent(): void; + addReflector(): void; + addExternalContextCreator(container: NestContainer): void; + addModulesContainer(container: NestContainer): void; + addInjectable(injectable: Metatype): void; + addComponent(component: ComponentMetatype): void; + isCustomProvider( + component: ComponentMetatype + ): component is CustomClass | CustomFactory | CustomValue; + addCustomProvider( + component: CustomFactory | CustomValue | CustomClass, + collection: Map + ): void; + isCustomClass(component: any): component is CustomClass; + isCustomValue(component: any): component is CustomValue; + isCustomFactory(component: any): component is CustomFactory; + addCustomClass(component: CustomClass, collection: Map): void; + addCustomValue(component: CustomValue, collection: Map): void; + addCustomFactory( + component: CustomFactory, + collection: Map + ): void; + addExportedComponent(exportedComponent: ComponentMetatype): void; + addCustomExportedComponent( + exportedComponent: CustomFactory | CustomValue | CustomClass + ): void; + addRoute(route: Metatype): void; + addRelatedModule(relatedModule: any): void; + replace(toReplace: any, options: any): void; + createModuleRefMetatype( + components: any + ): { + new (): { + readonly components: any; + get(type: OpaqueToken): T; }; + }; } diff --git a/lib/core/injector/modules-container.d.ts b/lib/core/injector/modules-container.d.ts index 2bf3c4c04e9..7eb90a23429 100644 --- a/lib/core/injector/modules-container.d.ts +++ b/lib/core/injector/modules-container.d.ts @@ -1,3 +1,2 @@ import { Module } from './module'; -export declare class ModulesContainer extends Map { -} +export declare class ModulesContainer extends Map {} diff --git a/lib/core/interceptors/interceptors-consumer.d.ts b/lib/core/interceptors/interceptors-consumer.d.ts index 58598449dee..c563de3a07d 100644 --- a/lib/core/interceptors/interceptors-consumer.d.ts +++ b/lib/core/interceptors/interceptors-consumer.d.ts @@ -5,7 +5,16 @@ import 'rxjs/add/operator/toPromise'; import 'rxjs/add/observable/defer'; import 'rxjs/add/operator/take'; export declare class InterceptorsConsumer { - intercept(interceptors: NestInterceptor[], dataOrRequest: any, instance: Controller, callback: (...args) => any, next: () => Promise): Promise; - createContext(instance: Controller, callback: (...args) => any): ExecutionContext; - transformDeffered(next: () => any): Promise | Observable; + intercept( + interceptors: NestInterceptor[], + dataOrRequest: any, + instance: Controller, + callback: (...args) => any, + next: () => Promise + ): Promise; + createContext( + instance: Controller, + callback: (...args) => any + ): ExecutionContext; + transformDeffered(next: () => any): Promise | Observable; } diff --git a/lib/core/interceptors/interceptors-context-creator.d.ts b/lib/core/interceptors/interceptors-context-creator.d.ts index f8e7acf5741..60f7c541aa2 100644 --- a/lib/core/interceptors/interceptors-context-creator.d.ts +++ b/lib/core/interceptors/interceptors-context-creator.d.ts @@ -4,15 +4,23 @@ import { ContextCreator } from './../helpers/context-creator'; import { NestContainer } from '../injector/container'; import { ConfigurationProvider } from '@nestjs/common/interfaces/configuration-provider.interface'; export declare class InterceptorsContextCreator extends ContextCreator { - private readonly container; - private readonly config; - private moduleContext; - constructor(container: NestContainer, config?: ConfigurationProvider); - create(instance: Controller, callback: (...args) => any, module: string): NestInterceptor[]; - createConcreteContext(metadata: T): R; - createGlobalMetadataContext(metadata: T): R; - getInstanceByMetatype(metatype: any): { + private readonly container; + private readonly config; + private moduleContext; + constructor(container: NestContainer, config?: ConfigurationProvider); + create( + instance: Controller, + callback: (...args) => any, + module: string + ): NestInterceptor[]; + createConcreteContext(metadata: T): R; + createGlobalMetadataContext(metadata: T): R; + getInstanceByMetatype( + metatype: any + ): + | { instance: any; - } | undefined; - getGlobalMetadata(): T; + } + | undefined; + getGlobalMetadata(): T; } diff --git a/lib/core/metadata-scanner.d.ts b/lib/core/metadata-scanner.d.ts index a70e7b963dd..791d0c188b9 100644 --- a/lib/core/metadata-scanner.d.ts +++ b/lib/core/metadata-scanner.d.ts @@ -1,4 +1,8 @@ import { Injectable } from '@nestjs/common/interfaces/injectable.interface'; export declare class MetadataScanner { - scanFromPrototype(instance: T, prototype: any, callback: (name: string) => R): R[]; + scanFromPrototype( + instance: T, + prototype: any, + callback: (name: string) => R + ): R[]; } diff --git a/lib/core/middlewares/builder.d.ts b/lib/core/middlewares/builder.d.ts index 69fd53603c5..ebe6760a50b 100644 --- a/lib/core/middlewares/builder.d.ts +++ b/lib/core/middlewares/builder.d.ts @@ -3,17 +3,17 @@ import { MiddlewaresConsumer } from '@nestjs/common/interfaces'; import { MiddlewareConfigProxy } from '@nestjs/common/interfaces/middlewares'; import { RoutesMapper } from './routes-mapper'; export declare class MiddlewareBuilder implements MiddlewaresConsumer { - private readonly routesMapper; - private readonly middlewaresCollection; - private readonly logger; - constructor(routesMapper: RoutesMapper); - apply(middlewares: any | any[]): MiddlewareConfigProxy; - /** - * @deprecated - * Since version RC.6 this method is deprecated. Use apply() instead. - */ - use(configuration: MiddlewareConfiguration): this; - build(): MiddlewareConfiguration[]; - private bindValuesToResolve(middlewares, resolveParams); - private static ConfigProxy; + private readonly routesMapper; + private readonly middlewaresCollection; + private readonly logger; + constructor(routesMapper: RoutesMapper); + apply(middlewares: any | any[]): MiddlewareConfigProxy; + /** + * @deprecated + * Since version RC.6 this method is deprecated. Use apply() instead. + */ + use(configuration: MiddlewareConfiguration): this; + build(): MiddlewareConfiguration[]; + private bindValuesToResolve(middlewares, resolveParams); + private static ConfigProxy; } diff --git a/lib/core/middlewares/container.d.ts b/lib/core/middlewares/container.d.ts index 849e47d0c7c..ef56f57897f 100644 --- a/lib/core/middlewares/container.d.ts +++ b/lib/core/middlewares/container.d.ts @@ -2,15 +2,15 @@ import { MiddlewareConfiguration } from '@nestjs/common/interfaces/middlewares/m import { NestMiddleware } from '@nestjs/common/interfaces/middlewares/nest-middleware.interface'; import { Metatype } from '@nestjs/common/interfaces/metatype.interface'; export declare class MiddlewaresContainer { - private readonly middlewares; - private readonly configs; - getMiddlewares(module: string): Map; - getConfigs(): Map>; - addConfig(configList: MiddlewareConfiguration[], module: string): void; - private getCurrentMiddlewares(module); - private getCurrentConfig(module); + private readonly middlewares; + private readonly configs; + getMiddlewares(module: string): Map; + getConfigs(): Map>; + addConfig(configList: MiddlewareConfiguration[], module: string): void; + private getCurrentMiddlewares(module); + private getCurrentConfig(module); } export interface MiddlewareWrapper { - instance: NestMiddleware; - metatype: Metatype; + instance: NestMiddleware; + metatype: Metatype; } diff --git a/lib/core/middlewares/middlewares-module.d.ts b/lib/core/middlewares/middlewares-module.d.ts index ba5e0ef4f8b..f0e5e28cb19 100644 --- a/lib/core/middlewares/middlewares-module.d.ts +++ b/lib/core/middlewares/middlewares-module.d.ts @@ -7,19 +7,44 @@ import { RequestMethod } from '@nestjs/common/enums/request-method.enum'; import { Module } from '../injector/module'; import { ApplicationConfig } from './../application-config'; export declare class MiddlewaresModule { - private readonly routesMapper; - private readonly routerProxy; - private readonly routerMethodFactory; - private routerExceptionFilter; - private resolver; - setup(middlewaresContainer: MiddlewaresContainer, container: NestContainer, config: ApplicationConfig): Promise; - resolveMiddlewares(middlewaresContainer: MiddlewaresContainer, modules: Map): Promise; - loadConfiguration(middlewaresContainer: MiddlewaresContainer, instance: NestModule, module: string): void; - setupMiddlewares(middlewaresContainer: MiddlewaresContainer, app: any): Promise; - setupMiddlewareConfig(middlewaresContainer: MiddlewaresContainer, config: MiddlewareConfiguration, module: string, app: any): Promise; - setupRouteMiddleware(middlewaresContainer: MiddlewaresContainer, route: ControllerMetadata & { - method: RequestMethod; - }, config: MiddlewareConfiguration, module: string, app: any): Promise; - private setupHandler(instance, metatype, app, method, path); - private setupHandlerWithProxy(exceptionsHandler, router, middleware, path); + private readonly routesMapper; + private readonly routerProxy; + private readonly routerMethodFactory; + private routerExceptionFilter; + private resolver; + setup( + middlewaresContainer: MiddlewaresContainer, + container: NestContainer, + config: ApplicationConfig + ): Promise; + resolveMiddlewares( + middlewaresContainer: MiddlewaresContainer, + modules: Map + ): Promise; + loadConfiguration( + middlewaresContainer: MiddlewaresContainer, + instance: NestModule, + module: string + ): void; + setupMiddlewares( + middlewaresContainer: MiddlewaresContainer, + app: any + ): Promise; + setupMiddlewareConfig( + middlewaresContainer: MiddlewaresContainer, + config: MiddlewareConfiguration, + module: string, + app: any + ): Promise; + setupRouteMiddleware( + middlewaresContainer: MiddlewaresContainer, + route: ControllerMetadata & { + method: RequestMethod; + }, + config: MiddlewareConfiguration, + module: string, + app: any + ): Promise; + private setupHandler(instance, metatype, app, method, path); + private setupHandlerWithProxy(exceptionsHandler, router, middleware, path); } diff --git a/lib/core/middlewares/resolver.d.ts b/lib/core/middlewares/resolver.d.ts index cd82405f852..4114bdbbbca 100644 --- a/lib/core/middlewares/resolver.d.ts +++ b/lib/core/middlewares/resolver.d.ts @@ -1,9 +1,9 @@ import { MiddlewaresContainer } from './container'; import { Module } from '../injector/module'; export declare class MiddlewaresResolver { - private readonly middlewaresContainer; - private readonly instanceLoader; - constructor(middlewaresContainer: MiddlewaresContainer); - resolveInstances(module: Module, moduleName: string): Promise; - private resolveMiddlewareInstance(wrapper, middlewares, module); + private readonly middlewaresContainer; + private readonly instanceLoader; + constructor(middlewaresContainer: MiddlewaresContainer); + resolveInstances(module: Module, moduleName: string): Promise; + private resolveMiddlewareInstance(wrapper, middlewares, module); } diff --git a/lib/core/middlewares/routes-mapper.d.ts b/lib/core/middlewares/routes-mapper.d.ts index 7edc27cf9a8..1a88d9ea81b 100644 --- a/lib/core/middlewares/routes-mapper.d.ts +++ b/lib/core/middlewares/routes-mapper.d.ts @@ -1,11 +1,13 @@ import 'reflect-metadata'; export declare class RoutesMapper { - private readonly routerExplorer; - mapRouteToRouteProps(routeMetatype: any): { - path: string; - method: any; - }[]; - private mapObjectToRouteProps(route); - private validateGlobalPath(path); - private validateRoutePath(path); + private readonly routerExplorer; + mapRouteToRouteProps( + routeMetatype: any + ): { + path: string; + method: any; + }[]; + private mapObjectToRouteProps(route); + private validateGlobalPath(path); + private validateRoutePath(path); } diff --git a/lib/core/nest-application-context.d.ts b/lib/core/nest-application-context.d.ts index 2ba86f6fd44..9e35378d6cc 100644 --- a/lib/core/nest-application-context.d.ts +++ b/lib/core/nest-application-context.d.ts @@ -3,12 +3,16 @@ import { NestModuleMetatype } from '@nestjs/common/interfaces/modules/module-met import { Metatype } from '@nestjs/common/interfaces'; import { INestApplicationContext } from '@nestjs/common'; export declare class NestApplicationContext implements INestApplicationContext { - protected readonly container: NestContainer; - private readonly scope; - protected contextModule: any; - private readonly moduleTokenFactory; - constructor(container: NestContainer, scope: NestModuleMetatype[], contextModule: any); - select(module: Metatype): INestApplicationContext; - get(metatypeOrToken: Metatype | string | symbol): T; - private findInstanceByPrototypeOrToken(metatypeOrToken); + protected readonly container: NestContainer; + private readonly scope; + protected contextModule: any; + private readonly moduleTokenFactory; + constructor( + container: NestContainer, + scope: NestModuleMetatype[], + contextModule: any + ); + select(module: Metatype): INestApplicationContext; + get(metatypeOrToken: Metatype | string | symbol): T; + private findInstanceByPrototypeOrToken(metatypeOrToken); } diff --git a/lib/core/nest-application.d.ts b/lib/core/nest-application.d.ts index 75f55b6caf6..c818c76e613 100644 --- a/lib/core/nest-application.d.ts +++ b/lib/core/nest-application.d.ts @@ -1,51 +1,58 @@ /// import * as http from 'http'; -import { CanActivate, ExceptionFilter, NestInterceptor, PipeTransform, WebSocketAdapter } from '@nestjs/common'; +import { + CanActivate, + ExceptionFilter, + NestInterceptor, + PipeTransform, + WebSocketAdapter +} from '@nestjs/common'; import { INestApplication, INestMicroservice } from '@nestjs/common'; import { MicroserviceConfiguration } from '@nestjs/common/interfaces/microservices/microservice-configuration.interface'; import { NestContainer } from './injector/container'; import { NestApplicationContext } from './nest-application-context'; -export declare class NestApplication extends NestApplicationContext implements INestApplication { - private readonly express; - private readonly logger; - private readonly middlewaresModule; - private readonly middlewaresContainer; - private readonly microservicesModule; - private readonly socketModule; - private readonly httpServer; - private readonly routesResolver; - private readonly config; - private readonly microservices; - private isInitialized; - constructor(container: NestContainer, express: any); - setupModules(): Promise; - init(): Promise; - setupParserMiddlewares(): void; - isMiddlewareApplied(app: any, name: string): boolean; - setupRouter(): Promise; - connectMicroservice(config: MicroserviceConfiguration): INestMicroservice; - getMicroservices(): INestMicroservice[]; - getHttpServer(): http.Server; - startAllMicroservices(callback?: () => void): void; - startAllMicroservicesAsync(): Promise; - use(...args: any[]): void; - set(...args: any[]): void; - listen(port: number, callback?: () => void): any; - listen(port: number, hostname: string, callback?: () => void): any; - listenAsync(port: number, hostname?: string): Promise; - close(): void; - setGlobalPrefix(prefix: string): void; - useWebSocketAdapter(adapter: WebSocketAdapter): void; - useGlobalFilters(...filters: ExceptionFilter[]): void; - useGlobalPipes(...pipes: PipeTransform[]): void; - useGlobalInterceptors(...interceptors: NestInterceptor[]): void; - useGlobalGuards(...guards: CanActivate[]): void; - private setupMiddlewares(instance); - private listenToPromise(microservice); - private callInitHook(); - private callModuleInitHook(module); - private hasOnModuleInitHook(instance); - private callDestroyHook(); - private callModuleDestroyHook(module); - private hasOnModuleDestroyHook(instance); +export declare class NestApplication extends NestApplicationContext + implements INestApplication { + private readonly express; + private readonly logger; + private readonly middlewaresModule; + private readonly middlewaresContainer; + private readonly microservicesModule; + private readonly socketModule; + private readonly httpServer; + private readonly routesResolver; + private readonly config; + private readonly microservices; + private isInitialized; + constructor(container: NestContainer, express: any); + setupModules(): Promise; + init(): Promise; + setupParserMiddlewares(): void; + isMiddlewareApplied(app: any, name: string): boolean; + setupRouter(): Promise; + connectMicroservice(config: MicroserviceConfiguration): INestMicroservice; + getMicroservices(): INestMicroservice[]; + getHttpServer(): http.Server; + startAllMicroservices(callback?: () => void): void; + startAllMicroservicesAsync(): Promise; + use(...args: any[]): void; + set(...args: any[]): void; + listen(port: number, callback?: () => void): any; + listen(port: number, hostname: string, callback?: () => void): any; + listenAsync(port: number, hostname?: string): Promise; + close(): void; + setGlobalPrefix(prefix: string): void; + useWebSocketAdapter(adapter: WebSocketAdapter): void; + useGlobalFilters(...filters: ExceptionFilter[]): void; + useGlobalPipes(...pipes: PipeTransform[]): void; + useGlobalInterceptors(...interceptors: NestInterceptor[]): void; + useGlobalGuards(...guards: CanActivate[]): void; + private setupMiddlewares(instance); + private listenToPromise(microservice); + private callInitHook(); + private callModuleInitHook(module); + private hasOnModuleInitHook(instance); + private callDestroyHook(); + private callModuleDestroyHook(module); + private hasOnModuleDestroyHook(instance); } diff --git a/lib/core/nest-factory.d.ts b/lib/core/nest-factory.d.ts index 821d1e32ea5..e07b586e897 100644 --- a/lib/core/nest-factory.d.ts +++ b/lib/core/nest-factory.d.ts @@ -1,36 +1,43 @@ import { MicroserviceConfiguration } from '@nestjs/common/interfaces/microservices/microservice-configuration.interface'; -import { INestApplication, INestMicroservice, INestApplicationContext } from '@nestjs/common'; +import { + INestApplication, + INestMicroservice, + INestApplicationContext +} from '@nestjs/common'; export declare class NestFactoryStatic { - private container; - private instanceLoader; - private logger; - private dependenciesScanner; - /** - * Creates an instance of the NestApplication (returns Promise) - * - * @param {} module Entry (root) application module class - * @param {} express Optional express() server instance - * @returns an `Promise` of the INestApplication instance - */ - create(module: any, express?: any): Promise; - /** - * Creates an instance of the NestMicroservice (returns Promise) - * - * @param {} module Entry (root) application module class - * @param {MicroserviceConfiguration} config Optional microservice configuration - * @returns an `Promise` of the INestMicroservice instance - */ - createMicroservice(module: any, config?: MicroserviceConfiguration): Promise; - /** - * Creates an instance of the NestApplicationContext (returns Promise) - * - * @param {} module Entry (root) application module class - * @returns an `Promise` of the INestApplicationContext instance - */ - createApplicationContext(module: any): Promise; - private createNestInstance(instance); - private initialize(module); - private createProxy(target); - private createExceptionProxy(); + private container; + private instanceLoader; + private logger; + private dependenciesScanner; + /** + * Creates an instance of the NestApplication (returns Promise) + * + * @param {} module Entry (root) application module class + * @param {} express Optional express() server instance + * @returns an `Promise` of the INestApplication instance + */ + create(module: any, express?: any): Promise; + /** + * Creates an instance of the NestMicroservice (returns Promise) + * + * @param {} module Entry (root) application module class + * @param {MicroserviceConfiguration} config Optional microservice configuration + * @returns an `Promise` of the INestMicroservice instance + */ + createMicroservice( + module: any, + config?: MicroserviceConfiguration + ): Promise; + /** + * Creates an instance of the NestApplicationContext (returns Promise) + * + * @param {} module Entry (root) application module class + * @returns an `Promise` of the INestApplicationContext instance + */ + createApplicationContext(module: any): Promise; + private createNestInstance(instance); + private initialize(module); + private createProxy(target); + private createExceptionProxy(); } export declare const NestFactory: NestFactoryStatic; diff --git a/lib/core/pipes/params-token-factory.d.ts b/lib/core/pipes/params-token-factory.d.ts index 221008b8935..0e44024ff54 100644 --- a/lib/core/pipes/params-token-factory.d.ts +++ b/lib/core/pipes/params-token-factory.d.ts @@ -1,5 +1,5 @@ import { RouteParamtypes } from '@nestjs/common/enums/route-paramtypes.enum'; import { Paramtype } from '@nestjs/common'; export declare class ParamsTokenFactory { - exchangeEnumForString(type: RouteParamtypes): Paramtype; + exchangeEnumForString(type: RouteParamtypes): Paramtype; } diff --git a/lib/core/pipes/pipes-consumer.d.ts b/lib/core/pipes/pipes-consumer.d.ts index 0ab5d8f6d19..8572340ff11 100644 --- a/lib/core/pipes/pipes-consumer.d.ts +++ b/lib/core/pipes/pipes-consumer.d.ts @@ -1,14 +1,30 @@ import { Transform } from '@nestjs/common/interfaces'; export declare class PipesConsumer { - private readonly paramsTokenFactory; - apply(value: any, {metatype, type, data}: { - metatype: any; - type: any; - data: any; - }, transforms: Transform[]): Promise; - applyPipes(value: any, {metatype, type, data}: { - metatype; - type?; - data?; - }, transforms: Transform[]): Promise; + private readonly paramsTokenFactory; + apply( + value: any, + { + metatype, + type, + data + }: { + metatype: any; + type: any; + data: any; + }, + transforms: Transform[] + ): Promise; + applyPipes( + value: any, + { + metatype, + type, + data + }: { + metatype; + type?; + data?; + }, + transforms: Transform[] + ): Promise; } diff --git a/lib/core/pipes/pipes-context-creator.d.ts b/lib/core/pipes/pipes-context-creator.d.ts index f627cb58425..e4c2a4a3e65 100644 --- a/lib/core/pipes/pipes-context-creator.d.ts +++ b/lib/core/pipes/pipes-context-creator.d.ts @@ -3,9 +3,9 @@ import { Controller, Transform } from '@nestjs/common/interfaces'; import { ApplicationConfig } from './../application-config'; import { ContextCreator } from './../helpers/context-creator'; export declare class PipesContextCreator extends ContextCreator { - private readonly config; - constructor(config?: ApplicationConfig); - create(instance: Controller, callback: (...args) => any): Transform[]; - createConcreteContext(metadata: T): R; - getGlobalMetadata(): T; + private readonly config; + constructor(config?: ApplicationConfig); + create(instance: Controller, callback: (...args) => any): Transform[]; + createConcreteContext(metadata: T): R; + getGlobalMetadata(): T; } diff --git a/lib/core/router/interfaces/exceptions-filter.interface.d.ts b/lib/core/router/interfaces/exceptions-filter.interface.d.ts index d2b0809070b..1d48ec311b4 100644 --- a/lib/core/router/interfaces/exceptions-filter.interface.d.ts +++ b/lib/core/router/interfaces/exceptions-filter.interface.d.ts @@ -1,5 +1,5 @@ import { Controller } from '@nestjs/common/interfaces/controllers/controller.interface'; import { ExceptionsHandler } from '../../exceptions/exceptions-handler'; export interface ExceptionsFilter { - create(instance: Controller, callback: any): ExceptionsHandler; + create(instance: Controller, callback: any): ExceptionsHandler; } diff --git a/lib/core/router/interfaces/explorer.inteface.d.ts b/lib/core/router/interfaces/explorer.inteface.d.ts index e70b8064bbc..df934235ed4 100644 --- a/lib/core/router/interfaces/explorer.inteface.d.ts +++ b/lib/core/router/interfaces/explorer.inteface.d.ts @@ -1,6 +1,10 @@ import { Controller } from '@nestjs/common/interfaces/index'; import { Metatype } from '@nestjs/common/interfaces/metatype.interface'; export interface RouterExplorer { - explore(instance: Controller, metatype: Metatype, module: string): any; - fetchRouterPath(metatype: Metatype): string; + explore( + instance: Controller, + metatype: Metatype, + module: string + ): any; + fetchRouterPath(metatype: Metatype): string; } diff --git a/lib/core/router/interfaces/resolver.interface.d.ts b/lib/core/router/interfaces/resolver.interface.d.ts index 9d7b066456a..f88e2ac6d1b 100644 --- a/lib/core/router/interfaces/resolver.interface.d.ts +++ b/lib/core/router/interfaces/resolver.interface.d.ts @@ -1,3 +1,3 @@ export interface Resolver { - resolve(express: any): any; + resolve(express: any): any; } diff --git a/lib/core/router/interfaces/route-params-factory.interface.d.ts b/lib/core/router/interfaces/route-params-factory.interface.d.ts index 7136dfe54b5..1306033c846 100644 --- a/lib/core/router/interfaces/route-params-factory.interface.d.ts +++ b/lib/core/router/interfaces/route-params-factory.interface.d.ts @@ -1,8 +1,16 @@ import { RouteParamtypes } from '@nestjs/common/enums/route-paramtypes.enum'; export interface IRouteParamsFactory { - exchangeKeyForValue(key: RouteParamtypes | string, data: any, {req, res, next}: { - req: any; - res: any; - next: any; - }): any; + exchangeKeyForValue( + key: RouteParamtypes | string, + data: any, + { + req, + res, + next + }: { + req: any; + res: any; + next: any; + } + ): any; } diff --git a/lib/core/router/route-params-factory.d.ts b/lib/core/router/route-params-factory.d.ts index 0c0d4fcc32c..1e14eca5d04 100644 --- a/lib/core/router/route-params-factory.d.ts +++ b/lib/core/router/route-params-factory.d.ts @@ -1,9 +1,17 @@ import { RouteParamtypes } from '@nestjs/common/enums/route-paramtypes.enum'; import { IRouteParamsFactory } from './interfaces/route-params-factory.interface'; export declare class RouteParamsFactory implements IRouteParamsFactory { - exchangeKeyForValue(key: RouteParamtypes | string, data: any, {req, res, next}: { - req: any; - res: any; - next: any; - }): any; + exchangeKeyForValue( + key: RouteParamtypes | string, + data: any, + { + req, + res, + next + }: { + req: any; + res: any; + next: any; + } + ): any; } diff --git a/lib/core/router/router-exception-filters.d.ts b/lib/core/router/router-exception-filters.d.ts index 21387c4e346..b322ce27bb0 100644 --- a/lib/core/router/router-exception-filters.d.ts +++ b/lib/core/router/router-exception-filters.d.ts @@ -5,8 +5,11 @@ import { RouterProxyCallback } from './../router/router-proxy'; import { ApplicationConfig } from './../application-config'; import { BaseExceptionFilterContext } from '../exceptions/base-exception-filter-context'; export declare class RouterExceptionFilters extends BaseExceptionFilterContext { - private readonly config; - constructor(config: ApplicationConfig); - create(instance: Controller, callback: RouterProxyCallback): ExceptionsHandler; - getGlobalMetadata(): T; + private readonly config; + constructor(config: ApplicationConfig); + create( + instance: Controller, + callback: RouterProxyCallback + ): ExceptionsHandler; + getGlobalMetadata(): T; } diff --git a/lib/core/router/router-execution-context.d.ts b/lib/core/router/router-execution-context.d.ts index 87fa6beccf5..45cd8a47a1a 100644 --- a/lib/core/router/router-execution-context.d.ts +++ b/lib/core/router/router-execution-context.d.ts @@ -11,37 +11,68 @@ import { GuardsConsumer } from '../guards/guards-consumer'; import { InterceptorsContextCreator } from '../interceptors/interceptors-context-creator'; import { InterceptorsConsumer } from '../interceptors/interceptors-consumer'; export interface ParamProperties { - index: number; - type: RouteParamtypes | string; - data: ParamData; - pipes: PipeTransform[]; - extractValue: (req, res, next) => any; + index: number; + type: RouteParamtypes | string; + data: ParamData; + pipes: PipeTransform[]; + extractValue: (req, res, next) => any; } export declare class RouterExecutionContext { - private readonly paramsFactory; - private readonly pipesContextCreator; - private readonly pipesConsumer; - private readonly guardsContextCreator; - private readonly guardsConsumer; - private readonly interceptorsContextCreator; - private readonly interceptorsConsumer; - private readonly responseController; - constructor(paramsFactory: IRouteParamsFactory, pipesContextCreator: PipesContextCreator, pipesConsumer: PipesConsumer, guardsContextCreator: GuardsContextCreator, guardsConsumer: GuardsConsumer, interceptorsContextCreator: InterceptorsContextCreator, interceptorsConsumer: InterceptorsConsumer); - create(instance: Controller, callback: (...args) => any, methodName: string, module: string, requestMethod: RequestMethod): (req: any, res: any, next: any) => Promise; - mapParamType(key: string): string; - reflectCallbackMetadata(instance: Controller, methodName: string): RouteParamsMetadata; - reflectCallbackParamtypes(instance: Controller, methodName: string): any[]; - reflectHttpStatusCode(callback: (...args) => any): number; - getArgumentsLength(keys: string[], metadata: RouteParamsMetadata): number; - createNullArray(length: number): any[]; - exchangeKeysForValues(keys: string[], metadata: RouteParamsMetadata): ParamProperties[]; - getCustomFactory(factory: (...args) => void, data: any): (...args) => any; - mergeParamsMetatypes(paramsProperties: ParamProperties[], paramtypes: any[]): (ParamProperties & { - metatype?: any; - })[]; - getParamValue(value: T, {metatype, type, data}: { - metatype: any; - type: any; - data: any; - }, transforms: Transform[]): Promise; + private readonly paramsFactory; + private readonly pipesContextCreator; + private readonly pipesConsumer; + private readonly guardsContextCreator; + private readonly guardsConsumer; + private readonly interceptorsContextCreator; + private readonly interceptorsConsumer; + private readonly responseController; + constructor( + paramsFactory: IRouteParamsFactory, + pipesContextCreator: PipesContextCreator, + pipesConsumer: PipesConsumer, + guardsContextCreator: GuardsContextCreator, + guardsConsumer: GuardsConsumer, + interceptorsContextCreator: InterceptorsContextCreator, + interceptorsConsumer: InterceptorsConsumer + ); + create( + instance: Controller, + callback: (...args) => any, + methodName: string, + module: string, + requestMethod: RequestMethod + ): (req: any, res: any, next: any) => Promise; + mapParamType(key: string): string; + reflectCallbackMetadata( + instance: Controller, + methodName: string + ): RouteParamsMetadata; + reflectCallbackParamtypes(instance: Controller, methodName: string): any[]; + reflectHttpStatusCode(callback: (...args) => any): number; + getArgumentsLength(keys: string[], metadata: RouteParamsMetadata): number; + createNullArray(length: number): any[]; + exchangeKeysForValues( + keys: string[], + metadata: RouteParamsMetadata + ): ParamProperties[]; + getCustomFactory(factory: (...args) => void, data: any): (...args) => any; + mergeParamsMetatypes( + paramsProperties: ParamProperties[], + paramtypes: any[] + ): (ParamProperties & { + metatype?: any; + })[]; + getParamValue( + value: T, + { + metatype, + type, + data + }: { + metatype: any; + type: any; + data: any; + }, + transforms: Transform[] + ): Promise; } diff --git a/lib/core/router/router-explorer.d.ts b/lib/core/router/router-explorer.d.ts index e2f9367a0f0..eec86416b81 100644 --- a/lib/core/router/router-explorer.d.ts +++ b/lib/core/router/router-explorer.d.ts @@ -10,27 +10,53 @@ import { MetadataScanner } from '../metadata-scanner'; import { ApplicationConfig } from './../application-config'; import { NestContainer } from '../injector/container'; export declare class ExpressRouterExplorer implements RouterExplorer { - private readonly metadataScanner; - private readonly routerProxy; - private readonly expressAdapter; - private readonly exceptionsFilter; - private readonly config; - private readonly executionContextCreator; - private readonly routerMethodFactory; - private readonly logger; - constructor(metadataScanner?: MetadataScanner, routerProxy?: RouterProxy, expressAdapter?: ExpressAdapter, exceptionsFilter?: ExceptionsFilter, config?: ApplicationConfig, container?: NestContainer); - explore(instance: Controller, metatype: Metatype, module: string): any; - fetchRouterPath(metatype: Metatype): string; - validateRoutePath(path: string): string; - scanForPaths(instance: Controller, prototype?: any): RoutePathProperties[]; - exploreMethodMetadata(instance: Controller, instancePrototype: any, methodName: string): RoutePathProperties; - applyPathsToRouterProxy(router: any, routePaths: RoutePathProperties[], instance: Controller, module: string): void; - private applyCallbackToRouter(router, pathProperties, instance, module); - private createCallbackProxy(instance, callback, methodName, module, requestMethod); + private readonly metadataScanner; + private readonly routerProxy; + private readonly expressAdapter; + private readonly exceptionsFilter; + private readonly config; + private readonly executionContextCreator; + private readonly routerMethodFactory; + private readonly logger; + constructor( + metadataScanner?: MetadataScanner, + routerProxy?: RouterProxy, + expressAdapter?: ExpressAdapter, + exceptionsFilter?: ExceptionsFilter, + config?: ApplicationConfig, + container?: NestContainer + ); + explore( + instance: Controller, + metatype: Metatype, + module: string + ): any; + fetchRouterPath(metatype: Metatype): string; + validateRoutePath(path: string): string; + scanForPaths(instance: Controller, prototype?: any): RoutePathProperties[]; + exploreMethodMetadata( + instance: Controller, + instancePrototype: any, + methodName: string + ): RoutePathProperties; + applyPathsToRouterProxy( + router: any, + routePaths: RoutePathProperties[], + instance: Controller, + module: string + ): void; + private applyCallbackToRouter(router, pathProperties, instance, module); + private createCallbackProxy( + instance, + callback, + methodName, + module, + requestMethod + ); } export interface RoutePathProperties { - path: string; - requestMethod: RequestMethod; - targetCallback: RouterProxyCallback; - methodName: string; + path: string; + requestMethod: RequestMethod; + targetCallback: RouterProxyCallback; + methodName: string; } diff --git a/lib/core/router/router-proxy.d.ts b/lib/core/router/router-proxy.d.ts index e97414bb7e6..900d71130b4 100644 --- a/lib/core/router/router-proxy.d.ts +++ b/lib/core/router/router-proxy.d.ts @@ -1,6 +1,12 @@ import { ExceptionsHandler } from '../exceptions/exceptions-handler'; export declare type RouterProxyCallback = (req?, res?, next?) => void; export declare class RouterProxy { - createProxy(targetCallback: RouterProxyCallback, exceptionsHandler: ExceptionsHandler): (req: any, res: any, next: any) => void; - createExceptionLayerProxy(targetCallback: (err, req, res, next) => void, exceptionsHandler: ExceptionsHandler): (err: any, req: any, res: any, next: any) => void; + createProxy( + targetCallback: RouterProxyCallback, + exceptionsHandler: ExceptionsHandler + ): (req: any, res: any, next: any) => void; + createExceptionLayerProxy( + targetCallback: (err, req, res, next) => void, + exceptionsHandler: ExceptionsHandler + ): (err: any, req: any, res: any, next: any) => void; } diff --git a/lib/core/router/router-response-controller.d.ts b/lib/core/router/router-response-controller.d.ts index ba2047d4e34..27817ec354a 100644 --- a/lib/core/router/router-response-controller.d.ts +++ b/lib/core/router/router-response-controller.d.ts @@ -1,7 +1,12 @@ import { RequestMethod } from '@nestjs/common'; import 'rxjs/add/operator/toPromise'; export declare class RouterResponseController { - apply(resultOrDeffered: any, response: any, requestMethod: RequestMethod, httpCode: number): Promise; - transformToResult(resultOrDeffered: any): Promise; - getStatusByMethod(requestMethod: RequestMethod): number; + apply( + resultOrDeffered: any, + response: any, + requestMethod: RequestMethod, + httpCode: number + ): Promise; + transformToResult(resultOrDeffered: any): Promise; + getStatusByMethod(requestMethod: RequestMethod): number; } diff --git a/lib/core/router/routes-resolver.d.ts b/lib/core/router/routes-resolver.d.ts index 1573adb9816..8f938607ffd 100644 --- a/lib/core/router/routes-resolver.d.ts +++ b/lib/core/router/routes-resolver.d.ts @@ -5,16 +5,24 @@ import { Controller } from '@nestjs/common/interfaces/controllers/controller.int import { Resolver } from './interfaces/resolver.interface'; import { ApplicationConfig } from './../application-config'; export declare class RoutesResolver implements Resolver { - private readonly container; - private readonly expressAdapter; - private readonly config; - private readonly logger; - private readonly routerProxy; - private readonly routerExceptionsFilter; - private readonly routerBuilder; - constructor(container: NestContainer, expressAdapter: any, config: ApplicationConfig); - resolve(express: Application): void; - setupRouters(routes: Map>, moduleName: string, express: Application): void; - setupNotFoundHandler(express: Application): void; - setupExceptionHandler(express: Application): void; + private readonly container; + private readonly expressAdapter; + private readonly config; + private readonly logger; + private readonly routerProxy; + private readonly routerExceptionsFilter; + private readonly routerBuilder; + constructor( + container: NestContainer, + expressAdapter: any, + config: ApplicationConfig + ); + resolve(express: Application): void; + setupRouters( + routes: Map>, + moduleName: string, + express: Application + ): void; + setupNotFoundHandler(express: Application): void; + setupExceptionHandler(express: Application): void; } diff --git a/lib/core/scanner.d.ts b/lib/core/scanner.d.ts index 8651f793485..24beab493e1 100644 --- a/lib/core/scanner.d.ts +++ b/lib/core/scanner.d.ts @@ -7,27 +7,43 @@ import { Metatype } from '@nestjs/common/interfaces/metatype.interface'; import { MetadataScanner } from '../core/metadata-scanner'; import { DynamicModule } from '@nestjs/common'; export declare class DependenciesScanner { - private readonly container; - private readonly metadataScanner; - constructor(container: NestContainer, metadataScanner: MetadataScanner); - scan(module: NestModuleMetatype): void; - scanForModules(module: NestModuleMetatype | DynamicModule, scope?: NestModuleMetatype[]): void; - storeModule(module: any, scope: NestModuleMetatype[]): void; - scanModulesForDependencies(): void; - reflectRelatedModules(module: NestModuleMetatype, token: string): void; - reflectComponents(module: NestModuleMetatype, token: string): void; - reflectComponentMetadata(component: Metatype, token: string): void; - reflectControllers(module: NestModuleMetatype, token: string): void; - reflectDynamicMetadata(obj: Metatype, token: string): void; - reflectExports(module: NestModuleMetatype, token: string): void; - reflectGatewaysMiddlewares(component: Metatype, token: string): void; - reflectGuards(component: Metatype, token: string): void; - reflectInterceptors(component: Metatype, token: string): void; - reflectKeyMetadata(component: Metatype, key: string, method: string): any; - storeRelatedModule(related: any, token: string): void; - storeComponent(component: Metatype, token: string): void; - storeInjectable(component: Metatype, token: string): void; - storeExportedComponent(exportedComponent: Metatype, token: string): void; - storeRoute(route: Metatype, token: string): void; - reflectMetadata(metatype: any, metadata: string): any; + private readonly container; + private readonly metadataScanner; + constructor(container: NestContainer, metadataScanner: MetadataScanner); + scan(module: NestModuleMetatype): void; + scanForModules( + module: NestModuleMetatype | DynamicModule, + scope?: NestModuleMetatype[] + ): void; + storeModule(module: any, scope: NestModuleMetatype[]): void; + scanModulesForDependencies(): void; + reflectRelatedModules(module: NestModuleMetatype, token: string): void; + reflectComponents(module: NestModuleMetatype, token: string): void; + reflectComponentMetadata( + component: Metatype, + token: string + ): void; + reflectControllers(module: NestModuleMetatype, token: string): void; + reflectDynamicMetadata(obj: Metatype, token: string): void; + reflectExports(module: NestModuleMetatype, token: string): void; + reflectGatewaysMiddlewares( + component: Metatype, + token: string + ): void; + reflectGuards(component: Metatype, token: string): void; + reflectInterceptors(component: Metatype, token: string): void; + reflectKeyMetadata( + component: Metatype, + key: string, + method: string + ): any; + storeRelatedModule(related: any, token: string): void; + storeComponent(component: Metatype, token: string): void; + storeInjectable(component: Metatype, token: string): void; + storeExportedComponent( + exportedComponent: Metatype, + token: string + ): void; + storeRoute(route: Metatype, token: string): void; + reflectMetadata(metatype: any, metadata: string): any; } diff --git a/lib/core/services/reflector.service.d.ts b/lib/core/services/reflector.service.d.ts index 2a175378a8c..a6e96a6ce66 100644 --- a/lib/core/services/reflector.service.d.ts +++ b/lib/core/services/reflector.service.d.ts @@ -1,3 +1,3 @@ export declare class Reflector { - get(metadataKey: any, target: any): T; + get(metadataKey: any, target: any): T; } diff --git a/lib/microservices/client/client-proxy-factory.d.ts b/lib/microservices/client/client-proxy-factory.d.ts index 1afa50f4734..7b05797f02f 100644 --- a/lib/microservices/client/client-proxy-factory.d.ts +++ b/lib/microservices/client/client-proxy-factory.d.ts @@ -2,5 +2,5 @@ import { ClientMetadata } from '../interfaces/client-metadata.interface'; import { ClientProxy } from './client-proxy'; import { Closeable } from '../interfaces/closeable.interface'; export declare class ClientProxyFactory { - static create(metadata: ClientMetadata): ClientProxy & Closeable; + static create(metadata: ClientMetadata): ClientProxy & Closeable; } diff --git a/lib/microservices/client/client-proxy.d.ts b/lib/microservices/client/client-proxy.d.ts index 344d81ad736..5b83c08206c 100644 --- a/lib/microservices/client/client-proxy.d.ts +++ b/lib/microservices/client/client-proxy.d.ts @@ -1,7 +1,12 @@ import { Observable } from 'rxjs/Observable'; import { Observer } from 'rxjs/Observer'; -export declare abstract class ClientProxy { - protected abstract sendSingleMessage(msg: any, callback: (err, result, disposed?: boolean) => void): any; - send(pattern: any, data: any): Observable; - protected createObserver(observer: Observer): (err, result, disposed?: boolean) => void; +export abstract class ClientProxy { + protected abstract sendSingleMessage( + msg: any, + callback: (err, result, disposed?: boolean) => void + ): any; + send(pattern: any, data: any): Observable; + protected createObserver( + observer: Observer + ): (err, result, disposed?: boolean) => void; } diff --git a/lib/microservices/client/client-redis.d.ts b/lib/microservices/client/client-redis.d.ts index 28a06506981..a26bf940fd7 100644 --- a/lib/microservices/client/client-redis.d.ts +++ b/lib/microservices/client/client-redis.d.ts @@ -2,16 +2,19 @@ import * as redis from 'redis'; import { ClientProxy } from './client-proxy'; import { ClientMetadata } from '../interfaces/client-metadata.interface'; export declare class ClientRedis extends ClientProxy { - private readonly logger; - private readonly url; - private pub; - private sub; - constructor(metadata: ClientMetadata); - protected sendSingleMessage(msg: any, callback: (...args) => any): (channel: any, message: any) => void; - getAckPatternName(pattern: string): string; - getResPatternName(pattern: string): string; - close(): void; - init(callback: (...args) => any): void; - createClient(): redis.RedisClient; - handleErrors(stream: any, callback: (...args) => any): void; + private readonly logger; + private readonly url; + private pub; + private sub; + constructor(metadata: ClientMetadata); + protected sendSingleMessage( + msg: any, + callback: (...args) => any + ): (channel: any, message: any) => void; + getAckPatternName(pattern: string): string; + getResPatternName(pattern: string): string; + close(): void; + init(callback: (...args) => any): void; + createClient(): redis.RedisClient; + handleErrors(stream: any, callback: (...args) => any): void; } diff --git a/lib/microservices/client/client-tcp.d.ts b/lib/microservices/client/client-tcp.d.ts index 1c2d1231ae8..044c01e7737 100644 --- a/lib/microservices/client/client-tcp.d.ts +++ b/lib/microservices/client/client-tcp.d.ts @@ -1,16 +1,19 @@ import { ClientProxy } from './client-proxy'; import { ClientMetadata } from '../interfaces/client-metadata.interface'; export declare class ClientTCP extends ClientProxy { - private readonly logger; - private readonly port; - private readonly host; - private isConnected; - private socket; - constructor({port, host}: ClientMetadata); - init(callback: (...args) => any): Promise<{}>; - protected sendSingleMessage(msg: any, callback: (...args) => any): Promise; - handleResponse(socket: any, callback: (...args) => any, buffer: any): void; - createSocket(): any; - close(): void; - bindEvents(socket: any, callback: (...args) => any): void; + private readonly logger; + private readonly port; + private readonly host; + private isConnected; + private socket; + constructor({ port, host }: ClientMetadata); + init(callback: (...args) => any): Promise<{}>; + protected sendSingleMessage( + msg: any, + callback: (...args) => any + ): Promise; + handleResponse(socket: any, callback: (...args) => any, buffer: any): void; + createSocket(): any; + close(): void; + bindEvents(socket: any, callback: (...args) => any): void; } diff --git a/lib/microservices/constants.d.ts b/lib/microservices/constants.d.ts index 37916977e6f..8b09c49f15c 100644 --- a/lib/microservices/constants.d.ts +++ b/lib/microservices/constants.d.ts @@ -1,5 +1,5 @@ -export declare const PATTERN_METADATA = "pattern"; -export declare const CLIENT_CONFIGURATION_METADATA = "client"; -export declare const CLIENT_METADATA = "__isClient"; -export declare const PATTERN_HANDLER_METADATA = "__isPattern"; +export declare const PATTERN_METADATA = 'pattern'; +export declare const CLIENT_CONFIGURATION_METADATA = 'client'; +export declare const CLIENT_METADATA = '__isClient'; +export declare const PATTERN_HANDLER_METADATA = '__isPattern'; export declare const NO_PATTERN_MESSAGE: string; diff --git a/lib/microservices/container.d.ts b/lib/microservices/container.d.ts index 8760c769be6..53380b20171 100644 --- a/lib/microservices/container.d.ts +++ b/lib/microservices/container.d.ts @@ -2,8 +2,8 @@ import { ClientProxy } from './index'; import { Closeable } from './interfaces/closeable.interface'; export declare type CloseableClient = Closeable & ClientProxy; export declare class ClientsContainer { - private clients; - getAllClients(): CloseableClient[]; - addClient(client: CloseableClient): void; - clear(): void; + private clients; + getAllClients(): CloseableClient[]; + addClient(client: CloseableClient): void; + clear(): void; } diff --git a/lib/microservices/context/exception-filters-context.d.ts b/lib/microservices/context/exception-filters-context.d.ts index c626cb18891..e038876cd44 100644 --- a/lib/microservices/context/exception-filters-context.d.ts +++ b/lib/microservices/context/exception-filters-context.d.ts @@ -5,8 +5,11 @@ import { RpcExceptionsHandler } from '../exceptions/rpc-exceptions-handler'; import { BaseExceptionFilterContext } from '@nestjs/core/exceptions/base-exception-filter-context'; import { ApplicationConfig } from '@nestjs/core/application-config'; export declare class ExceptionFiltersContext extends BaseExceptionFilterContext { - private readonly config; - constructor(config: ApplicationConfig); - create(instance: Controller, callback: (data) => Observable): RpcExceptionsHandler; - getGlobalMetadata(): T; + private readonly config; + constructor(config: ApplicationConfig); + create( + instance: Controller, + callback: (data) => Observable + ): RpcExceptionsHandler; + getGlobalMetadata(): T; } diff --git a/lib/microservices/context/rpc-context-creator.d.ts b/lib/microservices/context/rpc-context-creator.d.ts index e6126b3a65d..ff8efbfdee6 100644 --- a/lib/microservices/context/rpc-context-creator.d.ts +++ b/lib/microservices/context/rpc-context-creator.d.ts @@ -9,16 +9,32 @@ import { GuardsConsumer } from '@nestjs/core/guards/guards-consumer'; import { InterceptorsContextCreator } from '@nestjs/core/interceptors/interceptors-context-creator'; import { InterceptorsConsumer } from '@nestjs/core/interceptors/interceptors-consumer'; export declare class RpcContextCreator { - private readonly rpcProxy; - private readonly exceptionFiltersContext; - private readonly pipesCreator; - private readonly pipesConsumer; - private readonly guardsContextCreator; - private readonly guardsConsumer; - private readonly interceptorsContextCreator; - private readonly interceptorsConsumer; - constructor(rpcProxy: RpcProxy, exceptionFiltersContext: ExceptionFiltersContext, pipesCreator: PipesContextCreator, pipesConsumer: PipesConsumer, guardsContextCreator: GuardsContextCreator, guardsConsumer: GuardsConsumer, interceptorsContextCreator: InterceptorsContextCreator, interceptorsConsumer: InterceptorsConsumer); - create(instance: Controller, callback: (data) => Observable, module: any): (data) => Promise>; - reflectCallbackParamtypes(instance: Controller, callback: (...args) => any): any[]; - getDataMetatype(instance: any, callback: any): any; + private readonly rpcProxy; + private readonly exceptionFiltersContext; + private readonly pipesCreator; + private readonly pipesConsumer; + private readonly guardsContextCreator; + private readonly guardsConsumer; + private readonly interceptorsContextCreator; + private readonly interceptorsConsumer; + constructor( + rpcProxy: RpcProxy, + exceptionFiltersContext: ExceptionFiltersContext, + pipesCreator: PipesContextCreator, + pipesConsumer: PipesConsumer, + guardsContextCreator: GuardsContextCreator, + guardsConsumer: GuardsConsumer, + interceptorsContextCreator: InterceptorsContextCreator, + interceptorsConsumer: InterceptorsConsumer + ); + create( + instance: Controller, + callback: (data) => Observable, + module: any + ): (data) => Promise>; + reflectCallbackParamtypes( + instance: Controller, + callback: (...args) => any + ): any[]; + getDataMetatype(instance: any, callback: any): any; } diff --git a/lib/microservices/context/rpc-proxy.d.ts b/lib/microservices/context/rpc-proxy.d.ts index 1865dd669e2..7b2ca54ef85 100644 --- a/lib/microservices/context/rpc-proxy.d.ts +++ b/lib/microservices/context/rpc-proxy.d.ts @@ -1,5 +1,8 @@ import { Observable } from 'rxjs/Observable'; import { RpcExceptionsHandler } from '../exceptions/rpc-exceptions-handler'; export declare class RpcProxy { - create(targetCallback: (data) => Promise>, exceptionsHandler: RpcExceptionsHandler): (data) => Promise>; + create( + targetCallback: (data) => Promise>, + exceptionsHandler: RpcExceptionsHandler + ): (data) => Promise>; } diff --git a/lib/microservices/enums/transport.enum.d.ts b/lib/microservices/enums/transport.enum.d.ts index 5f116ab7c12..9de93a8b408 100644 --- a/lib/microservices/enums/transport.enum.d.ts +++ b/lib/microservices/enums/transport.enum.d.ts @@ -1,4 +1,4 @@ export declare enum Transport { - TCP = 0, - REDIS = 1, + TCP = 0, + REDIS = 1 } diff --git a/lib/microservices/exceptions/invalid-message.exception.d.ts b/lib/microservices/exceptions/invalid-message.exception.d.ts index 0bf90a240f5..c139da9e63e 100644 --- a/lib/microservices/exceptions/invalid-message.exception.d.ts +++ b/lib/microservices/exceptions/invalid-message.exception.d.ts @@ -1,4 +1,4 @@ import { RuntimeException } from '@nestjs/core/errors/exceptions/runtime.exception'; export declare class InvalidMessageException extends RuntimeException { - constructor(); + constructor(); } diff --git a/lib/microservices/exceptions/rpc-exception.d.ts b/lib/microservices/exceptions/rpc-exception.d.ts index 8a8f8d28617..db5d799f602 100644 --- a/lib/microservices/exceptions/rpc-exception.d.ts +++ b/lib/microservices/exceptions/rpc-exception.d.ts @@ -1,5 +1,5 @@ export declare class RpcException { - private readonly error; - constructor(error: string | object); - getError(): string | object; + private readonly error; + constructor(error: string | object); + getError(): string | object; } diff --git a/lib/microservices/exceptions/rpc-exceptions-handler.d.ts b/lib/microservices/exceptions/rpc-exceptions-handler.d.ts index fed9e6429e6..0dff40f86f8 100644 --- a/lib/microservices/exceptions/rpc-exceptions-handler.d.ts +++ b/lib/microservices/exceptions/rpc-exceptions-handler.d.ts @@ -3,9 +3,9 @@ import { RpcException } from './rpc-exception'; import { RpcExceptionFilterMetadata } from '@nestjs/common/interfaces/exceptions'; import 'rxjs/add/observable/throw'; export declare class RpcExceptionsHandler { - private static readonly logger; - private filters; - handle(exception: Error | RpcException | any): Observable; - setCustomFilters(filters: RpcExceptionFilterMetadata[]): void; - invokeCustomFilters(exception: any): Observable | null; + private static readonly logger; + private filters; + handle(exception: Error | RpcException | any): Observable; + setCustomFilters(filters: RpcExceptionFilterMetadata[]): void; + invokeCustomFilters(exception: any): Observable | null; } diff --git a/lib/microservices/interfaces/client-metadata.interface.d.ts b/lib/microservices/interfaces/client-metadata.interface.d.ts index 6a9ccb04755..5ae88508a06 100644 --- a/lib/microservices/interfaces/client-metadata.interface.d.ts +++ b/lib/microservices/interfaces/client-metadata.interface.d.ts @@ -1,7 +1,7 @@ import { Transport } from './../enums/transport.enum'; export interface ClientMetadata { - transport?: Transport; - url?: string; - port?: number; - host?: string; + transport?: Transport; + url?: string; + port?: number; + host?: string; } diff --git a/lib/microservices/interfaces/closeable.interface.d.ts b/lib/microservices/interfaces/closeable.interface.d.ts index 45097299a8a..a5cc2c694db 100644 --- a/lib/microservices/interfaces/closeable.interface.d.ts +++ b/lib/microservices/interfaces/closeable.interface.d.ts @@ -1,3 +1,3 @@ export interface Closeable { - close(): void; + close(): void; } diff --git a/lib/microservices/interfaces/custom-transport-strategy.interface.d.ts b/lib/microservices/interfaces/custom-transport-strategy.interface.d.ts index b743506b902..15072dab2f7 100644 --- a/lib/microservices/interfaces/custom-transport-strategy.interface.d.ts +++ b/lib/microservices/interfaces/custom-transport-strategy.interface.d.ts @@ -1,4 +1,4 @@ export interface CustomTransportStrategy { - listen(callback: () => void): any; - close(): any; + listen(callback: () => void): any; + close(): any; } diff --git a/lib/microservices/interfaces/message-handlers.interface.d.ts b/lib/microservices/interfaces/message-handlers.interface.d.ts index 9131cce636f..60b434f4eda 100644 --- a/lib/microservices/interfaces/message-handlers.interface.d.ts +++ b/lib/microservices/interfaces/message-handlers.interface.d.ts @@ -1,4 +1,4 @@ import { Observable } from 'rxjs/Observable'; export interface MessageHandlers { - [pattern: string]: (data) => Promise>; + [pattern: string]: (data) => Promise>; } diff --git a/lib/microservices/interfaces/microservice-configuration.interface.d.ts b/lib/microservices/interfaces/microservice-configuration.interface.d.ts index 0d515554d8f..2c31d991cb1 100644 --- a/lib/microservices/interfaces/microservice-configuration.interface.d.ts +++ b/lib/microservices/interfaces/microservice-configuration.interface.d.ts @@ -2,9 +2,9 @@ import { Transport } from '../enums/transport.enum'; import { CustomTransportStrategy } from './custom-transport-strategy.interface'; import { Server } from './../server/server'; export interface MicroserviceConfiguration { - transport?: Transport; - url?: string; - port?: number; - host?: string; - strategy?: Server & CustomTransportStrategy; + transport?: Transport; + url?: string; + port?: number; + host?: string; + strategy?: Server & CustomTransportStrategy; } diff --git a/lib/microservices/interfaces/microservice-response.interface.d.ts b/lib/microservices/interfaces/microservice-response.interface.d.ts index 9040f00b60f..6ea59c3b46d 100644 --- a/lib/microservices/interfaces/microservice-response.interface.d.ts +++ b/lib/microservices/interfaces/microservice-response.interface.d.ts @@ -1,5 +1,5 @@ export interface MicroserviceResponse { - response?: any; - err?: any; - disposed?: boolean; + response?: any; + err?: any; + disposed?: boolean; } diff --git a/lib/microservices/interfaces/pattern-metadata.interface.d.ts b/lib/microservices/interfaces/pattern-metadata.interface.d.ts index 817171de21d..7c440634542 100644 --- a/lib/microservices/interfaces/pattern-metadata.interface.d.ts +++ b/lib/microservices/interfaces/pattern-metadata.interface.d.ts @@ -1,3 +1,3 @@ export interface PatternMetadata { - [prop: string]: any; + [prop: string]: any; } diff --git a/lib/microservices/listener-metadata-explorer.d.ts b/lib/microservices/listener-metadata-explorer.d.ts index cf926686683..8964d12ae84 100644 --- a/lib/microservices/listener-metadata-explorer.d.ts +++ b/lib/microservices/listener-metadata-explorer.d.ts @@ -3,17 +3,21 @@ import { PatternMetadata } from './interfaces/pattern-metadata.interface'; import { ClientMetadata } from './interfaces/client-metadata.interface'; import { MetadataScanner } from '@nestjs/core/metadata-scanner'; export declare class ListenerMetadataExplorer { - private readonly metadataScanner; - constructor(metadataScanner: MetadataScanner); - explore(instance: Controller): PatternProperties[]; - exploreMethodMetadata(instance: any, instancePrototype: any, methodName: string): PatternProperties; - scanForClientHooks(instance: Controller): IterableIterator; + private readonly metadataScanner; + constructor(metadataScanner: MetadataScanner); + explore(instance: Controller): PatternProperties[]; + exploreMethodMetadata( + instance: any, + instancePrototype: any, + methodName: string + ): PatternProperties; + scanForClientHooks(instance: Controller): IterableIterator; } export interface ClientProperties { - property: string; - metadata: ClientMetadata; + property: string; + metadata: ClientMetadata; } export interface PatternProperties { - pattern: PatternMetadata; - targetCallback: (...args) => any; + pattern: PatternMetadata; + targetCallback: (...args) => any; } diff --git a/lib/microservices/listeners-controller.d.ts b/lib/microservices/listeners-controller.d.ts index 4e48632bb89..d7ff6cae009 100644 --- a/lib/microservices/listeners-controller.d.ts +++ b/lib/microservices/listeners-controller.d.ts @@ -5,10 +5,17 @@ import { CustomTransportStrategy } from './interfaces'; import { ClientsContainer } from './container'; import { RpcContextCreator } from './context/rpc-context-creator'; export declare class ListenersController { - private readonly clientsContainer; - private readonly contextCreator; - private readonly metadataExplorer; - constructor(clientsContainer: ClientsContainer, contextCreator: RpcContextCreator); - bindPatternHandlers(instance: Controller, server: Server & CustomTransportStrategy, module: string): void; - bindClientsToProperties(instance: Controller): void; + private readonly clientsContainer; + private readonly contextCreator; + private readonly metadataExplorer; + constructor( + clientsContainer: ClientsContainer, + contextCreator: RpcContextCreator + ); + bindPatternHandlers( + instance: Controller, + server: Server & CustomTransportStrategy, + module: string + ): void; + bindClientsToProperties(instance: Controller): void; } diff --git a/lib/microservices/microservices-module.d.ts b/lib/microservices/microservices-module.d.ts index 81cd8d6b5f5..0d98cc44772 100644 --- a/lib/microservices/microservices-module.d.ts +++ b/lib/microservices/microservices-module.d.ts @@ -3,12 +3,19 @@ import { Controller } from '@nestjs/common/interfaces/controllers/controller.int import { CustomTransportStrategy } from './interfaces'; import { Server } from './server/server'; export declare class MicroservicesModule { - private readonly clientsContainer; - private listenersController; - setup(container: any, config: any): void; - setupListeners(container: any, server: Server & CustomTransportStrategy): void; - setupClients(container: any): void; - bindListeners(controllers: Map>, server: Server & CustomTransportStrategy, module: string): void; - bindClients(controllers: Map>): void; - close(): void; + private readonly clientsContainer; + private listenersController; + setup(container: any, config: any): void; + setupListeners( + container: any, + server: Server & CustomTransportStrategy + ): void; + setupClients(container: any): void; + bindListeners( + controllers: Map>, + server: Server & CustomTransportStrategy, + module: string + ): void; + bindClients(controllers: Map>): void; + close(): void; } diff --git a/lib/microservices/nest-microservice.d.ts b/lib/microservices/nest-microservice.d.ts index b216d98d2f9..9f7a58d5edd 100644 --- a/lib/microservices/nest-microservice.d.ts +++ b/lib/microservices/nest-microservice.d.ts @@ -1,35 +1,42 @@ import { NestContainer } from '@nestjs/core/injector/container'; import { MicroserviceConfiguration } from './interfaces/microservice-configuration.interface'; -import { INestMicroservice, WebSocketAdapter, CanActivate, PipeTransform, NestInterceptor, ExceptionFilter } from '@nestjs/common'; +import { + INestMicroservice, + WebSocketAdapter, + CanActivate, + PipeTransform, + NestInterceptor, + ExceptionFilter +} from '@nestjs/common'; export declare class NestMicroservice implements INestMicroservice { - private readonly container; - private readonly logger; - private readonly microservicesModule; - private readonly socketModule; - private readonly microserviceConfig; - private readonly server; - private readonly config; - private isTerminated; - private isInitialized; - private isInitHookCalled; - constructor(container: NestContainer, config?: MicroserviceConfiguration); - setupModules(): void; - setupListeners(): void; - useWebSocketAdapter(adapter: WebSocketAdapter): void; - useGlobalFilters(...filters: ExceptionFilter[]): void; - useGlobalPipes(...pipes: PipeTransform[]): void; - useGlobalInterceptors(...interceptors: NestInterceptor[]): void; - useGlobalGuards(...guards: CanActivate[]): void; - listen(callback: () => void): void; - close(): void; - setIsInitialized(isInitialized: boolean): void; - setIsTerminated(isTerminaed: boolean): void; - setIsInitHookCalled(isInitHookCalled: boolean): void; - private closeApplication(); - private callInitHook(); - private callModuleInitHook(module); - private hasOnModuleInitHook(instance); - private callDestroyHook(); - private callModuleDestroyHook(module); - private hasOnModuleDestroyHook(instance); + private readonly container; + private readonly logger; + private readonly microservicesModule; + private readonly socketModule; + private readonly microserviceConfig; + private readonly server; + private readonly config; + private isTerminated; + private isInitialized; + private isInitHookCalled; + constructor(container: NestContainer, config?: MicroserviceConfiguration); + setupModules(): void; + setupListeners(): void; + useWebSocketAdapter(adapter: WebSocketAdapter): void; + useGlobalFilters(...filters: ExceptionFilter[]): void; + useGlobalPipes(...pipes: PipeTransform[]): void; + useGlobalInterceptors(...interceptors: NestInterceptor[]): void; + useGlobalGuards(...guards: CanActivate[]): void; + listen(callback: () => void): void; + close(): void; + setIsInitialized(isInitialized: boolean): void; + setIsTerminated(isTerminaed: boolean): void; + setIsInitHookCalled(isInitHookCalled: boolean): void; + private closeApplication(); + private callInitHook(); + private callModuleInitHook(module); + private hasOnModuleInitHook(instance); + private callDestroyHook(); + private callModuleDestroyHook(module); + private hasOnModuleDestroyHook(instance); } diff --git a/lib/microservices/server/server-factory.d.ts b/lib/microservices/server/server-factory.d.ts index be4251a337f..1d8654bf688 100644 --- a/lib/microservices/server/server-factory.d.ts +++ b/lib/microservices/server/server-factory.d.ts @@ -1,5 +1,10 @@ -import { MicroserviceConfiguration, CustomTransportStrategy } from '../interfaces'; +import { + MicroserviceConfiguration, + CustomTransportStrategy +} from '../interfaces'; import { Server } from './server'; export declare class ServerFactory { - static create(config: MicroserviceConfiguration): Server & CustomTransportStrategy; + static create( + config: MicroserviceConfiguration + ): Server & CustomTransportStrategy; } diff --git a/lib/microservices/server/server-redis.d.ts b/lib/microservices/server/server-redis.d.ts index 419d2e755c4..9fca204756d 100644 --- a/lib/microservices/server/server-redis.d.ts +++ b/lib/microservices/server/server-redis.d.ts @@ -5,21 +5,22 @@ import { CustomTransportStrategy } from './../interfaces'; import 'rxjs/add/operator/catch'; import 'rxjs/add/observable/empty'; import 'rxjs/add/operator/finally'; -export declare class ServerRedis extends Server implements CustomTransportStrategy { - private readonly url; - private sub; - private pub; - constructor(config: MicroserviceConfiguration); - listen(callback: () => void): void; - start(callback?: () => void): void; - close(): void; - createRedisClient(): redis.RedisClient; - handleConnection(callback: any, sub: any, pub: any): void; - getMessageHandler(pub: any): (channel: any, buffer: any) => Promise; - handleMessage(channel: any, buffer: any, pub: any): Promise; - getPublisher(pub: any, pattern: any): (respond: any) => void; - tryParse(content: any): any; - getAckQueueName(pattern: any): string; - getResQueueName(pattern: any): string; - handleErrors(stream: any): void; +export declare class ServerRedis extends Server + implements CustomTransportStrategy { + private readonly url; + private sub; + private pub; + constructor(config: MicroserviceConfiguration); + listen(callback: () => void): void; + start(callback?: () => void): void; + close(): void; + createRedisClient(): redis.RedisClient; + handleConnection(callback: any, sub: any, pub: any): void; + getMessageHandler(pub: any): (channel: any, buffer: any) => Promise; + handleMessage(channel: any, buffer: any, pub: any): Promise; + getPublisher(pub: any, pattern: any): (respond: any) => void; + tryParse(content: any): any; + getAckQueueName(pattern: any): string; + getResQueueName(pattern: any): string; + handleErrors(stream: any): void; } diff --git a/lib/microservices/server/server-tcp.d.ts b/lib/microservices/server/server-tcp.d.ts index c94b29ad082..84a1d3d4ae1 100644 --- a/lib/microservices/server/server-tcp.d.ts +++ b/lib/microservices/server/server-tcp.d.ts @@ -3,17 +3,21 @@ import { CustomTransportStrategy } from './../interfaces'; import 'rxjs/add/operator/catch'; import 'rxjs/add/observable/empty'; import 'rxjs/add/operator/finally'; -export declare class ServerTCP extends Server implements CustomTransportStrategy { - private readonly port; - private server; - constructor(config: any); - listen(callback: () => void): void; - close(): void; - bindHandler(socket: any): void; - handleMessage(socket: any, msg: { - pattern: any; - data: {}; - }): Promise; - private init(); - private getSocketInstance(socket); +export declare class ServerTCP extends Server + implements CustomTransportStrategy { + private readonly port; + private server; + constructor(config: any); + listen(callback: () => void): void; + close(): void; + bindHandler(socket: any): void; + handleMessage( + socket: any, + msg: { + pattern: any; + data: {}; + } + ): Promise; + private init(); + private getSocketInstance(socket); } diff --git a/lib/microservices/server/server.d.ts b/lib/microservices/server/server.d.ts index 22c7a10dd42..e0b6083fd10 100644 --- a/lib/microservices/server/server.d.ts +++ b/lib/microservices/server/server.d.ts @@ -8,12 +8,15 @@ import 'rxjs/add/operator/finally'; import 'rxjs/add/observable/empty'; import 'rxjs/add/observable/of'; import 'rxjs/add/observable/fromPromise'; -export declare abstract class Server { - protected readonly messageHandlers: MessageHandlers; - protected readonly logger: Logger; - getHandlers(): MessageHandlers; - add(pattern: any, callback: (data) => Promise>): void; - send(stream$: Observable, respond: (data: MicroserviceResponse) => void): Subscription; - transformToObservable(resultOrDeffered: any): Observable; - protected handleError(error: string): void; +export abstract class Server { + protected readonly messageHandlers: MessageHandlers; + protected readonly logger: Logger; + getHandlers(): MessageHandlers; + add(pattern: any, callback: (data) => Promise>): void; + send( + stream$: Observable, + respond: (data: MicroserviceResponse) => void + ): Subscription; + transformToObservable(resultOrDeffered: any): Observable; + protected handleError(error: string): void; } diff --git a/lib/microservices/utils/client.decorator.d.ts b/lib/microservices/utils/client.decorator.d.ts index 31ffc195a66..02f010bc3aa 100644 --- a/lib/microservices/utils/client.decorator.d.ts +++ b/lib/microservices/utils/client.decorator.d.ts @@ -10,4 +10,6 @@ import { ClientMetadata } from '../interfaces/client-metadata.interface'; * port?: number; * host?: string; */ -export declare const Client: (metadata?: ClientMetadata) => (target: object, propertyKey: string | symbol) => void; +export declare const Client: ( + metadata?: ClientMetadata +) => (target: object, propertyKey: string | symbol) => void; diff --git a/lib/microservices/utils/pattern.decorator.d.ts b/lib/microservices/utils/pattern.decorator.d.ts index fb99bc2c0f1..fc2ad370182 100644 --- a/lib/microservices/utils/pattern.decorator.d.ts +++ b/lib/microservices/utils/pattern.decorator.d.ts @@ -3,4 +3,6 @@ import { PatternMetadata } from '../interfaces/pattern-metadata.interface'; /** * Subscribes to the messages, which fulfils chosen pattern. */ -export declare const MessagePattern: (metadata?: string | PatternMetadata) => MethodDecorator; +export declare const MessagePattern: ( + metadata?: string | PatternMetadata +) => MethodDecorator; diff --git a/lib/testing/errors/unknown-module.exception.d.ts b/lib/testing/errors/unknown-module.exception.d.ts index 086aa145aad..d0434f90cd1 100644 --- a/lib/testing/errors/unknown-module.exception.d.ts +++ b/lib/testing/errors/unknown-module.exception.d.ts @@ -1,4 +1,4 @@ import { RuntimeException } from '@nestjs/core/errors/exceptions/runtime.exception'; export declare class UnknownModuleException extends RuntimeException { - constructor(); + constructor(); } diff --git a/lib/testing/interfaces/override-by-factory-options.interface.d.ts b/lib/testing/interfaces/override-by-factory-options.interface.d.ts index 87bffb82d28..6de3261193c 100644 --- a/lib/testing/interfaces/override-by-factory-options.interface.d.ts +++ b/lib/testing/interfaces/override-by-factory-options.interface.d.ts @@ -1,4 +1,4 @@ export interface OverrideByFactoryOptions { - factory: (...args) => any; - inject?: any[]; + factory: (...args) => any; + inject?: any[]; } diff --git a/lib/testing/interfaces/override-by.interface.d.ts b/lib/testing/interfaces/override-by.interface.d.ts index 3e4447fdc80..c6620de87fa 100644 --- a/lib/testing/interfaces/override-by.interface.d.ts +++ b/lib/testing/interfaces/override-by.interface.d.ts @@ -1,7 +1,7 @@ import { OverrideByFactoryOptions } from './override-by-factory-options.interface'; import { TestingModuleBuilder } from '../testing-module.builder'; export interface OverrideBy { - useValue: (value) => TestingModuleBuilder; - useFactory: (options: OverrideByFactoryOptions) => TestingModuleBuilder; - useClass: (metatype) => TestingModuleBuilder; + useValue: (value) => TestingModuleBuilder; + useFactory: (options: OverrideByFactoryOptions) => TestingModuleBuilder; + useClass: (metatype) => TestingModuleBuilder; } diff --git a/lib/testing/test.d.ts b/lib/testing/test.d.ts index bebc805af2e..719b3e2a2a7 100644 --- a/lib/testing/test.d.ts +++ b/lib/testing/test.d.ts @@ -1,7 +1,7 @@ import { ModuleMetadata } from '@nestjs/common/interfaces/modules/module-metadata.interface'; import { TestingModuleBuilder } from './testing-module.builder'; export declare class Test { - private static metadataScanner; - static createTestingModule(metadata: ModuleMetadata): TestingModuleBuilder; - private static init(); + private static metadataScanner; + static createTestingModule(metadata: ModuleMetadata): TestingModuleBuilder; + private static init(); } diff --git a/lib/testing/testing-module.builder.d.ts b/lib/testing/testing-module.builder.d.ts index f6c85cb7b3d..0b57f3a692c 100644 --- a/lib/testing/testing-module.builder.d.ts +++ b/lib/testing/testing-module.builder.d.ts @@ -3,17 +3,17 @@ import { MetadataScanner } from '@nestjs/core/metadata-scanner'; import { ModuleMetadata } from '@nestjs/common/interfaces'; import { TestingModule } from './testing-module'; export declare class TestingModuleBuilder { - private readonly container; - private readonly overloadsMap; - private readonly scanner; - private readonly instanceLoader; - private readonly module; - constructor(metadataScanner: MetadataScanner, metadata: ModuleMetadata); - overrideGuard(typeOrToken: any): OverrideBy; - overrideInterceptor(typeOrToken: any): OverrideBy; - overrideComponent(typeOrToken: any): OverrideBy; - compile(): Promise; - private override(typeOrToken, isComponent); - private createOverrideByBuilder(add); - private createModule(metadata); + private readonly container; + private readonly overloadsMap; + private readonly scanner; + private readonly instanceLoader; + private readonly module; + constructor(metadataScanner: MetadataScanner, metadata: ModuleMetadata); + overrideGuard(typeOrToken: any): OverrideBy; + overrideInterceptor(typeOrToken: any): OverrideBy; + overrideComponent(typeOrToken: any): OverrideBy; + compile(): Promise; + private override(typeOrToken, isComponent); + private createOverrideByBuilder(add); + private createModule(metadata); } diff --git a/lib/testing/testing-module.d.ts b/lib/testing/testing-module.d.ts index 0738e6e39f0..16c00b8c7e2 100644 --- a/lib/testing/testing-module.d.ts +++ b/lib/testing/testing-module.d.ts @@ -4,7 +4,11 @@ import { NestApplicationContext } from '@nestjs/core'; import { INestApplication, INestMicroservice } from '@nestjs/common'; import { MicroserviceConfiguration } from '@nestjs/common/interfaces/microservices/microservice-configuration.interface'; export declare class TestingModule extends NestApplicationContext { - constructor(container: NestContainer, scope: NestModuleMetatype[], contextModule: any); - createNestApplication(express?: any): INestApplication; - createNestMicroservice(config: MicroserviceConfiguration): INestMicroservice; + constructor( + container: NestContainer, + scope: NestModuleMetatype[], + contextModule: any + ); + createNestApplication(express?: any): INestApplication; + createNestMicroservice(config: MicroserviceConfiguration): INestMicroservice; } diff --git a/lib/websockets/adapters/io-adapter.d.ts b/lib/websockets/adapters/io-adapter.d.ts index 63db1abe51c..81a9f642e3a 100644 --- a/lib/websockets/adapters/io-adapter.d.ts +++ b/lib/websockets/adapters/io-adapter.d.ts @@ -9,13 +9,17 @@ import 'rxjs/add/operator/switchMap'; import 'rxjs/add/operator/filter'; import 'rxjs/add/operator/do'; export declare class IoAdapter implements WebSocketAdapter { - private readonly httpServer; - constructor(httpServer?: Server | null); - create(port: number): SocketIO.Server; - createWithNamespace(port: number, namespace: string, server?: any): any; - createIOServer(port: number): SocketIO.Server; - bindClientConnect(server: any, callback: (...args) => void): void; - bindClientDisconnect(client: any, callback: (...args) => void): void; - bindMessageHandlers(client: any, handlers: MessageMappingProperties[], process: (data: any) => Observable): void; - bindMiddleware(server: any, middleware: (socket, next) => void): void; + private readonly httpServer; + constructor(httpServer?: Server | null); + create(port: number): SocketIO.Server; + createWithNamespace(port: number, namespace: string, server?: any): any; + createIOServer(port: number): SocketIO.Server; + bindClientConnect(server: any, callback: (...args) => void): void; + bindClientDisconnect(client: any, callback: (...args) => void): void; + bindMessageHandlers( + client: any, + handlers: MessageMappingProperties[], + process: (data: any) => Observable + ): void; + bindMiddleware(server: any, middleware: (socket, next) => void): void; } diff --git a/lib/websockets/constants.d.ts b/lib/websockets/constants.d.ts index 04528be1a90..248744ea715 100644 --- a/lib/websockets/constants.d.ts +++ b/lib/websockets/constants.d.ts @@ -1,9 +1,9 @@ -export declare const MESSAGE_MAPPING_METADATA = "__isMessageMapping"; -export declare const MESSAGE_METADATA = "message"; -export declare const GATEWAY_SERVER_METADATA = "__isSocketServer"; -export declare const GATEWAY_METADATA = "__isGateway"; -export declare const NAMESPACE_METADATA = "namespace"; -export declare const PORT_METADATA = "port"; -export declare const GATEWAY_MIDDLEWARES = "__gatewayMiddlewares"; -export declare const CONNECTION_EVENT = "connection"; -export declare const DISCONNECT_EVENT = "disconnect"; +export declare const MESSAGE_MAPPING_METADATA = '__isMessageMapping'; +export declare const MESSAGE_METADATA = 'message'; +export declare const GATEWAY_SERVER_METADATA = '__isSocketServer'; +export declare const GATEWAY_METADATA = '__isGateway'; +export declare const NAMESPACE_METADATA = 'namespace'; +export declare const PORT_METADATA = 'port'; +export declare const GATEWAY_MIDDLEWARES = '__gatewayMiddlewares'; +export declare const CONNECTION_EVENT = 'connection'; +export declare const DISCONNECT_EVENT = 'disconnect'; diff --git a/lib/websockets/container.d.ts b/lib/websockets/container.d.ts index 2a2df557bc4..06762054723 100644 --- a/lib/websockets/container.d.ts +++ b/lib/websockets/container.d.ts @@ -1,8 +1,12 @@ import { ObservableSocketServer } from './interfaces'; export declare class SocketsContainer { - private readonly observableServers; - getAllServers(): Map; - getServerByPort(port: number): ObservableSocketServer; - addServer(namespace: string, port: number, server: ObservableSocketServer): void; - clear(): void; + private readonly observableServers; + getAllServers(): Map; + getServerByPort(port: number): ObservableSocketServer; + addServer( + namespace: string, + port: number, + server: ObservableSocketServer + ): void; + clear(): void; } diff --git a/lib/websockets/context/exception-filters-context.d.ts b/lib/websockets/context/exception-filters-context.d.ts index 77683487b9f..7bf01173a6c 100644 --- a/lib/websockets/context/exception-filters-context.d.ts +++ b/lib/websockets/context/exception-filters-context.d.ts @@ -3,6 +3,9 @@ import { Controller } from '@nestjs/common/interfaces/controllers/controller.int import { BaseExceptionFilterContext } from '@nestjs/core/exceptions/base-exception-filter-context'; import { WsExceptionsHandler } from '../exceptions/ws-exceptions-handler'; export declare class ExceptionFiltersContext extends BaseExceptionFilterContext { - create(instance: Controller, callback: (client, data) => any): WsExceptionsHandler; - getGlobalMetadata(): T; + create( + instance: Controller, + callback: (client, data) => any + ): WsExceptionsHandler; + getGlobalMetadata(): T; } diff --git a/lib/websockets/context/ws-context-creator.d.ts b/lib/websockets/context/ws-context-creator.d.ts index f1737bcd975..5035ebed98e 100644 --- a/lib/websockets/context/ws-context-creator.d.ts +++ b/lib/websockets/context/ws-context-creator.d.ts @@ -8,16 +8,32 @@ import { GuardsConsumer } from '@nestjs/core/guards/guards-consumer'; import { InterceptorsConsumer } from '@nestjs/core/interceptors/interceptors-consumer'; import { InterceptorsContextCreator } from '@nestjs/core/interceptors/interceptors-context-creator'; export declare class WsContextCreator { - private readonly wsProxy; - private readonly exceptionFiltersContext; - private readonly pipesCreator; - private readonly pipesConsumer; - private readonly guardsContextCreator; - private readonly guardsConsumer; - private readonly interceptorsContextCreator; - private readonly interceptorsConsumer; - constructor(wsProxy: WsProxy, exceptionFiltersContext: ExceptionFiltersContext, pipesCreator: PipesContextCreator, pipesConsumer: PipesConsumer, guardsContextCreator: GuardsContextCreator, guardsConsumer: GuardsConsumer, interceptorsContextCreator: InterceptorsContextCreator, interceptorsConsumer: InterceptorsConsumer); - create(instance: Controller, callback: (client, data) => void, module: any): (client, data) => Promise; - reflectCallbackParamtypes(instance: Controller, callback: (...args) => any): any[]; - getDataMetatype(instance: any, callback: any): any; + private readonly wsProxy; + private readonly exceptionFiltersContext; + private readonly pipesCreator; + private readonly pipesConsumer; + private readonly guardsContextCreator; + private readonly guardsConsumer; + private readonly interceptorsContextCreator; + private readonly interceptorsConsumer; + constructor( + wsProxy: WsProxy, + exceptionFiltersContext: ExceptionFiltersContext, + pipesCreator: PipesContextCreator, + pipesConsumer: PipesConsumer, + guardsContextCreator: GuardsContextCreator, + guardsConsumer: GuardsConsumer, + interceptorsContextCreator: InterceptorsContextCreator, + interceptorsConsumer: InterceptorsConsumer + ); + create( + instance: Controller, + callback: (client, data) => void, + module: any + ): (client, data) => Promise; + reflectCallbackParamtypes( + instance: Controller, + callback: (...args) => any + ): any[]; + getDataMetatype(instance: any, callback: any): any; } diff --git a/lib/websockets/context/ws-proxy.d.ts b/lib/websockets/context/ws-proxy.d.ts index 1b1a63e6cb1..688c00b257b 100644 --- a/lib/websockets/context/ws-proxy.d.ts +++ b/lib/websockets/context/ws-proxy.d.ts @@ -1,4 +1,7 @@ import { WsExceptionsHandler } from './../exceptions/ws-exceptions-handler'; export declare class WsProxy { - create(targetCallback: (client, data) => Promise, exceptionsHandler: WsExceptionsHandler): (client, data) => Promise; + create( + targetCallback: (client, data) => Promise, + exceptionsHandler: WsExceptionsHandler + ): (client, data) => Promise; } diff --git a/lib/websockets/exceptions/invalid-socket-port.exception.d.ts b/lib/websockets/exceptions/invalid-socket-port.exception.d.ts index 0bccb046771..9cfacab3182 100644 --- a/lib/websockets/exceptions/invalid-socket-port.exception.d.ts +++ b/lib/websockets/exceptions/invalid-socket-port.exception.d.ts @@ -1,4 +1,4 @@ import { RuntimeException } from '@nestjs/core/errors/exceptions/runtime.exception'; export declare class InvalidSocketPortException extends RuntimeException { - constructor(port: any, type: any); + constructor(port: any, type: any); } diff --git a/lib/websockets/exceptions/ws-exception.d.ts b/lib/websockets/exceptions/ws-exception.d.ts index a5a5071d768..10971e52a66 100644 --- a/lib/websockets/exceptions/ws-exception.d.ts +++ b/lib/websockets/exceptions/ws-exception.d.ts @@ -1,5 +1,5 @@ export declare class WsException { - private readonly error; - constructor(error: string | object); - getError(): string | object; + private readonly error; + constructor(error: string | object); + getError(): string | object; } diff --git a/lib/websockets/exceptions/ws-exceptions-handler.d.ts b/lib/websockets/exceptions/ws-exceptions-handler.d.ts index fc5ed7416fb..446ab51c041 100644 --- a/lib/websockets/exceptions/ws-exceptions-handler.d.ts +++ b/lib/websockets/exceptions/ws-exceptions-handler.d.ts @@ -1,8 +1,8 @@ import { ExceptionFilterMetadata } from '@nestjs/common/interfaces/exceptions/exception-filter-metadata.interface'; import { WsException } from '../exceptions/ws-exception'; export declare class WsExceptionsHandler { - private filters; - handle(exception: Error | WsException | any, client: any): any; - setCustomFilters(filters: ExceptionFilterMetadata[]): void; - invokeCustomFilters(exception: any, client: any): boolean; + private filters; + handle(exception: Error | WsException | any, client: any): any; + setCustomFilters(filters: ExceptionFilterMetadata[]): void; + invokeCustomFilters(exception: any, client: any): boolean; } diff --git a/lib/websockets/gateway-metadata-explorer.d.ts b/lib/websockets/gateway-metadata-explorer.d.ts index f3fbfe5d98f..cb79194bc8f 100644 --- a/lib/websockets/gateway-metadata-explorer.d.ts +++ b/lib/websockets/gateway-metadata-explorer.d.ts @@ -2,13 +2,16 @@ import { NestGateway } from './interfaces/nest-gateway.interface'; import { MetadataScanner } from '@nestjs/core/metadata-scanner'; import { Observable } from 'rxjs/Observable'; export declare class GatewayMetadataExplorer { - private readonly metadataScanner; - constructor(metadataScanner: MetadataScanner); - explore(instance: NestGateway): MessageMappingProperties[]; - exploreMethodMetadata(instancePrototype: any, methodName: string): MessageMappingProperties; - scanForServerHooks(instance: NestGateway): IterableIterator; + private readonly metadataScanner; + constructor(metadataScanner: MetadataScanner); + explore(instance: NestGateway): MessageMappingProperties[]; + exploreMethodMetadata( + instancePrototype: any, + methodName: string + ): MessageMappingProperties; + scanForServerHooks(instance: NestGateway): IterableIterator; } export interface MessageMappingProperties { - message: string; - callback: (...args) => Observable | Promise | void; + message: string; + callback: (...args) => Observable | Promise | void; } diff --git a/lib/websockets/interfaces/gateway-metadata.interface.d.ts b/lib/websockets/interfaces/gateway-metadata.interface.d.ts index dca57bb6116..cfb93c47e9e 100644 --- a/lib/websockets/interfaces/gateway-metadata.interface.d.ts +++ b/lib/websockets/interfaces/gateway-metadata.interface.d.ts @@ -1,7 +1,7 @@ import { Metatype } from '@nestjs/common/interfaces/metatype.interface'; import { GatewayMiddleware } from './gateway-middleware.interface'; export interface GatewayMetadata { - port?: number; - namespace?: string; - middlewares?: Metatype[]; + port?: number; + namespace?: string; + middlewares?: Metatype[]; } diff --git a/lib/websockets/interfaces/gateway-middleware.interface.d.ts b/lib/websockets/interfaces/gateway-middleware.interface.d.ts index e3cea273e1e..7cf923417cf 100644 --- a/lib/websockets/interfaces/gateway-middleware.interface.d.ts +++ b/lib/websockets/interfaces/gateway-middleware.interface.d.ts @@ -1,3 +1,3 @@ export interface GatewayMiddleware { - resolve(): (socket, next) => void; + resolve(): (socket, next) => void; } diff --git a/lib/websockets/interfaces/nest-gateway.interface.d.ts b/lib/websockets/interfaces/nest-gateway.interface.d.ts index 51b96ee1671..07c40bb32d0 100644 --- a/lib/websockets/interfaces/nest-gateway.interface.d.ts +++ b/lib/websockets/interfaces/nest-gateway.interface.d.ts @@ -1,5 +1,5 @@ export interface NestGateway { - afterInit?: (server: any) => void; - handleConnection?: (client: any) => void; - handleDisconnect?: (client: any) => void; + afterInit?: (server: any) => void; + handleConnection?: (client: any) => void; + handleDisconnect?: (client: any) => void; } diff --git a/lib/websockets/interfaces/observable-socket-server.interface.d.ts b/lib/websockets/interfaces/observable-socket-server.interface.d.ts index 4ee67465647..cd453280f14 100644 --- a/lib/websockets/interfaces/observable-socket-server.interface.d.ts +++ b/lib/websockets/interfaces/observable-socket-server.interface.d.ts @@ -1,8 +1,8 @@ import { ReplaySubject } from 'rxjs/ReplaySubject'; import { Subject } from 'rxjs/Subject'; export interface ObservableSocketServer { - server: any; - init: ReplaySubject; - connection: Subject; - disconnect: Subject; + server: any; + init: ReplaySubject; + connection: Subject; + disconnect: Subject; } diff --git a/lib/websockets/interfaces/on-gateway-connection.interface.d.ts b/lib/websockets/interfaces/on-gateway-connection.interface.d.ts index a7daeb395a5..d505e14d697 100644 --- a/lib/websockets/interfaces/on-gateway-connection.interface.d.ts +++ b/lib/websockets/interfaces/on-gateway-connection.interface.d.ts @@ -1,3 +1,3 @@ export interface OnGatewayConnection { - handleConnection(client: any): any; + handleConnection(client: any): any; } diff --git a/lib/websockets/interfaces/on-gateway-disconnect.interface.d.ts b/lib/websockets/interfaces/on-gateway-disconnect.interface.d.ts index f71c0cfae93..55eeaffa4d1 100644 --- a/lib/websockets/interfaces/on-gateway-disconnect.interface.d.ts +++ b/lib/websockets/interfaces/on-gateway-disconnect.interface.d.ts @@ -1,3 +1,3 @@ export interface OnGatewayDisconnect { - handleDisconnect(client: any): any; + handleDisconnect(client: any): any; } diff --git a/lib/websockets/interfaces/on-gateway-init.interface.d.ts b/lib/websockets/interfaces/on-gateway-init.interface.d.ts index 0e4521cddb8..392a2a6cc45 100644 --- a/lib/websockets/interfaces/on-gateway-init.interface.d.ts +++ b/lib/websockets/interfaces/on-gateway-init.interface.d.ts @@ -1,3 +1,3 @@ export interface OnGatewayInit { - afterInit(server: any): any; + afterInit(server: any): any; } diff --git a/lib/websockets/interfaces/web-socket-server.interface.d.ts b/lib/websockets/interfaces/web-socket-server.interface.d.ts index cfaa6414cbb..eacd80be493 100644 --- a/lib/websockets/interfaces/web-socket-server.interface.d.ts +++ b/lib/websockets/interfaces/web-socket-server.interface.d.ts @@ -1,4 +1,4 @@ export interface WebSocketServerData { - port: number; - namespace: string; + port: number; + namespace: string; } diff --git a/lib/websockets/interfaces/ws-response.interface.d.ts b/lib/websockets/interfaces/ws-response.interface.d.ts index 5c7710b08c2..2df913fbd9b 100644 --- a/lib/websockets/interfaces/ws-response.interface.d.ts +++ b/lib/websockets/interfaces/ws-response.interface.d.ts @@ -1,4 +1,4 @@ export interface WsResponse { - event: string; - data: T; + event: string; + data: T; } diff --git a/lib/websockets/middlewares-injector.d.ts b/lib/websockets/middlewares-injector.d.ts index e6b4f369300..65cccaed87b 100644 --- a/lib/websockets/middlewares-injector.d.ts +++ b/lib/websockets/middlewares-injector.d.ts @@ -1,16 +1,26 @@ import 'reflect-metadata'; -import { NestContainer, InstanceWrapper } from '@nestjs/core/injector/container'; +import { + NestContainer, + InstanceWrapper +} from '@nestjs/core/injector/container'; import { NestGateway } from './index'; import { Injectable } from '@nestjs/common/interfaces/injectable.interface'; import { GatewayMiddleware } from './interfaces/gateway-middleware.interface'; import { ApplicationConfig } from '@nestjs/core/application-config'; export declare class MiddlewaresInjector { - private readonly container; - private readonly config; - constructor(container: NestContainer, config: ApplicationConfig); - inject(server: any, instance: NestGateway, module: string): void; - reflectMiddlewaresTokens(instance: NestGateway): any[]; - applyMiddlewares(server: any, components: Map>, tokens: any[]): void; - bindMiddleware(token: string, components: Map>): any; - isGatewayMiddleware(middleware: object): middleware is GatewayMiddleware; + private readonly container; + private readonly config; + constructor(container: NestContainer, config: ApplicationConfig); + inject(server: any, instance: NestGateway, module: string): void; + reflectMiddlewaresTokens(instance: NestGateway): any[]; + applyMiddlewares( + server: any, + components: Map>, + tokens: any[] + ): void; + bindMiddleware( + token: string, + components: Map> + ): any; + isGatewayMiddleware(middleware: object): middleware is GatewayMiddleware; } diff --git a/lib/websockets/observable-socket.d.ts b/lib/websockets/observable-socket.d.ts index a0f335c39e6..5c674f01be7 100644 --- a/lib/websockets/observable-socket.d.ts +++ b/lib/websockets/observable-socket.d.ts @@ -1,4 +1,4 @@ import { ObservableSocketServer } from './interfaces/observable-socket-server.interface'; export declare class ObservableSocket { - static create(server: any): ObservableSocketServer; + static create(server: any): ObservableSocketServer; } diff --git a/lib/websockets/socket-module.d.ts b/lib/websockets/socket-module.d.ts index 6b30183e066..cc602b64047 100644 --- a/lib/websockets/socket-module.d.ts +++ b/lib/websockets/socket-module.d.ts @@ -2,11 +2,17 @@ import 'reflect-metadata'; import { InstanceWrapper } from '@nestjs/core/injector/container'; import { Injectable } from '@nestjs/common/interfaces/injectable.interface'; export declare class SocketModule { - private socketsContainer; - private webSocketsController; - setup(container: any, config: any): void; - hookGatewaysIntoServers(components: Map>, moduleName: string): void; - hookGatewayIntoServer(wrapper: InstanceWrapper, moduleName: string): void; - close(): void; - private getContextCreator(container); + private socketsContainer; + private webSocketsController; + setup(container: any, config: any): void; + hookGatewaysIntoServers( + components: Map>, + moduleName: string + ): void; + hookGatewayIntoServer( + wrapper: InstanceWrapper, + moduleName: string + ): void; + close(): void; + private getContextCreator(container); } diff --git a/lib/websockets/socket-server-provider.d.ts b/lib/websockets/socket-server-provider.d.ts index 85794b3cb0d..976b9f16cfe 100644 --- a/lib/websockets/socket-server-provider.d.ts +++ b/lib/websockets/socket-server-provider.d.ts @@ -2,12 +2,15 @@ import { SocketsContainer } from './container'; import { ObservableSocketServer } from './interfaces/observable-socket-server.interface'; import { ApplicationConfig } from '@nestjs/core/application-config'; export declare class SocketServerProvider { - private readonly socketsContainer; - private readonly applicationConfig; - constructor(socketsContainer: SocketsContainer, applicationConfig: ApplicationConfig); - scanForSocketServer(namespace: string, port: number): ObservableSocketServer; - private createSocketServer(namespace, port); - private createWithNamespace(namespace, port, observableSocket); - private getServerOfNamespace(namespace, port, server); - private validateNamespace(namespace); + private readonly socketsContainer; + private readonly applicationConfig; + constructor( + socketsContainer: SocketsContainer, + applicationConfig: ApplicationConfig + ); + scanForSocketServer(namespace: string, port: number): ObservableSocketServer; + private createSocketServer(namespace, port); + private createWithNamespace(namespace, port, observableSocket); + private getServerOfNamespace(namespace, port, server); + private validateNamespace(namespace); } diff --git a/lib/websockets/utils/socket-gateway.decorator.d.ts b/lib/websockets/utils/socket-gateway.decorator.d.ts index 5141700f35f..344c0d81cf0 100644 --- a/lib/websockets/utils/socket-gateway.decorator.d.ts +++ b/lib/websockets/utils/socket-gateway.decorator.d.ts @@ -4,4 +4,6 @@ import { GatewayMetadata } from '../interfaces'; * Defines the Gateway. The gateway can inject dependencies through constructor. * Those dependencies should belongs to the same module. Gateway is listening on the specified port. */ -export declare const WebSocketGateway: (metadataOrPort?: number | GatewayMetadata) => ClassDecorator; +export declare const WebSocketGateway: ( + metadataOrPort?: number | GatewayMetadata +) => ClassDecorator; diff --git a/lib/websockets/utils/subscribe-message.decorator.d.ts b/lib/websockets/utils/subscribe-message.decorator.d.ts index fae2e1f519d..0db3b8c22c1 100644 --- a/lib/websockets/utils/subscribe-message.decorator.d.ts +++ b/lib/websockets/utils/subscribe-message.decorator.d.ts @@ -2,6 +2,10 @@ import 'reflect-metadata'; /** * Subscribes to the messages, which fulfils chosen pattern. */ -export declare const SubscribeMessage: (message?: string | { - value: string; -}) => MethodDecorator; +export declare const SubscribeMessage: ( + message?: + | string + | { + value: string; + } +) => MethodDecorator; diff --git a/lib/websockets/web-sockets-controller.d.ts b/lib/websockets/web-sockets-controller.d.ts index f283f43b028..eff14b44755 100644 --- a/lib/websockets/web-sockets-controller.d.ts +++ b/lib/websockets/web-sockets-controller.d.ts @@ -14,24 +14,58 @@ import 'rxjs/add/observable/fromPromise'; import 'rxjs/add/observable/of'; import 'rxjs/add/operator/switchMap'; export declare class WebSocketsController { - private readonly socketServerProvider; - private readonly container; - private readonly config; - private readonly contextCreator; - private readonly metadataExplorer; - private readonly middlewaresInjector; - constructor(socketServerProvider: SocketServerProvider, container: NestContainer, config: ApplicationConfig, contextCreator: WsContextCreator); - hookGatewayIntoServer(instance: NestGateway, metatype: Metatype, module: string): void; - subscribeObservableServer(instance: NestGateway, namespace: string, port: number, module: string): void; - injectMiddlewares({server}: { - server: any; - }, instance: NestGateway, module: string): void; - subscribeEvents(instance: NestGateway, messageHandlers: MessageMappingProperties[], observableServer: ObservableSocketServer): void; - getConnectionHandler(context: WebSocketsController, instance: NestGateway, messageHandlers: MessageMappingProperties[], disconnect: Subject, connection: Subject): (client: any) => void; - subscribeInitEvent(instance: NestGateway, event: Subject): void; - subscribeConnectionEvent(instance: NestGateway, event: Subject): void; - subscribeDisconnectEvent(instance: NestGateway, event: Subject): void; - subscribeMessages(messageHandlers: MessageMappingProperties[], client: any, instance: NestGateway): void; - pickResult(defferedResult: Promise): Promise>; - private hookServerToProperties(instance, server); + private readonly socketServerProvider; + private readonly container; + private readonly config; + private readonly contextCreator; + private readonly metadataExplorer; + private readonly middlewaresInjector; + constructor( + socketServerProvider: SocketServerProvider, + container: NestContainer, + config: ApplicationConfig, + contextCreator: WsContextCreator + ); + hookGatewayIntoServer( + instance: NestGateway, + metatype: Metatype, + module: string + ): void; + subscribeObservableServer( + instance: NestGateway, + namespace: string, + port: number, + module: string + ): void; + injectMiddlewares( + { + server + }: { + server: any; + }, + instance: NestGateway, + module: string + ): void; + subscribeEvents( + instance: NestGateway, + messageHandlers: MessageMappingProperties[], + observableServer: ObservableSocketServer + ): void; + getConnectionHandler( + context: WebSocketsController, + instance: NestGateway, + messageHandlers: MessageMappingProperties[], + disconnect: Subject, + connection: Subject + ): (client: any) => void; + subscribeInitEvent(instance: NestGateway, event: Subject): void; + subscribeConnectionEvent(instance: NestGateway, event: Subject): void; + subscribeDisconnectEvent(instance: NestGateway, event: Subject): void; + subscribeMessages( + messageHandlers: MessageMappingProperties[], + client: any, + instance: NestGateway + ): void; + pickResult(defferedResult: Promise): Promise>; + private hookServerToProperties(instance, server); } diff --git a/package.json b/package.json index 6ed5fe8de27..e6671d4e582 100644 --- a/package.json +++ b/package.json @@ -6,6 +6,7 @@ "scripts": { "test": "nyc --require ts-node/register mocha src/**/*.spec.ts --reporter spec", "coverage": "nyc report --reporter=text-lcov | coveralls", + "prettier": "prettier */**/*.ts --ignore-path ./.prettierignore --write && git status", "build": "gulp build && gulp move", "build:lib": "gulp build --dist lib", "prepublish": "npm run build:lib", @@ -14,6 +15,7 @@ "engines": { "node": ">=6.11.0" }, + "precommit": "prettier", "author": "Kamil Mysliwiec", "license": "MIT", "dependencies": { @@ -68,6 +70,8 @@ "mocha": "^3.2.0", "nodemon": "^1.11.0", "nyc": "^10.1.2", + "pre-commit": "^1.2.2", + "prettier": "^1.9.2", "sinon": "^2.1.0", "sinon-chai": "^2.8.0", "ts-node": "^3.2.0" diff --git a/src/common/constants.ts b/src/common/constants.ts index 4c3b2dfecad..0046d89e99c 100644 --- a/src/common/constants.ts +++ b/src/common/constants.ts @@ -1,8 +1,8 @@ export const metadata = { - MODULES: 'modules', - COMPONENTS: 'components', - CONTROLLERS: 'controllers', - EXPORTS: 'exports', + MODULES: 'modules', + COMPONENTS: 'components', + CONTROLLERS: 'controllers', + EXPORTS: 'exports' }; export const SHARED_MODULE_METADATA = '__sharedModule__'; @@ -19,4 +19,4 @@ export const PIPES_METADATA = '__pipes__'; export const GUARDS_METADATA = '__guards__'; export const INTERCEPTORS_METADATA = '__interceptors__'; export const HTTP_CODE_METADATA = '__httpCode__'; -export const GATEWAY_MIDDLEWARES = '__gatewayMiddlewares'; \ No newline at end of file +export const GATEWAY_MIDDLEWARES = '__gatewayMiddlewares'; diff --git a/src/common/decorators/core/catch.decorator.ts b/src/common/decorators/core/catch.decorator.ts index 9c629d517d0..0a23774fa34 100644 --- a/src/common/decorators/core/catch.decorator.ts +++ b/src/common/decorators/core/catch.decorator.ts @@ -6,7 +6,7 @@ import { FILTER_CATCH_EXCEPTIONS } from '../../constants'; * The class should implements the `ExceptionFilter` interface. */ export function Catch(...exceptions): ClassDecorator { - return (target: object) => { - Reflect.defineMetadata(FILTER_CATCH_EXCEPTIONS, exceptions, target); - }; + return (target: object) => { + Reflect.defineMetadata(FILTER_CATCH_EXCEPTIONS, exceptions, target); + }; } diff --git a/src/common/decorators/core/component.decorator.ts b/src/common/decorators/core/component.decorator.ts index f04e65c5b02..9964f3febd1 100644 --- a/src/common/decorators/core/component.decorator.ts +++ b/src/common/decorators/core/component.decorator.ts @@ -3,40 +3,42 @@ * Those dependencies should belongs to the same module. */ export function Component(): ClassDecorator { - return (target: object) => {}; + return (target: object) => {}; } /** * Defines the Pipe. The Pipe should implements the `PipeTransform` interface. */ export function Pipe(): ClassDecorator { - return (target: object) => {}; + return (target: object) => {}; } /** * Defines the Guard. The Guard should implement the `CanActivate` interface. */ export function Guard(): ClassDecorator { - return (target: object) => {}; + return (target: object) => {}; } /** * Defines the Middleware. The Middleware should implement the `NestMiddleware` interface. */ export function Middleware(): ClassDecorator { - return (target: object) => {}; + return (target: object) => {}; } /** * Defines the Interceptor. The Interceptor should implement `HttpInterceptor`, `RpcInterceptor` or `WsInterceptor` interface. */ export function Interceptor(): ClassDecorator { - return (target: object) => {}; + return (target: object) => {}; } export function mixin(mixinClass) { - this.offset = this.offset ? ++this.offset : (Math.random() * 100); - Object.defineProperty(mixinClass, 'name', { value: JSON.stringify(this.offset) }); + this.offset = this.offset ? ++this.offset : Math.random() * 100; + Object.defineProperty(mixinClass, 'name', { + value: JSON.stringify(this.offset) + }); Component()(mixinClass); return mixinClass; -} \ No newline at end of file +} diff --git a/src/common/decorators/core/controller.decorator.ts b/src/common/decorators/core/controller.decorator.ts index ef52aa9e624..d99b4443fdb 100644 --- a/src/common/decorators/core/controller.decorator.ts +++ b/src/common/decorators/core/controller.decorator.ts @@ -8,8 +8,8 @@ import { PATH_METADATA } from '../../constants'; * Those dependencies should belongs to the same module. */ export function Controller(prefix?: string): ClassDecorator { - const path = isUndefined(prefix) ? '/' : prefix; - return (target: object) => { - Reflect.defineMetadata(PATH_METADATA, path, target); - }; -} \ No newline at end of file + const path = isUndefined(prefix) ? '/' : prefix; + return (target: object) => { + Reflect.defineMetadata(PATH_METADATA, path, target); + }; +} diff --git a/src/common/decorators/core/exception-filters.decorator.ts b/src/common/decorators/core/exception-filters.decorator.ts index cab15c01807..7bfddb6f66c 100644 --- a/src/common/decorators/core/exception-filters.decorator.ts +++ b/src/common/decorators/core/exception-filters.decorator.ts @@ -4,14 +4,18 @@ import { Logger } from '@nestjs/common'; import { ExceptionFilter } from '../../index'; const defineFiltersMetadata = (...filters: ExceptionFilter[]) => { - return (target: object, key?, descriptor?) => { - if (descriptor) { - Reflect.defineMetadata(EXCEPTION_FILTERS_METADATA, filters, descriptor.value); - return descriptor; - } - Reflect.defineMetadata(EXCEPTION_FILTERS_METADATA, filters, target); - return target; - }; + return (target: object, key?, descriptor?) => { + if (descriptor) { + Reflect.defineMetadata( + EXCEPTION_FILTERS_METADATA, + filters, + descriptor.value + ); + return descriptor; + } + Reflect.defineMetadata(EXCEPTION_FILTERS_METADATA, filters, target); + return target; + }; }; /** @@ -24,4 +28,5 @@ const defineFiltersMetadata = (...filters: ExceptionFilter[]) => { * * @param {ExceptionFilter[]} ...filters (instances) */ -export const UseFilters = (...filters: ExceptionFilter[]) => defineFiltersMetadata(...filters); +export const UseFilters = (...filters: ExceptionFilter[]) => + defineFiltersMetadata(...filters); diff --git a/src/common/decorators/core/index.ts b/src/common/decorators/core/index.ts index 98e6ce6687f..b40b25d662f 100644 --- a/src/common/decorators/core/index.ts +++ b/src/common/decorators/core/index.ts @@ -8,4 +8,4 @@ export * from './use-pipes.decorator'; export * from './use-guards.decorator'; export * from './reflect-metadata.decorator'; export * from './use-interceptors.decorator'; -export * from './bind.decorator'; \ No newline at end of file +export * from './bind.decorator'; diff --git a/src/common/decorators/core/inject.decorator.ts b/src/common/decorators/core/inject.decorator.ts index d8934da5c9e..a9f86725033 100644 --- a/src/common/decorators/core/inject.decorator.ts +++ b/src/common/decorators/core/inject.decorator.ts @@ -7,11 +7,11 @@ import { isFunction } from '../../utils/shared.utils'; * Components are recognized by types / or tokens. */ export function Inject(token): ParameterDecorator { - return (target, key, index) => { - const args = Reflect.getMetadata(SELF_DECLARED_DEPS_METADATA, target) || []; - const type = isFunction(token) ? token.name : token; + return (target, key, index) => { + const args = Reflect.getMetadata(SELF_DECLARED_DEPS_METADATA, target) || []; + const type = isFunction(token) ? token.name : token; - args.push({ index, param: type }); - Reflect.defineMetadata(SELF_DECLARED_DEPS_METADATA, args, target); - }; -} \ No newline at end of file + args.push({ index, param: type }); + Reflect.defineMetadata(SELF_DECLARED_DEPS_METADATA, args, target); + }; +} diff --git a/src/common/decorators/core/reflect-metadata.decorator.ts b/src/common/decorators/core/reflect-metadata.decorator.ts index 6ad230e02ac..c31a5ac0eee 100644 --- a/src/common/decorators/core/reflect-metadata.decorator.ts +++ b/src/common/decorators/core/reflect-metadata.decorator.ts @@ -2,11 +2,15 @@ * Assigns the metadata to the class / function under specified `key`. * This metadata can be reflected using `Reflector` class. */ -export const ReflectMetadata = (metadataKey, metadataValue) => (target: object, key?, descriptor?) => { - if (descriptor) { - Reflect.defineMetadata(metadataKey, metadataValue, descriptor.value); - return descriptor; - } - Reflect.defineMetadata(metadataKey, metadataValue, target); - return target; +export const ReflectMetadata = (metadataKey, metadataValue) => ( + target: object, + key?, + descriptor? +) => { + if (descriptor) { + Reflect.defineMetadata(metadataKey, metadataValue, descriptor.value); + return descriptor; + } + Reflect.defineMetadata(metadataKey, metadataValue, target); + return target; }; diff --git a/src/common/decorators/core/use-guards.decorator.ts b/src/common/decorators/core/use-guards.decorator.ts index 56047fe5298..12e2add1f9e 100644 --- a/src/common/decorators/core/use-guards.decorator.ts +++ b/src/common/decorators/core/use-guards.decorator.ts @@ -11,12 +11,12 @@ import { GUARDS_METADATA } from '../../constants'; * @param {} ...guards (types) */ export function UseGuards(...guards) { - return (target: object, key?, descriptor?) => { - if (descriptor) { - Reflect.defineMetadata(GUARDS_METADATA, guards, descriptor.value); - return descriptor; - } - Reflect.defineMetadata(GUARDS_METADATA, guards, target); - return target; - }; + return (target: object, key?, descriptor?) => { + if (descriptor) { + Reflect.defineMetadata(GUARDS_METADATA, guards, descriptor.value); + return descriptor; + } + Reflect.defineMetadata(GUARDS_METADATA, guards, target); + return target; + }; } diff --git a/src/common/decorators/core/use-interceptors.decorator.ts b/src/common/decorators/core/use-interceptors.decorator.ts index 18888a5e030..412e41b0d4b 100644 --- a/src/common/decorators/core/use-interceptors.decorator.ts +++ b/src/common/decorators/core/use-interceptors.decorator.ts @@ -11,12 +11,16 @@ import { INTERCEPTORS_METADATA } from '../../constants'; * @param {} ...interceptors (types) */ export function UseInterceptors(...interceptors) { - return (target: object, key?, descriptor?) => { - if (descriptor) { - Reflect.defineMetadata(INTERCEPTORS_METADATA, interceptors, descriptor.value); - return descriptor; - } - Reflect.defineMetadata(INTERCEPTORS_METADATA, interceptors, target); - return target; - }; + return (target: object, key?, descriptor?) => { + if (descriptor) { + Reflect.defineMetadata( + INTERCEPTORS_METADATA, + interceptors, + descriptor.value + ); + return descriptor; + } + Reflect.defineMetadata(INTERCEPTORS_METADATA, interceptors, target); + return target; + }; } diff --git a/src/common/decorators/core/use-pipes.decorator.ts b/src/common/decorators/core/use-pipes.decorator.ts index 5f0bf502ecd..55f9cb7f4cc 100644 --- a/src/common/decorators/core/use-pipes.decorator.ts +++ b/src/common/decorators/core/use-pipes.decorator.ts @@ -12,12 +12,12 @@ import { PIPES_METADATA } from '../../constants'; * @param {PipeTransform[]} ...pipes (instances) */ export function UsePipes(...pipes: PipeTransform[]) { - return (target: object, key?, descriptor?) => { - if (descriptor) { - Reflect.defineMetadata(PIPES_METADATA, pipes, descriptor.value); - return descriptor; - } - Reflect.defineMetadata(PIPES_METADATA, pipes, target); - return target; - }; + return (target: object, key?, descriptor?) => { + if (descriptor) { + Reflect.defineMetadata(PIPES_METADATA, pipes, descriptor.value); + return descriptor; + } + Reflect.defineMetadata(PIPES_METADATA, pipes, target); + return target; + }; } diff --git a/src/common/decorators/http/create-route-param-metadata.decorator.ts b/src/common/decorators/http/create-route-param-metadata.decorator.ts index 0ca285e083f..2dba0c82a67 100644 --- a/src/common/decorators/http/create-route-param-metadata.decorator.ts +++ b/src/common/decorators/http/create-route-param-metadata.decorator.ts @@ -1,6 +1,6 @@ import { - ROUTE_ARGS_METADATA, - CUSTOM_ROUTE_AGRS_METADATA, + ROUTE_ARGS_METADATA, + CUSTOM_ROUTE_AGRS_METADATA } from '../../constants'; import { CustomParamFactory } from '../../interfaces/custom-route-param-factory.interface'; import { RouteParamsMetadata, ParamData } from './route-params.decorator'; @@ -8,46 +8,46 @@ import { PipeTransform } from '../../index'; import { isNil, isString } from '../../utils/shared.utils'; const assignCustomMetadata = ( - args: RouteParamsMetadata, - paramtype: number | string, - index: number, - factory: CustomParamFactory, - data?: ParamData, - ...pipes: PipeTransform[], + args: RouteParamsMetadata, + paramtype: number | string, + index: number, + factory: CustomParamFactory, + data?: ParamData, + ...pipes: PipeTransform[] ) => ({ - ...args, - [`${paramtype}${CUSTOM_ROUTE_AGRS_METADATA}:${index}`]: { - index, - factory, - data, - pipes, - }, + ...args, + [`${paramtype}${CUSTOM_ROUTE_AGRS_METADATA}:${index}`]: { + index, + factory, + data, + pipes + } }); const randomString = () => - Math.random() - .toString(36) - .substring(2, 15); + Math.random() + .toString(36) + .substring(2, 15); /** * Create route params custom decorator * @param factory */ export function createRouteParamDecorator( - factory: CustomParamFactory, + factory: CustomParamFactory ): (data?: any, ...pipes: PipeTransform[]) => ParameterDecorator { - const paramtype = randomString() + randomString(); - return (data?, ...pipes: PipeTransform[]): ParameterDecorator => ( - target, - key, - index, - ) => { - const args = Reflect.getMetadata(ROUTE_ARGS_METADATA, target, key) || {}; - Reflect.defineMetadata( - ROUTE_ARGS_METADATA, - assignCustomMetadata(args, paramtype, index, factory, data, ...pipes), - target, - key, - ); - }; + const paramtype = randomString() + randomString(); + return (data?, ...pipes: PipeTransform[]): ParameterDecorator => ( + target, + key, + index + ) => { + const args = Reflect.getMetadata(ROUTE_ARGS_METADATA, target, key) || {}; + Reflect.defineMetadata( + ROUTE_ARGS_METADATA, + assignCustomMetadata(args, paramtype, index, factory, data, ...pipes), + target, + key + ); + }; } diff --git a/src/common/decorators/http/http-code.decorator.ts b/src/common/decorators/http/http-code.decorator.ts index c2372f4ae06..99fc0706b3a 100644 --- a/src/common/decorators/http/http-code.decorator.ts +++ b/src/common/decorators/http/http-code.decorator.ts @@ -7,8 +7,8 @@ import { HTTP_CODE_METADATA } from '../../constants'; * @param {number} statusCode */ export function HttpCode(statusCode: number): MethodDecorator { - return (target: object, key, descriptor) => { - Reflect.defineMetadata(HTTP_CODE_METADATA, statusCode, descriptor.value); - return descriptor; - }; + return (target: object, key, descriptor) => { + Reflect.defineMetadata(HTTP_CODE_METADATA, statusCode, descriptor.value); + return descriptor; + }; } diff --git a/src/common/decorators/http/index.ts b/src/common/decorators/http/index.ts index 0293aebd0b5..e15c9610e64 100644 --- a/src/common/decorators/http/index.ts +++ b/src/common/decorators/http/index.ts @@ -1,4 +1,4 @@ export * from './request-mapping.decorator'; export * from './route-params.decorator'; export * from './http-code.decorator'; -export * from './create-route-param-metadata.decorator'; \ No newline at end of file +export * from './create-route-param-metadata.decorator'; diff --git a/src/common/decorators/http/request-mapping.decorator.ts b/src/common/decorators/http/request-mapping.decorator.ts index 78485fb5f5a..43a8e9272ac 100644 --- a/src/common/decorators/http/request-mapping.decorator.ts +++ b/src/common/decorators/http/request-mapping.decorator.ts @@ -4,26 +4,30 @@ import { RequestMethod } from '../../enums/request-method.enum'; import { PATH_METADATA, METHOD_METADATA } from '../../constants'; const defaultMetadata = { - [PATH_METADATA]: '/', - [METHOD_METADATA]: RequestMethod.GET, + [PATH_METADATA]: '/', + [METHOD_METADATA]: RequestMethod.GET }; -export const RequestMapping = (metadata: RequestMappingMetadata = defaultMetadata): MethodDecorator => { - const path = metadata[PATH_METADATA] || '/'; - const requestMethod = metadata[METHOD_METADATA] || RequestMethod.GET; +export const RequestMapping = ( + metadata: RequestMappingMetadata = defaultMetadata +): MethodDecorator => { + const path = metadata[PATH_METADATA] || '/'; + const requestMethod = metadata[METHOD_METADATA] || RequestMethod.GET; - return (target, key, descriptor: PropertyDescriptor) => { - Reflect.defineMetadata(PATH_METADATA, path, descriptor.value); - Reflect.defineMetadata(METHOD_METADATA, requestMethod, descriptor.value); - return descriptor; - }; + return (target, key, descriptor: PropertyDescriptor) => { + Reflect.defineMetadata(PATH_METADATA, path, descriptor.value); + Reflect.defineMetadata(METHOD_METADATA, requestMethod, descriptor.value); + return descriptor; + }; }; -const createMappingDecorator = (method: RequestMethod) => (path?: string): MethodDecorator => { - return RequestMapping({ - [PATH_METADATA]: path, - [METHOD_METADATA]: method, - }); +const createMappingDecorator = (method: RequestMethod) => ( + path?: string +): MethodDecorator => { + return RequestMapping({ + [PATH_METADATA]: path, + [METHOD_METADATA]: method + }); }; /** @@ -65,4 +69,3 @@ export const Head = createMappingDecorator(RequestMethod.HEAD); * Routes all HTTP requests to the specified path. */ export const All = createMappingDecorator(RequestMethod.ALL); - diff --git a/src/common/decorators/http/route-params.decorator.ts b/src/common/decorators/http/route-params.decorator.ts index 5007289c666..b5c0ea0b3c3 100644 --- a/src/common/decorators/http/route-params.decorator.ts +++ b/src/common/decorators/http/route-params.decorator.ts @@ -17,14 +17,14 @@ const assignMetadata = ( paramtype: RouteParamtypes, index: number, data?: ParamData, - ...pipes: PipeTransform[], + ...pipes: PipeTransform[] ) => ({ ...args, [`${paramtype}:${index}`]: { index, data, - pipes, - }, + pipes + } }); const createRouteParamDecorator = (paramtype: RouteParamtypes) => { @@ -34,14 +34,14 @@ const createRouteParamDecorator = (paramtype: RouteParamtypes) => { ROUTE_ARGS_METADATA, assignMetadata(args, paramtype, index, data), target, - key, + key ); }; }; const createPipesRouteParamDecorator = (paramtype: RouteParamtypes) => ( data?, - ...pipes: PipeTransform[], + ...pipes: PipeTransform[] ): ParameterDecorator => (target, key, index) => { const args = Reflect.getMetadata(ROUTE_ARGS_METADATA, target, key) || {}; const hasParamData = isNil(data) || isString(data); @@ -52,24 +52,24 @@ const createPipesRouteParamDecorator = (paramtype: RouteParamtypes) => ( ROUTE_ARGS_METADATA, assignMetadata(args, paramtype, index, paramData, ...paramPipes), target, - key, + key ); }; export const Request: () => ParameterDecorator = createRouteParamDecorator( - RouteParamtypes.REQUEST, + RouteParamtypes.REQUEST ); export const Response: () => ParameterDecorator = createRouteParamDecorator( - RouteParamtypes.RESPONSE, + RouteParamtypes.RESPONSE ); export const Next: () => ParameterDecorator = createRouteParamDecorator( - RouteParamtypes.NEXT, + RouteParamtypes.NEXT ); export const Session: () => ParameterDecorator = createRouteParamDecorator( - RouteParamtypes.SESSION, + RouteParamtypes.SESSION ); export const Headers: ( - property?: string, + property?: string ) => ParameterDecorator = createRouteParamDecorator(RouteParamtypes.HEADERS); export function Query(); @@ -81,7 +81,7 @@ export function Query( ) { return createPipesRouteParamDecorator(RouteParamtypes.QUERY)( property, - ...pipes, + ...pipes ); } @@ -94,7 +94,7 @@ export function Body( ) { return createPipesRouteParamDecorator(RouteParamtypes.BODY)( property, - ...pipes, + ...pipes ); } @@ -107,7 +107,7 @@ export function Param( ) { return createPipesRouteParamDecorator(RouteParamtypes.PARAM)( property, - ...pipes, + ...pipes ); } diff --git a/src/common/decorators/index.ts b/src/common/decorators/index.ts index f5defd09318..20ab3a19c41 100644 --- a/src/common/decorators/index.ts +++ b/src/common/decorators/index.ts @@ -1,3 +1,3 @@ export * from './core'; export * from './modules'; -export * from './http'; \ No newline at end of file +export * from './http'; diff --git a/src/common/decorators/modules/exceptions/constants.ts b/src/common/decorators/modules/exceptions/constants.ts index e7664335aff..c18970eeb53 100644 --- a/src/common/decorators/modules/exceptions/constants.ts +++ b/src/common/decorators/modules/exceptions/constants.ts @@ -1,2 +1,2 @@ export const InvalidModuleConfigMessage = (property: string) => - `Invalid property '${property}' in @Module() decorator.`; \ No newline at end of file + `Invalid property '${property}' in @Module() decorator.`; diff --git a/src/common/decorators/modules/exceptions/invalid-module-config.exception.ts b/src/common/decorators/modules/exceptions/invalid-module-config.exception.ts index 5bdb3972e21..8edecdfddf5 100644 --- a/src/common/decorators/modules/exceptions/invalid-module-config.exception.ts +++ b/src/common/decorators/modules/exceptions/invalid-module-config.exception.ts @@ -1,7 +1,7 @@ import { InvalidModuleConfigMessage } from './constants'; export class InvalidModuleConfigException extends Error { - constructor(property: string) { - super(InvalidModuleConfigMessage(property)); - } -} \ No newline at end of file + constructor(property: string) { + super(InvalidModuleConfigMessage(property)); + } +} diff --git a/src/common/decorators/modules/global.decorator.ts b/src/common/decorators/modules/global.decorator.ts index a8888914e23..966dc18dfa6 100644 --- a/src/common/decorators/modules/global.decorator.ts +++ b/src/common/decorators/modules/global.decorator.ts @@ -1,5 +1,9 @@ import 'reflect-metadata'; -import { PATH_METADATA, SHARED_MODULE_METADATA, GLOBAL_MODULE_METADATA } from '../../constants'; +import { + PATH_METADATA, + SHARED_MODULE_METADATA, + GLOBAL_MODULE_METADATA +} from '../../constants'; /** * Makes the module global-scoped. * Once imported will be available for all of the existing modules. @@ -8,4 +12,4 @@ export function Global(): ClassDecorator { return (target: any) => { Reflect.defineMetadata(GLOBAL_MODULE_METADATA, true, target); }; -} \ No newline at end of file +} diff --git a/src/common/decorators/modules/index.ts b/src/common/decorators/modules/index.ts index e60834996fd..00c91f43824 100644 --- a/src/common/decorators/modules/index.ts +++ b/src/common/decorators/modules/index.ts @@ -1,4 +1,4 @@ export * from './module.decorator'; export * from './shared.decorator'; export * from './single-scope.decorator'; -export * from './global.decorator'; \ No newline at end of file +export * from './global.decorator'; diff --git a/src/common/decorators/modules/module.decorator.ts b/src/common/decorators/modules/module.decorator.ts index a1b8751e1c0..1320f545b12 100644 --- a/src/common/decorators/modules/module.decorator.ts +++ b/src/common/decorators/modules/module.decorator.ts @@ -4,20 +4,20 @@ import { InvalidModuleConfigException } from './exceptions/invalid-module-config import { metadata } from '../../constants'; const metadataKeys = [ - metadata.MODULES, - metadata.EXPORTS, - metadata.COMPONENTS, - metadata.CONTROLLERS, + metadata.MODULES, + metadata.EXPORTS, + metadata.COMPONENTS, + metadata.CONTROLLERS ]; const validateKeys = (keys: string[]) => { - const isKeyValid = (key) => metadataKeys.findIndex(k => k === key) < 0; - const validateKey = (key) => { - if (isKeyValid(key)) { - throw new InvalidModuleConfigException(key); - } - }; - keys.forEach(validateKey); + const isKeyValid = key => metadataKeys.findIndex(k => k === key) < 0; + const validateKey = key => { + if (isKeyValid(key)) { + throw new InvalidModuleConfigException(key); + } + }; + keys.forEach(validateKey); }; /** @@ -29,19 +29,19 @@ const validateKeys = (keys: string[]) => { * @param obj {ModuleMetadata} Module metadata */ export function Module(obj: { - modules?: any[], - controllers?: any[], - components?: any[], - exports?: any[], + modules?: any[]; + controllers?: any[]; + components?: any[]; + exports?: any[]; }): ClassDecorator { - const propsKeys = Object.keys(obj); - validateKeys(propsKeys); + const propsKeys = Object.keys(obj); + validateKeys(propsKeys); - return (target: object) => { - for (const property in obj) { - if (obj.hasOwnProperty(property)) { - Reflect.defineMetadata(property, obj[property], target); - } - } - }; -} \ No newline at end of file + return (target: object) => { + for (const property in obj) { + if (obj.hasOwnProperty(property)) { + Reflect.defineMetadata(property, obj[property], target); + } + } + }; +} diff --git a/src/common/decorators/modules/shared.decorator.ts b/src/common/decorators/modules/shared.decorator.ts index a93f18a57d2..bbda70bc7f7 100644 --- a/src/common/decorators/modules/shared.decorator.ts +++ b/src/common/decorators/modules/shared.decorator.ts @@ -11,17 +11,19 @@ import { Logger } from '../../index'; * @deprecated */ export const Shared = (scope: string = 'global') => { - const logger = new Logger('Shared'); - logger.warn('DEPRECATED! Since version 4.0.0 `@Shared()` decorator is deprecated. All modules are singletons now.'); - return (target: any) => { - const Metatype = target as FunctionConstructor; - const Type = class extends Metatype { - constructor(...args) { - super(...args); - } - }; - Reflect.defineMetadata(SHARED_MODULE_METADATA, scope, Type); - Object.defineProperty(Type, 'name', { value: target.name }); - return Type as any; + const logger = new Logger('Shared'); + logger.warn( + 'DEPRECATED! Since version 4.0.0 `@Shared()` decorator is deprecated. All modules are singletons now.' + ); + return (target: any) => { + const Metatype = target as FunctionConstructor; + const Type = class extends Metatype { + constructor(...args) { + super(...args); + } }; -}; \ No newline at end of file + Reflect.defineMetadata(SHARED_MODULE_METADATA, scope, Type); + Object.defineProperty(Type, 'name', { value: target.name }); + return Type as any; + }; +}; diff --git a/src/common/decorators/modules/single-scope.decorator.ts b/src/common/decorators/modules/single-scope.decorator.ts index 536912d29fd..bf90b6fc4a4 100644 --- a/src/common/decorators/modules/single-scope.decorator.ts +++ b/src/common/decorators/modules/single-scope.decorator.ts @@ -6,14 +6,14 @@ import { PATH_METADATA, SHARED_MODULE_METADATA } from '../../constants'; */ export function SingleScope(): ClassDecorator { return (target: any) => { - const Metatype = target as FunctionConstructor; - const Type = class extends Metatype { - constructor(...args) { - super(...args); - } - }; - Reflect.defineMetadata(SHARED_MODULE_METADATA, true, Type); - Object.defineProperty(Type, 'name', { value: target.name }); - return Type as any; + const Metatype = target as FunctionConstructor; + const Type = class extends Metatype { + constructor(...args) { + super(...args); + } }; -} \ No newline at end of file + Reflect.defineMetadata(SHARED_MODULE_METADATA, true, Type); + Object.defineProperty(Type, 'name', { value: target.name }); + return Type as any; + }; +} diff --git a/src/common/enums/http-status.enum.ts b/src/common/enums/http-status.enum.ts index 0adcdf94d2f..d8460119bb4 100644 --- a/src/common/enums/http-status.enum.ts +++ b/src/common/enums/http-status.enum.ts @@ -1,45 +1,45 @@ export enum HttpStatus { - CONTINUE = 100, - SWITCHING_PROTOCOLS = 101, - PROCESSING = 102, - OK = 200, - CREATED = 201, - ACCEPTED = 202, - NON_AUTHORITATIVE_INFORMATION = 203, - NO_CONTENT = 204, - RESET_CONTENT = 205, - PARTIAL_CONTENT = 206, - AMBIGUOUS = 300, - MOVED_PERMANENTLY = 301, - FOUND = 302, - SEE_OTHER = 303, - NOT_MODIFIED = 304, - TEMPORARY_REDIRECT = 307, - PERMANENT_REDIRECT = 308, - BAD_REQUEST = 400, - UNAUTHORIZED = 401, - PAYMENT_REQUIRED = 402, - FORBIDDEN = 403, - NOT_FOUND = 404, - METHOD_NOT_ALLOWED = 405, - NOT_ACCEPTABLE = 406, - PROXY_AUTHENTICATION_REQUIRED = 407, - REQUEST_TIMEOUT = 408, - CONFLICT = 409, - GONE = 410, - LENGTH_REQUIRED = 411, - PRECONDITION_FAILED = 412, - PAYLOAD_TOO_LARGE = 413, - URI_TOO_LONG = 414, - UNSUPPORTED_MEDIA_TYPE = 415, - REQUESTED_RANGE_NOT_SATISFIABLE = 416, - EXPECTATION_FAILED = 417, - UNPROCESSABLE_ENTITY = 422, - TOO_MANY_REQUESTS = 429, - INTERNAL_SERVER_ERROR = 500, - NOT_IMPLEMENTED = 501, - BAD_GATEWAY = 502, - SERVICE_UNAVAILABLE = 503, - GATEWAY_TIMEOUT = 504, - HTTP_VERSION_NOT_SUPPORTED = 505, -} \ No newline at end of file + CONTINUE = 100, + SWITCHING_PROTOCOLS = 101, + PROCESSING = 102, + OK = 200, + CREATED = 201, + ACCEPTED = 202, + NON_AUTHORITATIVE_INFORMATION = 203, + NO_CONTENT = 204, + RESET_CONTENT = 205, + PARTIAL_CONTENT = 206, + AMBIGUOUS = 300, + MOVED_PERMANENTLY = 301, + FOUND = 302, + SEE_OTHER = 303, + NOT_MODIFIED = 304, + TEMPORARY_REDIRECT = 307, + PERMANENT_REDIRECT = 308, + BAD_REQUEST = 400, + UNAUTHORIZED = 401, + PAYMENT_REQUIRED = 402, + FORBIDDEN = 403, + NOT_FOUND = 404, + METHOD_NOT_ALLOWED = 405, + NOT_ACCEPTABLE = 406, + PROXY_AUTHENTICATION_REQUIRED = 407, + REQUEST_TIMEOUT = 408, + CONFLICT = 409, + GONE = 410, + LENGTH_REQUIRED = 411, + PRECONDITION_FAILED = 412, + PAYLOAD_TOO_LARGE = 413, + URI_TOO_LONG = 414, + UNSUPPORTED_MEDIA_TYPE = 415, + REQUESTED_RANGE_NOT_SATISFIABLE = 416, + EXPECTATION_FAILED = 417, + UNPROCESSABLE_ENTITY = 422, + TOO_MANY_REQUESTS = 429, + INTERNAL_SERVER_ERROR = 500, + NOT_IMPLEMENTED = 501, + BAD_GATEWAY = 502, + SERVICE_UNAVAILABLE = 503, + GATEWAY_TIMEOUT = 504, + HTTP_VERSION_NOT_SUPPORTED = 505 +} diff --git a/src/common/enums/index.ts b/src/common/enums/index.ts index 26060d73209..c17d8692b12 100644 --- a/src/common/enums/index.ts +++ b/src/common/enums/index.ts @@ -1,2 +1,2 @@ export * from './request-method.enum'; -export * from './http-status.enum'; \ No newline at end of file +export * from './http-status.enum'; diff --git a/src/common/enums/nest-environment.enum.ts b/src/common/enums/nest-environment.enum.ts index f3c84d6663e..63778ca0286 100644 --- a/src/common/enums/nest-environment.enum.ts +++ b/src/common/enums/nest-environment.enum.ts @@ -1,4 +1,4 @@ export enum NestEnvironment { - RUN, - TEST, -} \ No newline at end of file + RUN, + TEST +} diff --git a/src/common/enums/request-method.enum.ts b/src/common/enums/request-method.enum.ts index 5cfd1dcfdfd..d193086a3af 100644 --- a/src/common/enums/request-method.enum.ts +++ b/src/common/enums/request-method.enum.ts @@ -1,10 +1,10 @@ export enum RequestMethod { - GET = 0, - POST, - PUT, - DELETE, - PATCH, - ALL, - OPTIONS, - HEAD, -} \ No newline at end of file + GET = 0, + POST, + PUT, + DELETE, + PATCH, + ALL, + OPTIONS, + HEAD +} diff --git a/src/common/enums/route-paramtypes.enum.ts b/src/common/enums/route-paramtypes.enum.ts index 06389edd837..5b05d983cac 100644 --- a/src/common/enums/route-paramtypes.enum.ts +++ b/src/common/enums/route-paramtypes.enum.ts @@ -1,10 +1,10 @@ export enum RouteParamtypes { - REQUEST, - RESPONSE, - NEXT, - BODY, - QUERY, - PARAM, - HEADERS, - SESSION, -} \ No newline at end of file + REQUEST, + RESPONSE, + NEXT, + BODY, + QUERY, + PARAM, + HEADERS, + SESSION +} diff --git a/src/common/enums/transport.enum.ts b/src/common/enums/transport.enum.ts index 0d68c11964d..c677d5f0197 100644 --- a/src/common/enums/transport.enum.ts +++ b/src/common/enums/transport.enum.ts @@ -1,4 +1,4 @@ export enum Transport { TCP = 0, - REDIS = 1, -} \ No newline at end of file + REDIS = 1 +} diff --git a/src/common/exceptions/bad-gateway.exception.ts b/src/common/exceptions/bad-gateway.exception.ts index 91fb4b96029..fdcee564109 100644 --- a/src/common/exceptions/bad-gateway.exception.ts +++ b/src/common/exceptions/bad-gateway.exception.ts @@ -3,10 +3,10 @@ import { HttpStatus } from '../enums/http-status.enum'; import { createHttpExceptionBody } from './../utils/http-exception-body.util'; export class BadGatewayException extends HttpException { - constructor(message?: string | object | any, error = 'Bad Gateway') { - super( - createHttpExceptionBody(message, error, HttpStatus.BAD_GATEWAY), - HttpStatus.BAD_GATEWAY, - ); - } + constructor(message?: string | object | any, error = 'Bad Gateway') { + super( + createHttpExceptionBody(message, error, HttpStatus.BAD_GATEWAY), + HttpStatus.BAD_GATEWAY + ); + } } diff --git a/src/common/exceptions/bad-request.exception.ts b/src/common/exceptions/bad-request.exception.ts index e068ebdeab6..3a17b9bdf1b 100644 --- a/src/common/exceptions/bad-request.exception.ts +++ b/src/common/exceptions/bad-request.exception.ts @@ -3,10 +3,10 @@ import { HttpStatus } from '../enums/http-status.enum'; import { createHttpExceptionBody } from './../utils/http-exception-body.util'; export class BadRequestException extends HttpException { - constructor(message?: string | object | any, error = 'Bad Request') { + constructor(message?: string | object | any, error = 'Bad Request') { super( - createHttpExceptionBody(message, error, HttpStatus.BAD_REQUEST), - HttpStatus.BAD_REQUEST, - ); - } + createHttpExceptionBody(message, error, HttpStatus.BAD_REQUEST), + HttpStatus.BAD_REQUEST + ); + } } diff --git a/src/common/exceptions/conflict.exception.ts b/src/common/exceptions/conflict.exception.ts index 74769326dfe..37a9a675713 100644 --- a/src/common/exceptions/conflict.exception.ts +++ b/src/common/exceptions/conflict.exception.ts @@ -3,10 +3,10 @@ import { HttpStatus } from '../enums/http-status.enum'; import { createHttpExceptionBody } from './../utils/http-exception-body.util'; export class ConflictException extends HttpException { - constructor(message?: string | object | any, error = 'Conflict') { + constructor(message?: string | object | any, error = 'Conflict') { super( - createHttpExceptionBody(message, error, HttpStatus.CONFLICT), - HttpStatus.CONFLICT, - ); - } -} \ No newline at end of file + createHttpExceptionBody(message, error, HttpStatus.CONFLICT), + HttpStatus.CONFLICT + ); + } +} diff --git a/src/common/exceptions/forbidden.exception.ts b/src/common/exceptions/forbidden.exception.ts index 510d196e0ef..719e61c96e8 100644 --- a/src/common/exceptions/forbidden.exception.ts +++ b/src/common/exceptions/forbidden.exception.ts @@ -5,8 +5,8 @@ import { createHttpExceptionBody } from './../utils/http-exception-body.util'; export class ForbiddenException extends HttpException { constructor(message?: string | object | any, error = 'Forbidden') { super( - createHttpExceptionBody(message, error, HttpStatus.FORBIDDEN), - HttpStatus.FORBIDDEN, - ); - } -} \ No newline at end of file + createHttpExceptionBody(message, error, HttpStatus.FORBIDDEN), + HttpStatus.FORBIDDEN + ); + } +} diff --git a/src/common/exceptions/gateway-timeout.exception.ts b/src/common/exceptions/gateway-timeout.exception.ts index 4061bdd134d..619633e9006 100644 --- a/src/common/exceptions/gateway-timeout.exception.ts +++ b/src/common/exceptions/gateway-timeout.exception.ts @@ -5,8 +5,8 @@ import { createHttpExceptionBody } from './../utils/http-exception-body.util'; export class GatewayTimeoutException extends HttpException { constructor(message?: string | object | any, error = 'Gateway Timeout') { super( - createHttpExceptionBody(message, error, HttpStatus.GATEWAY_TIMEOUT), - HttpStatus.GATEWAY_TIMEOUT, - ); - } -} \ No newline at end of file + createHttpExceptionBody(message, error, HttpStatus.GATEWAY_TIMEOUT), + HttpStatus.GATEWAY_TIMEOUT + ); + } +} diff --git a/src/common/exceptions/gone.exception.ts b/src/common/exceptions/gone.exception.ts index d7b13789539..fad35277010 100644 --- a/src/common/exceptions/gone.exception.ts +++ b/src/common/exceptions/gone.exception.ts @@ -5,8 +5,8 @@ import { createHttpExceptionBody } from './../utils/http-exception-body.util'; export class GoneException extends HttpException { constructor(message?: string | object | any, error = 'Gone') { super( - createHttpExceptionBody(message, error, HttpStatus.GONE), - HttpStatus.GONE, - ); - } -} \ No newline at end of file + createHttpExceptionBody(message, error, HttpStatus.GONE), + HttpStatus.GONE + ); + } +} diff --git a/src/common/exceptions/http.exception.ts b/src/common/exceptions/http.exception.ts index ae0c96bfb3b..6ea9882ebad 100644 --- a/src/common/exceptions/http.exception.ts +++ b/src/common/exceptions/http.exception.ts @@ -16,17 +16,17 @@ export class HttpException { * ``` */ constructor( - private readonly response: string | object, - private readonly status: number, + private readonly response: string | object, + private readonly status: number ) { this.message = response; } public getResponse(): string | object { - return this.response; + return this.response; } public getStatus(): number { - return this.status; + return this.status; } } diff --git a/src/common/exceptions/index.ts b/src/common/exceptions/index.ts index edaea318b96..23c69da657a 100644 --- a/src/common/exceptions/index.ts +++ b/src/common/exceptions/index.ts @@ -15,4 +15,4 @@ export * from './internal-server-error.exception'; export * from './not-implemented.exception'; export * from './bad-gateway.exception'; export * from './service-unavailable.exception'; -export * from './gateway-timeout.exception'; \ No newline at end of file +export * from './gateway-timeout.exception'; diff --git a/src/common/exceptions/internal-server-error.exception.ts b/src/common/exceptions/internal-server-error.exception.ts index 0fe6fbe830c..24aa1179bf4 100644 --- a/src/common/exceptions/internal-server-error.exception.ts +++ b/src/common/exceptions/internal-server-error.exception.ts @@ -3,10 +3,13 @@ import { HttpStatus } from '../enums/http-status.enum'; import { createHttpExceptionBody } from './../utils/http-exception-body.util'; export class InternalServerErrorException extends HttpException { - constructor(message?: string | object | any, error = 'Internal Server Error') { + constructor( + message?: string | object | any, + error = 'Internal Server Error' + ) { super( - createHttpExceptionBody(message, error, HttpStatus.INTERNAL_SERVER_ERROR), - HttpStatus.INTERNAL_SERVER_ERROR, - ); - } -} \ No newline at end of file + createHttpExceptionBody(message, error, HttpStatus.INTERNAL_SERVER_ERROR), + HttpStatus.INTERNAL_SERVER_ERROR + ); + } +} diff --git a/src/common/exceptions/method-not-allowed.exception.ts b/src/common/exceptions/method-not-allowed.exception.ts index 6418a233a02..221cfbe8dab 100644 --- a/src/common/exceptions/method-not-allowed.exception.ts +++ b/src/common/exceptions/method-not-allowed.exception.ts @@ -5,8 +5,8 @@ import { createHttpExceptionBody } from './../utils/http-exception-body.util'; export class MethodNotAllowedException extends HttpException { constructor(message?: string | object | any, error = 'Method Not Allowed') { super( - createHttpExceptionBody(message, error, HttpStatus.METHOD_NOT_ALLOWED), - HttpStatus.METHOD_NOT_ALLOWED, - ); - } -} \ No newline at end of file + createHttpExceptionBody(message, error, HttpStatus.METHOD_NOT_ALLOWED), + HttpStatus.METHOD_NOT_ALLOWED + ); + } +} diff --git a/src/common/exceptions/not-acceptable.exception.ts b/src/common/exceptions/not-acceptable.exception.ts index ad263171e20..32849bb925b 100644 --- a/src/common/exceptions/not-acceptable.exception.ts +++ b/src/common/exceptions/not-acceptable.exception.ts @@ -5,8 +5,8 @@ import { createHttpExceptionBody } from './../utils/http-exception-body.util'; export class NotAcceptableException extends HttpException { constructor(message?: string | object | any, error = 'Not Acceptable') { super( - createHttpExceptionBody(message, error, HttpStatus.NOT_ACCEPTABLE), - HttpStatus.NOT_ACCEPTABLE, - ); - } -} \ No newline at end of file + createHttpExceptionBody(message, error, HttpStatus.NOT_ACCEPTABLE), + HttpStatus.NOT_ACCEPTABLE + ); + } +} diff --git a/src/common/exceptions/not-found.exception.ts b/src/common/exceptions/not-found.exception.ts index e293f6fd6e1..e1e15d0e6b0 100644 --- a/src/common/exceptions/not-found.exception.ts +++ b/src/common/exceptions/not-found.exception.ts @@ -5,8 +5,8 @@ import { createHttpExceptionBody } from './../utils/http-exception-body.util'; export class NotFoundException extends HttpException { constructor(message?: string | object | any, error = 'Not Found') { super( - createHttpExceptionBody(message, error, HttpStatus.NOT_FOUND), - HttpStatus.NOT_FOUND, - ); - } -} \ No newline at end of file + createHttpExceptionBody(message, error, HttpStatus.NOT_FOUND), + HttpStatus.NOT_FOUND + ); + } +} diff --git a/src/common/exceptions/not-implemented.exception.ts b/src/common/exceptions/not-implemented.exception.ts index faf426606b2..2eaf0c74749 100644 --- a/src/common/exceptions/not-implemented.exception.ts +++ b/src/common/exceptions/not-implemented.exception.ts @@ -5,8 +5,8 @@ import { createHttpExceptionBody } from './../utils/http-exception-body.util'; export class NotImplementedException extends HttpException { constructor(message?: string | object | any, error = 'Not Implemented') { super( - createHttpExceptionBody(message, error, HttpStatus.NOT_IMPLEMENTED), - HttpStatus.NOT_IMPLEMENTED, - ); - } -} \ No newline at end of file + createHttpExceptionBody(message, error, HttpStatus.NOT_IMPLEMENTED), + HttpStatus.NOT_IMPLEMENTED + ); + } +} diff --git a/src/common/exceptions/payload-too-large.exception.ts b/src/common/exceptions/payload-too-large.exception.ts index 3f3d1078fdb..636a1577c0c 100644 --- a/src/common/exceptions/payload-too-large.exception.ts +++ b/src/common/exceptions/payload-too-large.exception.ts @@ -5,8 +5,8 @@ import { createHttpExceptionBody } from './../utils/http-exception-body.util'; export class PayloadTooLargeException extends HttpException { constructor(message?: string | object | any, error = 'Payload Too Large') { super( - createHttpExceptionBody(message, error, HttpStatus.PAYLOAD_TOO_LARGE), - HttpStatus.PAYLOAD_TOO_LARGE, - ); - } -} \ No newline at end of file + createHttpExceptionBody(message, error, HttpStatus.PAYLOAD_TOO_LARGE), + HttpStatus.PAYLOAD_TOO_LARGE + ); + } +} diff --git a/src/common/exceptions/request-timeout.exception.ts b/src/common/exceptions/request-timeout.exception.ts index ee4941e7865..3f384234311 100644 --- a/src/common/exceptions/request-timeout.exception.ts +++ b/src/common/exceptions/request-timeout.exception.ts @@ -5,8 +5,8 @@ import { createHttpExceptionBody } from './../utils/http-exception-body.util'; export class RequestTimeoutException extends HttpException { constructor(message?: string | object | any, error = 'Request Timeout') { super( - createHttpExceptionBody(message, error, HttpStatus.REQUEST_TIMEOUT), - HttpStatus.REQUEST_TIMEOUT, - ); - } -} \ No newline at end of file + createHttpExceptionBody(message, error, HttpStatus.REQUEST_TIMEOUT), + HttpStatus.REQUEST_TIMEOUT + ); + } +} diff --git a/src/common/exceptions/service-unavailable.exception.ts b/src/common/exceptions/service-unavailable.exception.ts index a4569c17a3e..af472422922 100644 --- a/src/common/exceptions/service-unavailable.exception.ts +++ b/src/common/exceptions/service-unavailable.exception.ts @@ -5,8 +5,8 @@ import { createHttpExceptionBody } from './../utils/http-exception-body.util'; export class ServiceUnavailableException extends HttpException { constructor(message?: string | object | any, error = 'Service Unavailable') { super( - createHttpExceptionBody(message, error, HttpStatus.SERVICE_UNAVAILABLE), - HttpStatus.SERVICE_UNAVAILABLE, - ); - } -} \ No newline at end of file + createHttpExceptionBody(message, error, HttpStatus.SERVICE_UNAVAILABLE), + HttpStatus.SERVICE_UNAVAILABLE + ); + } +} diff --git a/src/common/exceptions/unauthorized.exception.ts b/src/common/exceptions/unauthorized.exception.ts index 92d63bbd14c..23ab7871a91 100644 --- a/src/common/exceptions/unauthorized.exception.ts +++ b/src/common/exceptions/unauthorized.exception.ts @@ -5,8 +5,8 @@ import { createHttpExceptionBody } from './../utils/http-exception-body.util'; export class UnauthorizedException extends HttpException { constructor(message?: string | object | any, error = 'Unauthorized') { super( - createHttpExceptionBody(message, error, HttpStatus.UNAUTHORIZED), - HttpStatus.UNAUTHORIZED, - ); - } -} \ No newline at end of file + createHttpExceptionBody(message, error, HttpStatus.UNAUTHORIZED), + HttpStatus.UNAUTHORIZED + ); + } +} diff --git a/src/common/exceptions/unprocessable-entity.exception.ts b/src/common/exceptions/unprocessable-entity.exception.ts index 9114b5aceb9..556ef50e036 100644 --- a/src/common/exceptions/unprocessable-entity.exception.ts +++ b/src/common/exceptions/unprocessable-entity.exception.ts @@ -5,8 +5,8 @@ import { createHttpExceptionBody } from './../utils/http-exception-body.util'; export class UnprocessableEntityException extends HttpException { constructor(message?: string | object | any, error = 'Unprocessable Entity') { super( - createHttpExceptionBody(message, error, HttpStatus.UNPROCESSABLE_ENTITY), - HttpStatus.UNPROCESSABLE_ENTITY, - ); - } -} \ No newline at end of file + createHttpExceptionBody(message, error, HttpStatus.UNPROCESSABLE_ENTITY), + HttpStatus.UNPROCESSABLE_ENTITY + ); + } +} diff --git a/src/common/exceptions/unsupported-media-type.exception.ts b/src/common/exceptions/unsupported-media-type.exception.ts index 536b5c80f6f..4ee19a3bdcf 100644 --- a/src/common/exceptions/unsupported-media-type.exception.ts +++ b/src/common/exceptions/unsupported-media-type.exception.ts @@ -3,10 +3,17 @@ import { HttpStatus } from '../enums/http-status.enum'; import { createHttpExceptionBody } from './../utils/http-exception-body.util'; export class UnsupportedMediaTypeException extends HttpException { - constructor(message?: string | object | any, error = 'Unsupported Media Type') { + constructor( + message?: string | object | any, + error = 'Unsupported Media Type' + ) { super( - createHttpExceptionBody(message, error, HttpStatus.UNSUPPORTED_MEDIA_TYPE), - HttpStatus.UNSUPPORTED_MEDIA_TYPE, - ); - } -} \ No newline at end of file + createHttpExceptionBody( + message, + error, + HttpStatus.UNSUPPORTED_MEDIA_TYPE + ), + HttpStatus.UNSUPPORTED_MEDIA_TYPE + ); + } +} diff --git a/src/common/index.ts b/src/common/index.ts index 5e14504888e..ccd0bf3b010 100644 --- a/src/common/index.ts +++ b/src/common/index.ts @@ -8,30 +8,30 @@ export * from './decorators'; export * from './enums'; export { - NestModule, - INestApplication, - INestMicroservice, - MiddlewareConfigProxy, - MiddlewareConfiguration, - NestMiddleware, - ExpressMiddleware, - MiddlewaresConsumer, - OnModuleInit, - ExceptionFilter, - WebSocketAdapter, - PipeTransform, - Paramtype, - ArgumentMetadata, - OnModuleDestroy, - ExecutionContext, - CanActivate, - RpcExceptionFilter, - WsExceptionFilter, - NestInterceptor, - DynamicModule, - INestApplicationContext, + NestModule, + INestApplication, + INestMicroservice, + MiddlewareConfigProxy, + MiddlewareConfiguration, + NestMiddleware, + ExpressMiddleware, + MiddlewaresConsumer, + OnModuleInit, + ExceptionFilter, + WebSocketAdapter, + PipeTransform, + Paramtype, + ArgumentMetadata, + OnModuleDestroy, + ExecutionContext, + CanActivate, + RpcExceptionFilter, + WsExceptionFilter, + NestInterceptor, + DynamicModule, + INestApplicationContext } from './interfaces'; export * from './services/logger.service'; export * from './pipes'; export * from './utils'; -export * from './exceptions'; \ No newline at end of file +export * from './exceptions'; diff --git a/src/common/interfaces/can-activate.interface.ts b/src/common/interfaces/can-activate.interface.ts index 7a7cb47490d..b82a23927bc 100644 --- a/src/common/interfaces/can-activate.interface.ts +++ b/src/common/interfaces/can-activate.interface.ts @@ -2,5 +2,8 @@ import { Observable } from 'rxjs/Observable'; import { ExecutionContext } from './execution-context.interface'; export interface CanActivate { - canActivate(request, context: ExecutionContext): boolean | Promise | Observable; -} \ No newline at end of file + canActivate( + request, + context: ExecutionContext + ): boolean | Promise | Observable; +} diff --git a/src/common/interfaces/configuration-provider.interface.ts b/src/common/interfaces/configuration-provider.interface.ts index 6db6bd03e86..c0a0ca430a5 100644 --- a/src/common/interfaces/configuration-provider.interface.ts +++ b/src/common/interfaces/configuration-provider.interface.ts @@ -2,6 +2,6 @@ import { NestInterceptor } from './nest-interceptor.interface'; import { CanActivate } from './can-activate.interface'; export interface ConfigurationProvider { - getGlobalInterceptors(): NestInterceptor[]; - getGlobalGuards(): CanActivate[]; -} \ No newline at end of file + getGlobalInterceptors(): NestInterceptor[]; + getGlobalGuards(): CanActivate[]; +} diff --git a/src/common/interfaces/controllers/controller-metadata.interface.ts b/src/common/interfaces/controllers/controller-metadata.interface.ts index b816bf9aafb..593c4054e95 100644 --- a/src/common/interfaces/controllers/controller-metadata.interface.ts +++ b/src/common/interfaces/controllers/controller-metadata.interface.ts @@ -1,3 +1,3 @@ export interface ControllerMetadata { - path?: string; + path?: string; } diff --git a/src/common/interfaces/controllers/index.ts b/src/common/interfaces/controllers/index.ts index 16fdd33a9e4..4bd60924b00 100644 --- a/src/common/interfaces/controllers/index.ts +++ b/src/common/interfaces/controllers/index.ts @@ -1,2 +1,2 @@ export * from './controller-metadata.interface'; -export * from './controller.interface'; \ No newline at end of file +export * from './controller.interface'; diff --git a/src/common/interfaces/exceptions/exception-filter-metadata.interface.ts b/src/common/interfaces/exceptions/exception-filter-metadata.interface.ts index 7c8a8879a07..fbac6aca595 100644 --- a/src/common/interfaces/exceptions/exception-filter-metadata.interface.ts +++ b/src/common/interfaces/exceptions/exception-filter-metadata.interface.ts @@ -2,6 +2,6 @@ import { ExceptionFilter } from './exception-filter.interface'; import { Metatype } from '../metatype.interface'; export interface ExceptionFilterMetadata { - func: ExceptionFilter['catch']; - exceptionMetatypes: Metatype[]; + func: ExceptionFilter['catch']; + exceptionMetatypes: Metatype[]; } diff --git a/src/common/interfaces/exceptions/exception-filter.interface.ts b/src/common/interfaces/exceptions/exception-filter.interface.ts index c96d16431c1..8d37e3c8353 100644 --- a/src/common/interfaces/exceptions/exception-filter.interface.ts +++ b/src/common/interfaces/exceptions/exception-filter.interface.ts @@ -1,3 +1,3 @@ export interface ExceptionFilter { - catch(exception, response); -} \ No newline at end of file + catch(exception, response); +} diff --git a/src/common/interfaces/exceptions/index.ts b/src/common/interfaces/exceptions/index.ts index ae01703f1f8..f35002c2e21 100644 --- a/src/common/interfaces/exceptions/index.ts +++ b/src/common/interfaces/exceptions/index.ts @@ -2,4 +2,4 @@ export * from './exception-filter-metadata.interface'; export * from './exception-filter.interface'; export * from './rpc-exception-filter-metadata.interface'; export * from './rpc-exception-filter.interface'; -export * from './ws-exception-filter.interface'; \ No newline at end of file +export * from './ws-exception-filter.interface'; diff --git a/src/common/interfaces/exceptions/rpc-exception-filter-metadata.interface.ts b/src/common/interfaces/exceptions/rpc-exception-filter-metadata.interface.ts index 97f782e286a..a1a01adc454 100644 --- a/src/common/interfaces/exceptions/rpc-exception-filter-metadata.interface.ts +++ b/src/common/interfaces/exceptions/rpc-exception-filter-metadata.interface.ts @@ -2,6 +2,6 @@ import { RpcExceptionFilter } from './rpc-exception-filter.interface'; import { Metatype } from '../metatype.interface'; export interface RpcExceptionFilterMetadata { - func: RpcExceptionFilter['catch']; - exceptionMetatypes: Metatype[]; + func: RpcExceptionFilter['catch']; + exceptionMetatypes: Metatype[]; } diff --git a/src/common/interfaces/exceptions/rpc-exception-filter.interface.ts b/src/common/interfaces/exceptions/rpc-exception-filter.interface.ts index fcad046f178..22f79627302 100644 --- a/src/common/interfaces/exceptions/rpc-exception-filter.interface.ts +++ b/src/common/interfaces/exceptions/rpc-exception-filter.interface.ts @@ -1,5 +1,5 @@ import { Observable } from 'rxjs/Observable'; export interface RpcExceptionFilter { - catch(exception): Observable; -} \ No newline at end of file + catch(exception): Observable; +} diff --git a/src/common/interfaces/exceptions/ws-exception-filter.interface.ts b/src/common/interfaces/exceptions/ws-exception-filter.interface.ts index a413be8509a..e13c3849981 100644 --- a/src/common/interfaces/exceptions/ws-exception-filter.interface.ts +++ b/src/common/interfaces/exceptions/ws-exception-filter.interface.ts @@ -1,3 +1,3 @@ export interface WsExceptionFilter { - catch(exception, client); -} \ No newline at end of file + catch(exception, client); +} diff --git a/src/common/interfaces/execution-context.interface.ts b/src/common/interfaces/execution-context.interface.ts index 20ab9319402..2084f61e189 100644 --- a/src/common/interfaces/execution-context.interface.ts +++ b/src/common/interfaces/execution-context.interface.ts @@ -1,4 +1,4 @@ export interface ExecutionContext { parent: Function; handler: (...args) => any; -} \ No newline at end of file +} diff --git a/src/common/interfaces/index.ts b/src/common/interfaces/index.ts index 1ad2c0c596d..005099d8a6a 100644 --- a/src/common/interfaces/index.ts +++ b/src/common/interfaces/index.ts @@ -22,4 +22,4 @@ export * from './exceptions/ws-exception-filter.interface'; export * from './execution-context.interface'; export * from './nest-interceptor.interface'; export * from './custom-route-param-factory.interface'; -export * from './modules/dynamic-module.interface'; \ No newline at end of file +export * from './modules/dynamic-module.interface'; diff --git a/src/common/interfaces/metatype.interface.ts b/src/common/interfaces/metatype.interface.ts index 1befbd78048..e614c6c62af 100644 --- a/src/common/interfaces/metatype.interface.ts +++ b/src/common/interfaces/metatype.interface.ts @@ -1,3 +1,3 @@ export interface Metatype { - new (...args: any[]): T; -} \ No newline at end of file + new (...args: any[]): T; +} diff --git a/src/common/interfaces/microservices/microservice-configuration.interface.ts b/src/common/interfaces/microservices/microservice-configuration.interface.ts index 5803449324b..848df0c6d4e 100644 --- a/src/common/interfaces/microservices/microservice-configuration.interface.ts +++ b/src/common/interfaces/microservices/microservice-configuration.interface.ts @@ -7,4 +7,4 @@ export interface MicroserviceConfiguration { port?: number; host?: string; strategy?: CustomTransportStrategy; -} \ No newline at end of file +} diff --git a/src/common/interfaces/middlewares/express-middleware.interface.ts b/src/common/interfaces/middlewares/express-middleware.interface.ts index 1aa6896b102..f2abd6868dd 100644 --- a/src/common/interfaces/middlewares/express-middleware.interface.ts +++ b/src/common/interfaces/middlewares/express-middleware.interface.ts @@ -1,4 +1,4 @@ // tslint:disable-next-line:callable-types export interface ExpressMiddleware { - (req?, res?, next?): void; -} \ No newline at end of file + (req?, res?, next?): void; +} diff --git a/src/common/interfaces/middlewares/middleware-config-proxy.interface.ts b/src/common/interfaces/middlewares/middleware-config-proxy.interface.ts index 2c27f8ddae6..745a7d05664 100644 --- a/src/common/interfaces/middlewares/middleware-config-proxy.interface.ts +++ b/src/common/interfaces/middlewares/middleware-config-proxy.interface.ts @@ -2,26 +2,26 @@ import { MiddlewaresConsumer } from './middlewares-consumer.interface'; import { RequestMappingMetadata } from '../request-mapping-metadata.interface'; export interface MiddlewareConfigProxy { - /** - * Passes custom arguments to `resolve()` method of the middleware - * - * @param {} ...data - * @returns MiddlewareConfigProxy - */ - with(...data): MiddlewareConfigProxy; + /** + * Passes custom arguments to `resolve()` method of the middleware + * + * @param {} ...data + * @returns MiddlewareConfigProxy + */ + with(...data): MiddlewareConfigProxy; - /** - * Attaches passed routes / controllers to the processed middleware(s). - * Single route can be defined as a literal object: - * ``` - * path: string; - * method: RequestMethod; - * ``` - * - * When you passed Controller class, Nest will attach middleware to every HTTP route handler inside this controller. - * - * @param {} ...routes - * @returns MiddlewaresConsumer - */ - forRoutes(...routes): MiddlewaresConsumer; -} \ No newline at end of file + /** + * Attaches passed routes / controllers to the processed middleware(s). + * Single route can be defined as a literal object: + * ``` + * path: string; + * method: RequestMethod; + * ``` + * + * When you passed Controller class, Nest will attach middleware to every HTTP route handler inside this controller. + * + * @param {} ...routes + * @returns MiddlewaresConsumer + */ + forRoutes(...routes): MiddlewaresConsumer; +} diff --git a/src/common/interfaces/middlewares/middleware-configuration.interface.ts b/src/common/interfaces/middlewares/middleware-configuration.interface.ts index b91944ab9dc..4b47cfa3381 100644 --- a/src/common/interfaces/middlewares/middleware-configuration.interface.ts +++ b/src/common/interfaces/middlewares/middleware-configuration.interface.ts @@ -3,6 +3,6 @@ import { Controller } from '../controllers/controller.interface'; import { RequestMethod } from '../../enums/request-method.enum'; export interface MiddlewareConfiguration { - middlewares: any; - forRoutes: (Controller | ControllerMetadata & { method?: RequestMethod })[]; -} \ No newline at end of file + middlewares: any; + forRoutes: (Controller | ControllerMetadata & { method?: RequestMethod })[]; +} diff --git a/src/common/interfaces/middlewares/middlewares-consumer.interface.ts b/src/common/interfaces/middlewares/middlewares-consumer.interface.ts index 5b81099cfbb..cdee82fa0ff 100644 --- a/src/common/interfaces/middlewares/middlewares-consumer.interface.ts +++ b/src/common/interfaces/middlewares/middlewares-consumer.interface.ts @@ -1,12 +1,12 @@ import { MiddlewareConfigProxy } from './middleware-config-proxy.interface'; export interface MiddlewaresConsumer { - /** - * Takes single middleware class or array of classes, - * which subsequently can be attached to the passed routes / controllers. - * - * @param {any|any[]} middlewares - * @returns MiddlewareConfigProxy - */ - apply(middlewares: any | any[]): MiddlewareConfigProxy; -} \ No newline at end of file + /** + * Takes single middleware class or array of classes, + * which subsequently can be attached to the passed routes / controllers. + * + * @param {any|any[]} middlewares + * @returns MiddlewareConfigProxy + */ + apply(middlewares: any | any[]): MiddlewareConfigProxy; +} diff --git a/src/common/interfaces/middlewares/nest-middleware.interface.ts b/src/common/interfaces/middlewares/nest-middleware.interface.ts index 9b99a89c875..f3a5230718c 100644 --- a/src/common/interfaces/middlewares/nest-middleware.interface.ts +++ b/src/common/interfaces/middlewares/nest-middleware.interface.ts @@ -2,5 +2,10 @@ import { ExpressMiddleware } from './express-middleware.interface'; export type AsyncExpressMiddleware = Promise; export interface NestMiddleware { - resolve(...args): ExpressMiddleware | AsyncExpressMiddleware | Promise; + resolve( + ...args + ): + | ExpressMiddleware + | AsyncExpressMiddleware + | Promise; } diff --git a/src/common/interfaces/modules/dynamic-module.interface.ts b/src/common/interfaces/modules/dynamic-module.interface.ts index fd01cf4de26..91ba554e6b5 100644 --- a/src/common/interfaces/modules/dynamic-module.interface.ts +++ b/src/common/interfaces/modules/dynamic-module.interface.ts @@ -2,4 +2,4 @@ import { ModuleMetadata } from './module-metadata.interface'; export interface DynamicModule extends ModuleMetadata { module: any; -} \ No newline at end of file +} diff --git a/src/common/interfaces/modules/index.ts b/src/common/interfaces/modules/index.ts index 3592a9fc5ff..9e71b8dc083 100644 --- a/src/common/interfaces/modules/index.ts +++ b/src/common/interfaces/modules/index.ts @@ -2,4 +2,4 @@ export * from './module-metadata.interface'; export * from './module-metatype.interface'; export * from './nest-module.interface'; export * from './on-init.interface'; -export * from './dynamic-module.interface'; \ No newline at end of file +export * from './dynamic-module.interface'; diff --git a/src/common/interfaces/modules/module-metadata.interface.ts b/src/common/interfaces/modules/module-metadata.interface.ts index 4e14da6fb83..2f27a678573 100644 --- a/src/common/interfaces/modules/module-metadata.interface.ts +++ b/src/common/interfaces/modules/module-metadata.interface.ts @@ -2,8 +2,8 @@ import { NestModule } from './nest-module.interface'; import { Controller } from '../controllers/controller.interface'; export interface ModuleMetadata { - modules?: NestModule[] | any[]; - components?: any[]; - controllers?: Controller[] | any[]; - exports?: any[]; + modules?: NestModule[] | any[]; + components?: any[]; + controllers?: Controller[] | any[]; + exports?: any[]; } diff --git a/src/common/interfaces/modules/module-metatype.interface.ts b/src/common/interfaces/modules/module-metatype.interface.ts index dea03f3b7c3..a5b7175afdf 100644 --- a/src/common/interfaces/modules/module-metatype.interface.ts +++ b/src/common/interfaces/modules/module-metatype.interface.ts @@ -1,4 +1,4 @@ import { NestModule } from './nest-module.interface'; import { Metatype } from '../metatype.interface'; -export interface NestModuleMetatype extends Metatype {} \ No newline at end of file +export interface NestModuleMetatype extends Metatype {} diff --git a/src/common/interfaces/modules/nest-module.interface.ts b/src/common/interfaces/modules/nest-module.interface.ts index 149d4a7f886..8b8db1e4906 100644 --- a/src/common/interfaces/modules/nest-module.interface.ts +++ b/src/common/interfaces/modules/nest-module.interface.ts @@ -1,5 +1,5 @@ import { MiddlewaresConsumer } from '../middlewares/middlewares-consumer.interface'; export interface NestModule { - configure(consumer: MiddlewaresConsumer): MiddlewaresConsumer | void; -} \ No newline at end of file + configure(consumer: MiddlewaresConsumer): MiddlewaresConsumer | void; +} diff --git a/src/common/interfaces/modules/on-destroy.interface.ts b/src/common/interfaces/modules/on-destroy.interface.ts index d7fc3e79c51..8ed7a88240b 100644 --- a/src/common/interfaces/modules/on-destroy.interface.ts +++ b/src/common/interfaces/modules/on-destroy.interface.ts @@ -1,3 +1,3 @@ export interface OnModuleDestroy { - onModuleDestroy(); -} \ No newline at end of file + onModuleDestroy(); +} diff --git a/src/common/interfaces/modules/on-init.interface.ts b/src/common/interfaces/modules/on-init.interface.ts index 43bac80a1ec..3453bad1bdb 100644 --- a/src/common/interfaces/modules/on-init.interface.ts +++ b/src/common/interfaces/modules/on-init.interface.ts @@ -1,3 +1,3 @@ export interface OnModuleInit { - onModuleInit(); -} \ No newline at end of file + onModuleInit(); +} diff --git a/src/common/interfaces/nest-application-context.interface.ts b/src/common/interfaces/nest-application-context.interface.ts index 1400a9be998..041dbd25e83 100644 --- a/src/common/interfaces/nest-application-context.interface.ts +++ b/src/common/interfaces/nest-application-context.interface.ts @@ -1,15 +1,15 @@ import { Metatype } from './metatype.interface'; export interface INestApplicationContext { - /** - * Allows you to navigate through the modules tree, for example, to pull out a specific instance from the selected module. - * @returns INestApplicationContext - */ - select(module: Metatype): INestApplicationContext; + /** + * Allows you to navigate through the modules tree, for example, to pull out a specific instance from the selected module. + * @returns INestApplicationContext + */ + select(module: Metatype): INestApplicationContext; - /** - * Makes possible to retrieve the instance of the component or controller available inside the processed module. - * @returns T - */ - get(metatypeOrToken: Metatype | string): T; -} \ No newline at end of file + /** + * Makes possible to retrieve the instance of the component or controller available inside the processed module. + * @returns T + */ + get(metatypeOrToken: Metatype | string): T; +} diff --git a/src/common/interfaces/nest-application.interface.ts b/src/common/interfaces/nest-application.interface.ts index 29816800e91..41548d20470 100644 --- a/src/common/interfaces/nest-application.interface.ts +++ b/src/common/interfaces/nest-application.interface.ts @@ -5,135 +5,135 @@ import { NestInterceptor } from './nest-interceptor.interface'; import { INestApplicationContext } from './nest-application-context.interface'; export interface INestApplication extends INestApplicationContext { - /** - * Initializes application. It is not necessary to call this method directly. - * - * @returns Promise - */ - init(): Promise; - - /** - * The wrapper function around native `express.use()` method. - * Example `app.use(cors())` - * - * @returns void - */ - use(...args): void; - - /** - * The wrapper function around native `express.set()` method. - * Example `app.set('trust proxy', 'loopback')` - * - * @returns void - */ - set(...args): void; - - /** - * Starts the application. - * - * @param {number} port - * @param {string} hostname - * @param {Function} callback Optional callback - * @returns Promise - */ - listen(port: number, callback?: () => void): Promise; - listen(port: number, hostname: string, callback?: () => void): Promise; - - /** - * Starts the application and can be awaited. - * - * @param {number} port - * @param {string} hostname (optional) - * @returns Promise - */ - listenAsync(port: number, hostname?: string): Promise; - - /** - * Setups the prefix for the every HTTP route path - * - * @param {string} prefix The prefix for the every HTTP route path (for example `/v1/api`) - * @returns void - */ - setGlobalPrefix(prefix: string): void; - - /** - * Setup Web Sockets Adapter, which will be used inside Gateways. - * Use, when you want to override default `socket.io` library. - * - * @param {WebSocketAdapter} adapter - * @returns void - */ - useWebSocketAdapter(adapter: WebSocketAdapter): void; - - /** - * Connects microservice to the NestApplication instance. It transforms application to the hybrid instance. - * - * @param {MicroserviceConfiguration} config Microservice configuration objet - * @returns INestMicroservice - */ - connectMicroservice(config): INestMicroservice; - - /** - * Returns array of the connected microservices to the NestApplication. - * - * @returns INestMicroservice[] - */ - getMicroservices(): INestMicroservice[]; - - /** - * Returns underlying native HTTP server. - * - * @returns http.Server - */ - getHttpServer(): any; - - /** - * Starts all the connected microservices asynchronously - * - * @param {Function} callback Optional callback function - * @returns void - */ - startAllMicroservices(callback?: () => void): void; - - /** - * Starts all the connected microservices and can be awaited - * - * @returns Promise - */ - startAllMicroservicesAsync(): Promise; - - /** - * Setups exception filters as a global filters (will be used within every HTTP route handler) - * - * @param {ExceptionFilter[]} ...filters - */ - useGlobalFilters(...filters: ExceptionFilter[]); - - /** - * Setups pipes as a global pipes (will be used within every HTTP route handler) - * - * @param {PipeTransform[]} ...pipes - */ - useGlobalPipes(...pipes: PipeTransform[]); - - /** - * Setups interceptors as a global interceptors (will be used within every HTTP route handler) - * - * @param {NestInterceptor[]} ...interceptors - */ - useGlobalInterceptors(...interceptors: NestInterceptor[]); - - /** - * Setups guards as a global guards (will be used within every HTTP route handler) - * - * @param {CanActivate[]} ...guards - */ - useGlobalGuards(...guards: CanActivate[]); - - /** - * Terminates the application (both NestApplication, Web Socket Gateways and every connected microservice) - * - * @returns void - */ - close(): void; -} \ No newline at end of file + /** + * Initializes application. It is not necessary to call this method directly. + * + * @returns Promise + */ + init(): Promise; + + /** + * The wrapper function around native `express.use()` method. + * Example `app.use(cors())` + * + * @returns void + */ + use(...args): void; + + /** + * The wrapper function around native `express.set()` method. + * Example `app.set('trust proxy', 'loopback')` + * + * @returns void + */ + set(...args): void; + + /** + * Starts the application. + * + * @param {number} port + * @param {string} hostname + * @param {Function} callback Optional callback + * @returns Promise + */ + listen(port: number, callback?: () => void): Promise; + listen(port: number, hostname: string, callback?: () => void): Promise; + + /** + * Starts the application and can be awaited. + * + * @param {number} port + * @param {string} hostname (optional) + * @returns Promise + */ + listenAsync(port: number, hostname?: string): Promise; + + /** + * Setups the prefix for the every HTTP route path + * + * @param {string} prefix The prefix for the every HTTP route path (for example `/v1/api`) + * @returns void + */ + setGlobalPrefix(prefix: string): void; + + /** + * Setup Web Sockets Adapter, which will be used inside Gateways. + * Use, when you want to override default `socket.io` library. + * + * @param {WebSocketAdapter} adapter + * @returns void + */ + useWebSocketAdapter(adapter: WebSocketAdapter): void; + + /** + * Connects microservice to the NestApplication instance. It transforms application to the hybrid instance. + * + * @param {MicroserviceConfiguration} config Microservice configuration objet + * @returns INestMicroservice + */ + connectMicroservice(config): INestMicroservice; + + /** + * Returns array of the connected microservices to the NestApplication. + * + * @returns INestMicroservice[] + */ + getMicroservices(): INestMicroservice[]; + + /** + * Returns underlying, native HTTP server. + * + * @returns http.Server + */ + getHttpServer(): any; + + /** + * Starts all the connected microservices asynchronously + * + * @param {Function} callback Optional callback function + * @returns void + */ + startAllMicroservices(callback?: () => void): void; + + /** + * Starts all the connected microservices and can be awaited + * + * @returns Promise + */ + startAllMicroservicesAsync(): Promise; + + /** + * Setups exception filters as a global filters (will be used within every HTTP route handler) + * + * @param {ExceptionFilter[]} ...filters + */ + useGlobalFilters(...filters: ExceptionFilter[]); + + /** + * Setups pipes as a global pipes (will be used within every HTTP route handler) + * + * @param {PipeTransform[]} ...pipes + */ + useGlobalPipes(...pipes: PipeTransform[]); + + /** + * Setups interceptors as a global interceptors (will be used within every HTTP route handler) + * + * @param {NestInterceptor[]} ...interceptors + */ + useGlobalInterceptors(...interceptors: NestInterceptor[]); + + /** + * Setups guards as a global guards (will be used within every HTTP route handler) + * + * @param {CanActivate[]} ...guards + */ + useGlobalGuards(...guards: CanActivate[]); + + /** + * Terminates the application (both NestApplication, Web Socket Gateways and every connected microservice) + * + * @returns void + */ + close(): void; +} diff --git a/src/common/interfaces/nest-interceptor.interface.ts b/src/common/interfaces/nest-interceptor.interface.ts index 485edcc61b9..f9945badb53 100644 --- a/src/common/interfaces/nest-interceptor.interface.ts +++ b/src/common/interfaces/nest-interceptor.interface.ts @@ -2,5 +2,9 @@ import { Observable } from 'rxjs/Observable'; import { ExecutionContext } from './execution-context.interface'; export interface NestInterceptor { - intercept(dataOrRequest, context: ExecutionContext, stream$: Observable): Observable | Promise>; -} \ No newline at end of file + intercept( + dataOrRequest, + context: ExecutionContext, + stream$: Observable + ): Observable | Promise>; +} diff --git a/src/common/interfaces/nest-microservice.interface.ts b/src/common/interfaces/nest-microservice.interface.ts index d051ae23c86..8e6f6a1a7c8 100644 --- a/src/common/interfaces/nest-microservice.interface.ts +++ b/src/common/interfaces/nest-microservice.interface.ts @@ -5,55 +5,55 @@ import { NestInterceptor } from './nest-interceptor.interface'; import { CanActivate } from './can-activate.interface'; export interface INestMicroservice { - /** - * Starts the microservice. - * - * @param {Function} callback Callback called after instant - * @returns Promise - */ - listen(callback: () => void); + /** + * Starts the microservice. + * + * @param {Function} callback Callback called after instant + * @returns Promise + */ + listen(callback: () => void); - /** - * Setup Web Sockets Adapter, which will be used inside Gateways. - * Use, when you want to override default `socket.io` library. - * - * @param {WebSocketAdapter} adapter - * @returns void - */ - useWebSocketAdapter(adapter: WebSocketAdapter): void; + /** + * Setup Web Sockets Adapter, which will be used inside Gateways. + * Use, when you want to override default `socket.io` library. + * + * @param {WebSocketAdapter} adapter + * @returns void + */ + useWebSocketAdapter(adapter: WebSocketAdapter): void; - /** - * Setups exception filters as a global filters (will be used within every message pattern handler) - * - * @param {ExceptionFilter[]} ...filters - */ - useGlobalFilters(...filters: ExceptionFilter[]); - - /** - * Setups pipes as a global pipes (will be used within every message pattern handler) - * - * @param {PipeTransform[]} ...pipes - */ - useGlobalPipes(...pipes: PipeTransform[]); + /** + * Setups exception filters as a global filters (will be used within every message pattern handler) + * + * @param {ExceptionFilter[]} ...filters + */ + useGlobalFilters(...filters: ExceptionFilter[]); - /** - * Setups interceptors as a global interceptors (will be used within every message pattern handler) - * - * @param {NestInterceptor[]} ...interceptors - */ - useGlobalInterceptors(...interceptors: NestInterceptor[]); + /** + * Setups pipes as a global pipes (will be used within every message pattern handler) + * + * @param {PipeTransform[]} ...pipes + */ + useGlobalPipes(...pipes: PipeTransform[]); - /** - * Setups guards as a global guards (will be used within every message pattern handler) - * - * @param {CanActivate[]} ...guards - */ - useGlobalGuards(...guards: CanActivate[]); + /** + * Setups interceptors as a global interceptors (will be used within every message pattern handler) + * + * @param {NestInterceptor[]} ...interceptors + */ + useGlobalInterceptors(...interceptors: NestInterceptor[]); - /** - * Terminates the application (both NestMicroservice and every Web Socket Gateway) - * - * @returns void - */ - close(): void; -} \ No newline at end of file + /** + * Setups guards as a global guards (will be used within every message pattern handler) + * + * @param {CanActivate[]} ...guards + */ + useGlobalGuards(...guards: CanActivate[]); + + /** + * Terminates the application (both NestMicroservice and every Web Socket Gateway) + * + * @returns void + */ + close(): void; +} diff --git a/src/common/interfaces/paramtype.interface.ts b/src/common/interfaces/paramtype.interface.ts index 0151aad1eee..d2c299dbc01 100644 --- a/src/common/interfaces/paramtype.interface.ts +++ b/src/common/interfaces/paramtype.interface.ts @@ -1 +1 @@ -export type Paramtype = 'body' | 'query' | 'param' | 'custom'; \ No newline at end of file +export type Paramtype = 'body' | 'query' | 'param' | 'custom'; diff --git a/src/common/interfaces/pipe-transform.interface.ts b/src/common/interfaces/pipe-transform.interface.ts index df94661df80..721a632e738 100644 --- a/src/common/interfaces/pipe-transform.interface.ts +++ b/src/common/interfaces/pipe-transform.interface.ts @@ -3,11 +3,11 @@ import { Paramtype } from './paramtype.interface'; export type Transform = (value: T, metadata: ArgumentMetadata) => any; export interface ArgumentMetadata { - type: Paramtype; - metatype?: new (...args) => any; - data?: string; + type: Paramtype; + metatype?: new (...args) => any; + data?: string; } export interface PipeTransform { - transform(value: T, metadata: ArgumentMetadata): any; -} \ No newline at end of file + transform(value: T, metadata: ArgumentMetadata): any; +} diff --git a/src/common/interfaces/request-mapping-metadata.interface.ts b/src/common/interfaces/request-mapping-metadata.interface.ts index 3bf07134f6a..0cb2947b96a 100644 --- a/src/common/interfaces/request-mapping-metadata.interface.ts +++ b/src/common/interfaces/request-mapping-metadata.interface.ts @@ -1,6 +1,6 @@ import { RequestMethod } from '../enums/request-method.enum'; export interface RequestMappingMetadata { - path?: string; - method?: RequestMethod; + path?: string; + method?: RequestMethod; } diff --git a/src/common/interfaces/web-socket-adapter.interface.ts b/src/common/interfaces/web-socket-adapter.interface.ts index eab43f957d2..90a192a2258 100644 --- a/src/common/interfaces/web-socket-adapter.interface.ts +++ b/src/common/interfaces/web-socket-adapter.interface.ts @@ -11,7 +11,7 @@ export interface WebSocketAdapter { message: string; callback: (...args) => Observable | Promise | void; }[], - process: (data) => Observable, + process: (data) => Observable ); bindMiddleware?(server, middleware: (socket, next) => void); } diff --git a/src/common/pipes/index.ts b/src/common/pipes/index.ts index a8bd608e789..001a3fc7f75 100644 --- a/src/common/pipes/index.ts +++ b/src/common/pipes/index.ts @@ -1,2 +1,2 @@ export * from './validation.pipe'; -export * from './parse-int.pipe'; \ No newline at end of file +export * from './parse-int.pipe'; diff --git a/src/common/pipes/parse-int.pipe.ts b/src/common/pipes/parse-int.pipe.ts index 5171854d62e..db9781433cb 100644 --- a/src/common/pipes/parse-int.pipe.ts +++ b/src/common/pipes/parse-int.pipe.ts @@ -11,4 +11,4 @@ export class ParseIntPipe implements PipeTransform { } return val; } -} \ No newline at end of file +} diff --git a/src/common/pipes/validation.pipe.ts b/src/common/pipes/validation.pipe.ts index c5b317b8cc8..4ef46bc2738 100644 --- a/src/common/pipes/validation.pipe.ts +++ b/src/common/pipes/validation.pipe.ts @@ -7,21 +7,21 @@ import { Pipe } from './../decorators/core/component.decorator'; @Pipe() export class ValidationPipe implements PipeTransform { - public async transform(value, metadata: ArgumentMetadata) { - const { metatype } = metadata; - if (!metatype || !this.toValidate(metatype)) { - return value; - } - const entity = plainToClass(metatype, value); - const errors = await validate(entity); - if (errors.length > 0) { - throw new BadRequestException(errors); - } - return value; - } + public async transform(value, metadata: ArgumentMetadata) { + const { metatype } = metadata; + if (!metatype || !this.toValidate(metatype)) { + return value; + } + const entity = plainToClass(metatype, value); + const errors = await validate(entity); + if (errors.length > 0) { + throw new BadRequestException(errors); + } + return value; + } - private toValidate(metatype): boolean { - const types = [String, Boolean, Number, Array, Object]; - return !types.find(type => metatype === type) && !isNil(metatype); - } + private toValidate(metatype): boolean { + const types = [String, Boolean, Number, Array, Object]; + return !types.find(type => metatype === type) && !isNil(metatype); + } } diff --git a/src/common/services/logger.service.ts b/src/common/services/logger.service.ts index 689c963c017..c186e87f7d4 100644 --- a/src/common/services/logger.service.ts +++ b/src/common/services/logger.service.ts @@ -4,55 +4,58 @@ import { NestEnvironment } from '../enums/nest-environment.enum'; declare const process; export class Logger { - private static lastTimestamp = null; - private static contextEnv = NestEnvironment.RUN; - private readonly yellow = clc.xterm(3); - - constructor( - private readonly context: string, - private readonly printTimestamps = false) {} - - public static setMode(mode: NestEnvironment) { - this.contextEnv = mode; - } - - public log(message: string) { - this.printMessage(message, clc.green); - } - - public error(message: string, trace = '') { - this.printMessage(message, clc.red); - this.printStackTrace(trace); - } - - public warn(message: string) { - this.printMessage(message, clc.yellow); + private static lastTimestamp = null; + private static contextEnv = NestEnvironment.RUN; + private readonly yellow = clc.xterm(3); + + constructor( + private readonly context: string, + private readonly printTimestamps = false + ) {} + + public static setMode(mode: NestEnvironment) { + this.contextEnv = mode; + } + + public log(message: string) { + this.printMessage(message, clc.green); + } + + public error(message: string, trace = '') { + this.printMessage(message, clc.red); + this.printStackTrace(trace); + } + + public warn(message: string) { + this.printMessage(message, clc.yellow); + } + + private printMessage(message: string, color: (msg: string) => string) { + if (Logger.contextEnv === NestEnvironment.TEST) return; + + process.stdout.write(color(`[Nest] ${process.pid} - `)); + process.stdout.write(`${new Date(Date.now()).toLocaleString()} `); + process.stdout.write(this.yellow(`[${this.context}] `)); + process.stdout.write(color(message)); + + this.printTimestamp(); + process.stdout.write(`\n`); + } + + private printTimestamp() { + const includeTimestamp = Logger.lastTimestamp && this.printTimestamps; + if (includeTimestamp) { + process.stdout.write( + this.yellow(` +${Date.now() - Logger.lastTimestamp}ms`) + ); } + Logger.lastTimestamp = Date.now(); + } - private printMessage(message: string, color: (msg: string) => string) { - if (Logger.contextEnv === NestEnvironment.TEST) return; + private printStackTrace(trace: string) { + if (Logger.contextEnv === NestEnvironment.TEST || !trace) return; - process.stdout.write(color(`[Nest] ${process.pid} - `)); - process.stdout.write(`${new Date(Date.now()).toLocaleString()} `); - process.stdout.write(this.yellow(`[${this.context}] `)); - process.stdout.write(color(message)); - - this.printTimestamp(); - process.stdout.write(`\n`); - } - - private printTimestamp() { - const includeTimestamp = Logger.lastTimestamp && this.printTimestamps; - if (includeTimestamp) { - process.stdout.write(this.yellow(` +${Date.now() - Logger.lastTimestamp}ms`)); - } - Logger.lastTimestamp = Date.now(); - } - - private printStackTrace(trace: string) { - if (Logger.contextEnv === NestEnvironment.TEST || !trace) return; - - process.stdout.write(trace); - process.stdout.write(`\n`); - } -} \ No newline at end of file + process.stdout.write(trace); + process.stdout.write(`\n`); + } +} diff --git a/src/common/test/decorators/bind.decorator.spec.ts b/src/common/test/decorators/bind.decorator.spec.ts index 19eb78ed712..b4b757d7b4d 100644 --- a/src/common/test/decorators/bind.decorator.spec.ts +++ b/src/common/test/decorators/bind.decorator.spec.ts @@ -5,22 +5,21 @@ import { ROUTE_ARGS_METADATA } from '@nestjs/common/constants'; import { Req } from '../../decorators/http/route-params.decorator'; describe('@Bind', () => { - class TestWithMethod { - @Bind(Req()) - public test() {} - } + class TestWithMethod { + @Bind(Req()) + public test() {} + } - it('should enhance method - bind each decorator to method', () => { - const test = new TestWithMethod(); - const metadata = Reflect.getMetadata(ROUTE_ARGS_METADATA, test, 'test'); + it('should enhance method - bind each decorator to method', () => { + const test = new TestWithMethod(); + const metadata = Reflect.getMetadata(ROUTE_ARGS_METADATA, test, 'test'); - expect(metadata).to.be.deep.equal({ - '0:0': { - data: undefined, - index: 0, - pipes: [], - }, - }); + expect(metadata).to.be.deep.equal({ + '0:0': { + data: undefined, + index: 0, + pipes: [] + } }); - -}); \ No newline at end of file + }); +}); diff --git a/src/common/test/decorators/catch.decorator.spec.ts b/src/common/test/decorators/catch.decorator.spec.ts index 15d2612923a..dec7df0a44f 100644 --- a/src/common/test/decorators/catch.decorator.spec.ts +++ b/src/common/test/decorators/catch.decorator.spec.ts @@ -4,13 +4,13 @@ import { Catch } from '../../decorators/core/catch.decorator'; import { FILTER_CATCH_EXCEPTIONS } from '../../constants'; describe('@Catch', () => { - const exceptions = [ 'exception', 'exception2' ]; + const exceptions = ['exception', 'exception2']; - @Catch(...exceptions) class Test {} + @Catch(...exceptions) + class Test {} - it('should enhance class with expected exceptions array', () => { - const metadata = Reflect.getMetadata(FILTER_CATCH_EXCEPTIONS, Test); - expect(metadata).to.be.eql(exceptions); - }); - -}); \ No newline at end of file + it('should enhance class with expected exceptions array', () => { + const metadata = Reflect.getMetadata(FILTER_CATCH_EXCEPTIONS, Test); + expect(metadata).to.be.eql(exceptions); + }); +}); diff --git a/src/common/test/decorators/component.decorator.spec.ts b/src/common/test/decorators/component.decorator.spec.ts index 8f8b85f0ea3..b0b8736b640 100644 --- a/src/common/test/decorators/component.decorator.spec.ts +++ b/src/common/test/decorators/component.decorator.spec.ts @@ -3,71 +3,71 @@ import { expect } from 'chai'; import { Component, Middleware, Interceptor, mixin } from '../../index'; describe('@Component', () => { - @Component() - class TestComponent { - constructor(param: number, test: string) {} - } + @Component() + class TestComponent { + constructor(param: number, test: string) {} + } - it('should enhance component with "design:paramtypes" metadata', () => { - const constructorParams = Reflect.getMetadata( - 'design:paramtypes', - TestComponent, - ); + it('should enhance component with "design:paramtypes" metadata', () => { + const constructorParams = Reflect.getMetadata( + 'design:paramtypes', + TestComponent + ); - expect(constructorParams[0]).to.be.eql(Number); - expect(constructorParams[1]).to.be.eql(String); - }); + expect(constructorParams[0]).to.be.eql(Number); + expect(constructorParams[1]).to.be.eql(String); + }); }); describe('@Middleware', () => { - @Middleware() - class TestMiddleware { - constructor(param: number, test: string) {} - } + @Middleware() + class TestMiddleware { + constructor(param: number, test: string) {} + } - it('should enhance component with "design:paramtypes" metadata', () => { - const constructorParams = Reflect.getMetadata( - 'design:paramtypes', - TestMiddleware, - ); + it('should enhance component with "design:paramtypes" metadata', () => { + const constructorParams = Reflect.getMetadata( + 'design:paramtypes', + TestMiddleware + ); - expect(constructorParams[0]).to.be.eql(Number); - expect(constructorParams[1]).to.be.eql(String); - }); + expect(constructorParams[0]).to.be.eql(Number); + expect(constructorParams[1]).to.be.eql(String); + }); }); describe('@Interceptor', () => { - @Interceptor() - class TestInterceptor { - constructor(param: number, test: string) {} - } + @Interceptor() + class TestInterceptor { + constructor(param: number, test: string) {} + } - it('should enhance component with "design:paramtypes" metadata', () => { - const constructorParams = Reflect.getMetadata( - 'design:paramtypes', - TestInterceptor, - ); + it('should enhance component with "design:paramtypes" metadata', () => { + const constructorParams = Reflect.getMetadata( + 'design:paramtypes', + TestInterceptor + ); - expect(constructorParams[0]).to.be.eql(Number); - expect(constructorParams[1]).to.be.eql(String); - }); + expect(constructorParams[0]).to.be.eql(Number); + expect(constructorParams[1]).to.be.eql(String); + }); }); describe('mixin', () => { - @Interceptor() - class Test { - constructor(param: number, test: string) {} - } + @Interceptor() + class Test { + constructor(param: number, test: string) {} + } - it('should set name of metatype', () => { - const type = mixin(Test); - expect(type.name).to.not.eql('Test'); - }); + it('should set name of metatype', () => { + const type = mixin(Test); + expect(type.name).to.not.eql('Test'); + }); - it('should not lost the design:parmatypes metadata', () => { - const type = mixin(Test); - const constructorParams = Reflect.getMetadata('design:paramtypes', type); - expect(constructorParams[0]).to.be.eql(Number); - expect(constructorParams[1]).to.be.eql(String); - }); + it('should not lost the design:parmatypes metadata', () => { + const type = mixin(Test); + const constructorParams = Reflect.getMetadata('design:paramtypes', type); + expect(constructorParams[0]).to.be.eql(Number); + expect(constructorParams[1]).to.be.eql(String); + }); }); diff --git a/src/common/test/decorators/controller.decorator.spec.ts b/src/common/test/decorators/controller.decorator.spec.ts index d6e5dd0c834..7c8456b9cc4 100644 --- a/src/common/test/decorators/controller.decorator.spec.ts +++ b/src/common/test/decorators/controller.decorator.spec.ts @@ -3,18 +3,20 @@ import { expect } from 'chai'; import { Controller } from '../../decorators/core/controller.decorator'; describe('@Controller', () => { - const reflectedPath = 'test'; + const reflectedPath = 'test'; - @Controller(reflectedPath) class Test {} - @Controller() class EmptyDecorator {} + @Controller(reflectedPath) + class Test {} + @Controller() + class EmptyDecorator {} - it('should enhance controller with expected path metadata', () => { - const path = Reflect.getMetadata('path', Test); - expect(path).to.be.eql(reflectedPath); - }); + it('should enhance controller with expected path metadata', () => { + const path = Reflect.getMetadata('path', Test); + expect(path).to.be.eql(reflectedPath); + }); - it('should set default path when no object passed as param', () => { - const path = Reflect.getMetadata('path', EmptyDecorator); - expect(path).to.be.eql('/'); - }); -}); \ No newline at end of file + it('should set default path when no object passed as param', () => { + const path = Reflect.getMetadata('path', EmptyDecorator); + expect(path).to.be.eql('/'); + }); +}); diff --git a/src/common/test/decorators/dependencies.decorator.spec.ts b/src/common/test/decorators/dependencies.decorator.spec.ts index 369393cfa03..eac0171982b 100644 --- a/src/common/test/decorators/dependencies.decorator.spec.ts +++ b/src/common/test/decorators/dependencies.decorator.spec.ts @@ -4,19 +4,22 @@ import { Dependencies } from '../../decorators/core/dependencies.decorator'; import { PARAMTYPES_METADATA } from '../../constants'; describe('@Dependencies', () => { - const dep = 'test', dep2 = 'test2'; - const deps = [ dep, dep2 ]; + const dep = 'test', + dep2 = 'test2'; + const deps = [dep, dep2]; - @Dependencies(deps) class Test {} - @Dependencies(dep, dep2) class Test2 {} + @Dependencies(deps) + class Test {} + @Dependencies(dep, dep2) + class Test2 {} - it('should enhance class with expected dependencies array', () => { - const metadata = Reflect.getMetadata(PARAMTYPES_METADATA, Test); - expect(metadata).to.be.eql(deps); - }); + it('should enhance class with expected dependencies array', () => { + const metadata = Reflect.getMetadata(PARAMTYPES_METADATA, Test); + expect(metadata).to.be.eql(deps); + }); - it('should makes passed array flatten', () => { - const metadata = Reflect.getMetadata(PARAMTYPES_METADATA, Test2); - expect(metadata).to.be.eql([dep, dep2]); - }); -}); \ No newline at end of file + it('should makes passed array flatten', () => { + const metadata = Reflect.getMetadata(PARAMTYPES_METADATA, Test2); + expect(metadata).to.be.eql([dep, dep2]); + }); +}); diff --git a/src/common/test/decorators/exception-filters.decorator.spec.ts b/src/common/test/decorators/exception-filters.decorator.spec.ts index a6fb289b330..b11a0ce6ee9 100644 --- a/src/common/test/decorators/exception-filters.decorator.spec.ts +++ b/src/common/test/decorators/exception-filters.decorator.spec.ts @@ -4,23 +4,26 @@ import { EXCEPTION_FILTERS_METADATA } from '../../constants'; import { UseFilters } from '../../decorators/core/exception-filters.decorator'; describe('@UseFilters', () => { - const filters = [ 'exception', 'exception2' ]; + const filters = ['exception', 'exception2']; - @UseFilters(...filters as any) class Test {} + @UseFilters(...(filters as any)) + class Test {} - class TestWithMethod { - @UseFilters(...filters as any) - public static test() {} - } + class TestWithMethod { + @UseFilters(...(filters as any)) + public static test() {} + } - it('should enhance class with expected exception filters array', () => { - const metadata = Reflect.getMetadata(EXCEPTION_FILTERS_METADATA, Test); - expect(metadata).to.be.eql(filters); - }); + it('should enhance class with expected exception filters array', () => { + const metadata = Reflect.getMetadata(EXCEPTION_FILTERS_METADATA, Test); + expect(metadata).to.be.eql(filters); + }); - it('should enhance method with expected exception filters array', () => { - const metadata = Reflect.getMetadata(EXCEPTION_FILTERS_METADATA, TestWithMethod.test); - expect(metadata).to.be.eql(filters); - }); - -}); \ No newline at end of file + it('should enhance method with expected exception filters array', () => { + const metadata = Reflect.getMetadata( + EXCEPTION_FILTERS_METADATA, + TestWithMethod.test + ); + expect(metadata).to.be.eql(filters); + }); +}); diff --git a/src/common/test/decorators/global.decorator.spec.ts b/src/common/test/decorators/global.decorator.spec.ts index c2029445d10..a428122d00f 100644 --- a/src/common/test/decorators/global.decorator.spec.ts +++ b/src/common/test/decorators/global.decorator.spec.ts @@ -4,11 +4,11 @@ import { GLOBAL_MODULE_METADATA } from '../../constants'; import { Global } from '../../index'; describe('Global', () => { - @Global() - class Test {} + @Global() + class Test {} - it('should enrich metatype with GlobalModule metadata', () => { - const isGlobal = Reflect.getMetadata(GLOBAL_MODULE_METADATA, Test); - expect(isGlobal).to.be.true; - }); -}); \ No newline at end of file + it('should enrich metatype with GlobalModule metadata', () => { + const isGlobal = Reflect.getMetadata(GLOBAL_MODULE_METADATA, Test); + expect(isGlobal).to.be.true; + }); +}); diff --git a/src/common/test/decorators/http-code.decorator.spec.ts b/src/common/test/decorators/http-code.decorator.spec.ts index 8662d929454..289068e3fc3 100644 --- a/src/common/test/decorators/http-code.decorator.spec.ts +++ b/src/common/test/decorators/http-code.decorator.spec.ts @@ -4,15 +4,14 @@ import { HttpCode } from '../../decorators/http/http-code.decorator'; import { HTTP_CODE_METADATA } from '../../constants'; describe('@HttpCode', () => { - const httpCode = 200; - class Test { - @HttpCode(httpCode) - public static test() {} - } + const httpCode = 200; + class Test { + @HttpCode(httpCode) + public static test() {} + } - it('should enhance method with expected http status code', () => { - const metadata = Reflect.getMetadata(HTTP_CODE_METADATA, Test.test); - expect(metadata).to.be.eql(httpCode); - }); - -}); \ No newline at end of file + it('should enhance method with expected http status code', () => { + const metadata = Reflect.getMetadata(HTTP_CODE_METADATA, Test.test); + expect(metadata).to.be.eql(httpCode); + }); +}); diff --git a/src/common/test/decorators/inject.decorator.spec.ts b/src/common/test/decorators/inject.decorator.spec.ts index bf29e230d3c..a2dbf5b0ef4 100644 --- a/src/common/test/decorators/inject.decorator.spec.ts +++ b/src/common/test/decorators/inject.decorator.spec.ts @@ -4,23 +4,23 @@ import { SELF_DECLARED_DEPS_METADATA } from '../../constants'; import { Inject } from '../../index'; describe('@Inject', () => { - const opaqueToken = () => ({}); - class Test { - constructor( - @Inject('test') param, - @Inject('test2') param2, - @Inject(opaqueToken) param3) {} - } + const opaqueToken = () => ({}); + class Test { + constructor( + @Inject('test') param, + @Inject('test2') param2, + @Inject(opaqueToken) param3 + ) {} + } - it('should enhance class with expected constructor params metadata', () => { - const metadata = Reflect.getMetadata(SELF_DECLARED_DEPS_METADATA, Test); + it('should enhance class with expected constructor params metadata', () => { + const metadata = Reflect.getMetadata(SELF_DECLARED_DEPS_METADATA, Test); - const expectedMetadata = [ - { index: 2, param: opaqueToken.name }, - { index: 1, param: 'test2' }, - { index: 0, param: 'test' }, - ]; - expect(metadata).to.be.eql(expectedMetadata); - }); - -}); \ No newline at end of file + const expectedMetadata = [ + { index: 2, param: opaqueToken.name }, + { index: 1, param: 'test2' }, + { index: 0, param: 'test' } + ]; + expect(metadata).to.be.eql(expectedMetadata); + }); +}); diff --git a/src/common/test/decorators/module.decorator.spec.ts b/src/common/test/decorators/module.decorator.spec.ts index ead362974d0..cd2b1797cd5 100644 --- a/src/common/test/decorators/module.decorator.spec.ts +++ b/src/common/test/decorators/module.decorator.spec.ts @@ -4,35 +4,36 @@ import { Module } from '../../decorators/modules/module.decorator'; import { InvalidModuleConfigException } from '../../decorators/modules/exceptions/invalid-module-config.exception'; describe('@Module', () => { - const moduleProps = { - components: [ 'Test' ], - modules: [ 'Test' ], - exports: [ 'Test' ], - controllers: [ 'Test' ] - }; - - @Module(moduleProps) - class TestModule {} + const moduleProps = { + components: ['Test'], + modules: ['Test'], + exports: ['Test'], + controllers: ['Test'] + }; - it('should enhance class with expected module metadata', () => { - const modules = Reflect.getMetadata('modules', TestModule); - const components = Reflect.getMetadata('components', TestModule); - const exports = Reflect.getMetadata('exports', TestModule); - const controllers = Reflect.getMetadata('controllers', TestModule); + @Module(moduleProps) + class TestModule {} - expect(modules).to.be.eql(moduleProps.modules); - expect(components).to.be.eql(moduleProps.components); - expect(controllers).to.be.eql(moduleProps.controllers); - expect(exports).to.be.eql(moduleProps.exports); - }); + it('should enhance class with expected module metadata', () => { + const modules = Reflect.getMetadata('modules', TestModule); + const components = Reflect.getMetadata('components', TestModule); + const exports = Reflect.getMetadata('exports', TestModule); + const controllers = Reflect.getMetadata('controllers', TestModule); - it('should throw exception when module properties are invalid', () => { - const invalidProps = { - ...moduleProps, - test: [], - }; + expect(modules).to.be.eql(moduleProps.modules); + expect(components).to.be.eql(moduleProps.components); + expect(controllers).to.be.eql(moduleProps.controllers); + expect(exports).to.be.eql(moduleProps.exports); + }); - expect(Module.bind(null, invalidProps)).to.throw(InvalidModuleConfigException); - }); + it('should throw exception when module properties are invalid', () => { + const invalidProps = { + ...moduleProps, + test: [] + }; -}); \ No newline at end of file + expect(Module.bind(null, invalidProps)).to.throw( + InvalidModuleConfigException + ); + }); +}); diff --git a/src/common/test/decorators/reflect-metadata.decorator.spec.ts b/src/common/test/decorators/reflect-metadata.decorator.spec.ts index 89cbf36633c..594ee060c33 100644 --- a/src/common/test/decorators/reflect-metadata.decorator.spec.ts +++ b/src/common/test/decorators/reflect-metadata.decorator.spec.ts @@ -3,23 +3,24 @@ import { expect } from 'chai'; import { ReflectMetadata } from '../../decorators/core/reflect-metadata.decorator'; describe('@ReflectMetadata', () => { - const key = 'key', value = 'value'; + const key = 'key', + value = 'value'; - @ReflectMetadata(key, value) class Test {} + @ReflectMetadata(key, value) + class Test {} - class TestWithMethod { - @ReflectMetadata(key, value) - public static test() {} - } + class TestWithMethod { + @ReflectMetadata(key, value) + public static test() {} + } - it('should enhance class with expected metadata', () => { - const metadata = Reflect.getMetadata(key, Test); - expect(metadata).to.be.eql(value); - }); + it('should enhance class with expected metadata', () => { + const metadata = Reflect.getMetadata(key, Test); + expect(metadata).to.be.eql(value); + }); - it('should enhance method with expected metadata', () => { - const metadata = Reflect.getMetadata(key, TestWithMethod.test); - expect(metadata).to.be.eql(value); - }); - -}); \ No newline at end of file + it('should enhance method with expected metadata', () => { + const metadata = Reflect.getMetadata(key, TestWithMethod.test); + expect(metadata).to.be.eql(value); + }); +}); diff --git a/src/common/test/decorators/request-mapping.decorator.spec.ts b/src/common/test/decorators/request-mapping.decorator.spec.ts index 032034d2757..932378c116c 100644 --- a/src/common/test/decorators/request-mapping.decorator.spec.ts +++ b/src/common/test/decorators/request-mapping.decorator.spec.ts @@ -4,42 +4,41 @@ import { RequestMapping } from '../../decorators/http/request-mapping.decorator' import { RequestMethod } from '../../enums/request-method.enum'; describe('@RequestMapping', () => { - const requestProps = { - path: 'test', - method: RequestMethod.ALL, - }; - - it('should enhance class with expected request metadata', () => { - class Test { - @RequestMapping(requestProps) - public static test() {} - } - - const path = Reflect.getMetadata('path', Test.test); - const method = Reflect.getMetadata('method', Test.test); - - expect(method).to.be.eql(requestProps.method); - expect(path).to.be.eql(requestProps.path); - }); - - it('should set request method on GET by default', () => { - class Test { - @RequestMapping({ path: '' }) - public static test() {} - } - - const method = Reflect.getMetadata('method', Test.test); - expect(method).to.be.eql(RequestMethod.GET); - }); - - it('should set path on "/" by default', () => { - class Test { - @RequestMapping({}) - public static test() {} - } - - const method = Reflect.getMetadata('path', Test.test); - expect(method).to.be.eql('/'); - }); - -}); \ No newline at end of file + const requestProps = { + path: 'test', + method: RequestMethod.ALL + }; + + it('should enhance class with expected request metadata', () => { + class Test { + @RequestMapping(requestProps) + public static test() {} + } + + const path = Reflect.getMetadata('path', Test.test); + const method = Reflect.getMetadata('method', Test.test); + + expect(method).to.be.eql(requestProps.method); + expect(path).to.be.eql(requestProps.path); + }); + + it('should set request method on GET by default', () => { + class Test { + @RequestMapping({ path: '' }) + public static test() {} + } + + const method = Reflect.getMetadata('method', Test.test); + expect(method).to.be.eql(RequestMethod.GET); + }); + + it('should set path on "/" by default', () => { + class Test { + @RequestMapping({}) + public static test() {} + } + + const method = Reflect.getMetadata('path', Test.test); + expect(method).to.be.eql('/'); + }); +}); diff --git a/src/common/test/decorators/route-params.decorator.spec.ts b/src/common/test/decorators/route-params.decorator.spec.ts index 0810c470b2b..bb19ad4cb78 100644 --- a/src/common/test/decorators/route-params.decorator.spec.ts +++ b/src/common/test/decorators/route-params.decorator.spec.ts @@ -4,187 +4,181 @@ import { RequestMethod } from '../../enums/request-method.enum'; import { Get, Post, Delete, All, Put, Patch } from '../../index'; describe('@Get', () => { - const requestPath = 'test'; - const requestProps = { - path: requestPath, - method: RequestMethod.GET, - }; - - it('should enhance class with expected request metadata', () => { - class Test { - @Get(requestPath) - public static test() {} - } - - const path = Reflect.getMetadata('path', Test.test); - const method = Reflect.getMetadata('method', Test.test); - - expect(method).to.be.eql(requestProps.method); - expect(path).to.be.eql(requestPath); - }); - - it('should set path on "/" by default', () => { - class Test { - @Get() - public static test() {} - } - const path = Reflect.getMetadata('path', Test.test); - expect(path).to.be.eql('/'); - }); - + const requestPath = 'test'; + const requestProps = { + path: requestPath, + method: RequestMethod.GET + }; + + it('should enhance class with expected request metadata', () => { + class Test { + @Get(requestPath) + public static test() {} + } + + const path = Reflect.getMetadata('path', Test.test); + const method = Reflect.getMetadata('method', Test.test); + + expect(method).to.be.eql(requestProps.method); + expect(path).to.be.eql(requestPath); + }); + + it('should set path on "/" by default', () => { + class Test { + @Get() + public static test() {} + } + const path = Reflect.getMetadata('path', Test.test); + expect(path).to.be.eql('/'); + }); }); describe('@Post', () => { - const requestPath = 'test'; - const requestProps = { - path: requestPath, - method: RequestMethod.POST, - }; - - it('should enhance class with expected request metadata', () => { - class Test { - @Post(requestPath) - public static test() {} - } - - const path = Reflect.getMetadata('path', Test.test); - const method = Reflect.getMetadata('method', Test.test); - - expect(method).to.be.eql(requestProps.method); - expect(path).to.be.eql(requestPath); - }); - - it('should set path on "/" by default', () => { - class Test { - @Post() - public static test() {} - } - const path = Reflect.getMetadata('path', Test.test); - expect(path).to.be.eql('/'); - }); - + const requestPath = 'test'; + const requestProps = { + path: requestPath, + method: RequestMethod.POST + }; + + it('should enhance class with expected request metadata', () => { + class Test { + @Post(requestPath) + public static test() {} + } + + const path = Reflect.getMetadata('path', Test.test); + const method = Reflect.getMetadata('method', Test.test); + + expect(method).to.be.eql(requestProps.method); + expect(path).to.be.eql(requestPath); + }); + + it('should set path on "/" by default', () => { + class Test { + @Post() + public static test() {} + } + const path = Reflect.getMetadata('path', Test.test); + expect(path).to.be.eql('/'); + }); }); describe('@Delete', () => { - const requestPath = 'test'; - const requestProps = { - path: requestPath, - method: RequestMethod.DELETE, - }; - - it('should enhance class with expected request metadata', () => { - class Test { - @Delete(requestPath) - public static test() {} - } - - const path = Reflect.getMetadata('path', Test.test); - const method = Reflect.getMetadata('method', Test.test); - - expect(method).to.be.eql(requestProps.method); - expect(path).to.be.eql(requestPath); - }); - - it('should set path on "/" by default', () => { - class Test { - @Delete() - public static test() {} - } - const path = Reflect.getMetadata('path', Test.test); - expect(path).to.be.eql('/'); - }); - + const requestPath = 'test'; + const requestProps = { + path: requestPath, + method: RequestMethod.DELETE + }; + + it('should enhance class with expected request metadata', () => { + class Test { + @Delete(requestPath) + public static test() {} + } + + const path = Reflect.getMetadata('path', Test.test); + const method = Reflect.getMetadata('method', Test.test); + + expect(method).to.be.eql(requestProps.method); + expect(path).to.be.eql(requestPath); + }); + + it('should set path on "/" by default', () => { + class Test { + @Delete() + public static test() {} + } + const path = Reflect.getMetadata('path', Test.test); + expect(path).to.be.eql('/'); + }); }); describe('@All', () => { - const requestPath = 'test'; - const requestProps = { - path: requestPath, - method: RequestMethod.ALL, - }; - - it('should enhance class with expected request metadata', () => { - class Test { - @All(requestPath) - public static test() {} - } - - const path = Reflect.getMetadata('path', Test.test); - const method = Reflect.getMetadata('method', Test.test); - - expect(method).to.be.eql(requestProps.method); - expect(path).to.be.eql(requestPath); - }); - - it('should set path on "/" by default', () => { - class Test { - @All() - public static test() {} - } - const path = Reflect.getMetadata('path', Test.test); - expect(path).to.be.eql('/'); - }); - + const requestPath = 'test'; + const requestProps = { + path: requestPath, + method: RequestMethod.ALL + }; + + it('should enhance class with expected request metadata', () => { + class Test { + @All(requestPath) + public static test() {} + } + + const path = Reflect.getMetadata('path', Test.test); + const method = Reflect.getMetadata('method', Test.test); + + expect(method).to.be.eql(requestProps.method); + expect(path).to.be.eql(requestPath); + }); + + it('should set path on "/" by default', () => { + class Test { + @All() + public static test() {} + } + const path = Reflect.getMetadata('path', Test.test); + expect(path).to.be.eql('/'); + }); }); describe('@Put', () => { - const requestPath = 'test'; - const requestProps = { - path: requestPath, - method: RequestMethod.PUT, - }; - - it('should enhance class with expected request metadata', () => { - class Test { - @Put(requestPath) - public static test() {} - } - - const path = Reflect.getMetadata('path', Test.test); - const method = Reflect.getMetadata('method', Test.test); - - expect(method).to.be.eql(requestProps.method); - expect(path).to.be.eql(requestPath); - }); - - it('should set path on "/" by default', () => { - class Test { - @Put() - public static test() {} - } - const path = Reflect.getMetadata('path', Test.test); - expect(path).to.be.eql('/'); - }); - + const requestPath = 'test'; + const requestProps = { + path: requestPath, + method: RequestMethod.PUT + }; + + it('should enhance class with expected request metadata', () => { + class Test { + @Put(requestPath) + public static test() {} + } + + const path = Reflect.getMetadata('path', Test.test); + const method = Reflect.getMetadata('method', Test.test); + + expect(method).to.be.eql(requestProps.method); + expect(path).to.be.eql(requestPath); + }); + + it('should set path on "/" by default', () => { + class Test { + @Put() + public static test() {} + } + const path = Reflect.getMetadata('path', Test.test); + expect(path).to.be.eql('/'); + }); }); describe('@Patch', () => { - const requestPath = 'test'; - const requestProps = { - path: requestPath, - method: RequestMethod.PATCH, - }; - - it('should enhance class with expected request metadata', () => { - class Test { - @Patch(requestPath) - public static test() {} - } - - const path = Reflect.getMetadata('path', Test.test); - const method = Reflect.getMetadata('method', Test.test); - - expect(method).to.be.eql(requestProps.method); - expect(path).to.be.eql(requestPath); - }); - - it('should set path on "/" by default', () => { - class Test { - @Patch() - public static test() {} - } - const path = Reflect.getMetadata('path', Test.test); - expect(path).to.be.eql('/'); - }); - -}); \ No newline at end of file + const requestPath = 'test'; + const requestProps = { + path: requestPath, + method: RequestMethod.PATCH + }; + + it('should enhance class with expected request metadata', () => { + class Test { + @Patch(requestPath) + public static test() {} + } + + const path = Reflect.getMetadata('path', Test.test); + const method = Reflect.getMetadata('method', Test.test); + + expect(method).to.be.eql(requestProps.method); + expect(path).to.be.eql(requestPath); + }); + + it('should set path on "/" by default', () => { + class Test { + @Patch() + public static test() {} + } + const path = Reflect.getMetadata('path', Test.test); + expect(path).to.be.eql('/'); + }); +}); diff --git a/src/common/test/decorators/shared.decorator.spec.ts b/src/common/test/decorators/shared.decorator.spec.ts index f85c011050a..ae108b15fcc 100644 --- a/src/common/test/decorators/shared.decorator.spec.ts +++ b/src/common/test/decorators/shared.decorator.spec.ts @@ -4,18 +4,18 @@ import { Shared } from '../../decorators/modules/shared.decorator'; import { SHARED_MODULE_METADATA } from '../../constants'; describe('Shared', () => { - let type; - const token = '_'; - class Test {} + let type; + const token = '_'; + class Test {} - beforeEach(() => { - type = Shared(token)(Test); - }); - it('should enrich metatype with SharedModule token', () => { - const opaqueToken = Reflect.getMetadata(SHARED_MODULE_METADATA, type); - expect(opaqueToken).to.be.equal(token); - }); - it('should set name of the metatype', () => { - expect(type.name).to.eq(Test.name); - }); -}); \ No newline at end of file + beforeEach(() => { + type = Shared(token)(Test); + }); + it('should enrich metatype with SharedModule token', () => { + const opaqueToken = Reflect.getMetadata(SHARED_MODULE_METADATA, type); + expect(opaqueToken).to.be.equal(token); + }); + it('should set name of the metatype', () => { + expect(type.name).to.eq(Test.name); + }); +}); diff --git a/src/common/test/decorators/use-guards.decorator.spec.ts b/src/common/test/decorators/use-guards.decorator.spec.ts index 225b10b86ec..adeb814aefd 100644 --- a/src/common/test/decorators/use-guards.decorator.spec.ts +++ b/src/common/test/decorators/use-guards.decorator.spec.ts @@ -4,23 +4,23 @@ import { UseGuards } from '../../decorators/core/use-guards.decorator'; import { GUARDS_METADATA } from '../../constants'; describe('@UseGuards', () => { - const guards = [ 'guard1', 'guard2' ]; + const guards = ['guard1', 'guard2']; - @UseGuards(...guards as any) class Test {} + @UseGuards(...(guards as any)) + class Test {} - class TestWithMethod { - @UseGuards(...guards as any) - public static test() {} - } + class TestWithMethod { + @UseGuards(...(guards as any)) + public static test() {} + } - it('should enhance class with expected guards array', () => { - const metadata = Reflect.getMetadata(GUARDS_METADATA, Test); - expect(metadata).to.be.eql(guards); - }); + it('should enhance class with expected guards array', () => { + const metadata = Reflect.getMetadata(GUARDS_METADATA, Test); + expect(metadata).to.be.eql(guards); + }); - it('should enhance method with expected guards array', () => { - const metadata = Reflect.getMetadata(GUARDS_METADATA, TestWithMethod.test); - expect(metadata).to.be.eql(guards); - }); - -}); \ No newline at end of file + it('should enhance method with expected guards array', () => { + const metadata = Reflect.getMetadata(GUARDS_METADATA, TestWithMethod.test); + expect(metadata).to.be.eql(guards); + }); +}); diff --git a/src/common/test/decorators/use-interceptors.decorator.spec.ts b/src/common/test/decorators/use-interceptors.decorator.spec.ts index 27bf7a0e12a..f8a4284d808 100644 --- a/src/common/test/decorators/use-interceptors.decorator.spec.ts +++ b/src/common/test/decorators/use-interceptors.decorator.spec.ts @@ -4,23 +4,26 @@ import { UseInterceptors } from '../../decorators/core/use-interceptors.decorato import { INTERCEPTORS_METADATA } from '../../constants'; describe('@UseInterceptors', () => { - const interceptors = [ 'interceptor1', 'interceptor2' ]; + const interceptors = ['interceptor1', 'interceptor2']; - @UseInterceptors(...interceptors as any) class Test {} + @UseInterceptors(...(interceptors as any)) + class Test {} - class TestWithMethod { - @UseInterceptors(...interceptors as any) - public static test() {} - } + class TestWithMethod { + @UseInterceptors(...(interceptors as any)) + public static test() {} + } - it('should enhance class with expected interceptors array', () => { - const metadata = Reflect.getMetadata(INTERCEPTORS_METADATA, Test); - expect(metadata).to.be.eql(interceptors); - }); + it('should enhance class with expected interceptors array', () => { + const metadata = Reflect.getMetadata(INTERCEPTORS_METADATA, Test); + expect(metadata).to.be.eql(interceptors); + }); - it('should enhance method with expected interceptors array', () => { - const metadata = Reflect.getMetadata(INTERCEPTORS_METADATA, TestWithMethod.test); - expect(metadata).to.be.eql(interceptors); - }); - -}); \ No newline at end of file + it('should enhance method with expected interceptors array', () => { + const metadata = Reflect.getMetadata( + INTERCEPTORS_METADATA, + TestWithMethod.test + ); + expect(metadata).to.be.eql(interceptors); + }); +}); diff --git a/src/common/test/decorators/use-pipes.decorator.spec.ts b/src/common/test/decorators/use-pipes.decorator.spec.ts index 9426e6383ed..333b15fe536 100644 --- a/src/common/test/decorators/use-pipes.decorator.spec.ts +++ b/src/common/test/decorators/use-pipes.decorator.spec.ts @@ -4,23 +4,23 @@ import { UsePipes } from '../../decorators/core/use-pipes.decorator'; import { PIPES_METADATA } from '../../constants'; describe('@UsePipes', () => { - const pipes = [ 'pipe1', 'pipe2' ]; + const pipes = ['pipe1', 'pipe2']; - @UsePipes(...pipes as any) class Test {} + @UsePipes(...(pipes as any)) + class Test {} - class TestWithMethod { - @UsePipes(...pipes as any) - public static test() {} - } + class TestWithMethod { + @UsePipes(...(pipes as any)) + public static test() {} + } - it('should enhance class with expected pipes array', () => { - const metadata = Reflect.getMetadata(PIPES_METADATA, Test); - expect(metadata).to.be.eql(pipes); - }); + it('should enhance class with expected pipes array', () => { + const metadata = Reflect.getMetadata(PIPES_METADATA, Test); + expect(metadata).to.be.eql(pipes); + }); - it('should enhance method with expected pipes array', () => { - const metadata = Reflect.getMetadata(PIPES_METADATA, TestWithMethod.test); - expect(metadata).to.be.eql(pipes); - }); - -}); \ No newline at end of file + it('should enhance method with expected pipes array', () => { + const metadata = Reflect.getMetadata(PIPES_METADATA, TestWithMethod.test); + expect(metadata).to.be.eql(pipes); + }); +}); diff --git a/src/common/test/pipes/parse-int.pipe.spec.ts b/src/common/test/pipes/parse-int.pipe.spec.ts index e1ce281bb0e..176477664d7 100644 --- a/src/common/test/pipes/parse-int.pipe.spec.ts +++ b/src/common/test/pipes/parse-int.pipe.spec.ts @@ -4,24 +4,24 @@ import { ArgumentMetadata } from './../../interfaces'; import { ParseIntPipe } from './../../pipes/parse-int.pipe'; describe('ParseIntPipe', () => { - let target: ParseIntPipe; - beforeEach(() => { - target = new ParseIntPipe(); - }); - describe('transform', () => { - describe('when validation passes', () => { - it('should return number', async () => { - const num = '3'; - expect(await target.transform(num, {} as any)).to.equal( - parseInt(num, 10), - ); - }); - }); - describe('when validation vails', () => { - it('should throw an error', async () => { - return expect(target.transform('notanumber!', {} as any)).to.be - .rejected; - }); - }); - }); + let target: ParseIntPipe; + beforeEach(() => { + target = new ParseIntPipe(); + }); + describe('transform', () => { + describe('when validation passes', () => { + it('should return number', async () => { + const num = '3'; + expect(await target.transform(num, {} as any)).to.equal( + parseInt(num, 10) + ); + }); + }); + describe('when validation vails', () => { + it('should throw an error', async () => { + return expect(target.transform('notanumber!', {} as any)).to.be + .rejected; + }); + }); + }); }); diff --git a/src/common/test/pipes/validation.pipe.spec.ts b/src/common/test/pipes/validation.pipe.spec.ts index a8c55369672..e1ba9f127c5 100644 --- a/src/common/test/pipes/validation.pipe.spec.ts +++ b/src/common/test/pipes/validation.pipe.spec.ts @@ -5,37 +5,37 @@ import { IsString } from 'class-validator'; import { ValidationPipe } from './../../pipes/validation.pipe'; class TestModel { - constructor() {} - @IsString() public prop1: string; + constructor() {} + @IsString() public prop1: string; - @IsString() public prop2: string; + @IsString() public prop2: string; } describe('ValidationPipe', () => { - let target: ValidationPipe; - const metadata: ArgumentMetadata = { - type: 'body', - metatype: TestModel, - data: '', - }; - beforeEach(() => { - target = new ValidationPipe(); - }); - describe('transform', () => { - describe('when validation passes', () => { - it('should return the value unchanged', async () => { - const testObj = { prop1: 'value1', prop2: 'value2' }; - expect(await target.transform(testObj, {} as any)).to.equal(testObj); - expect(await target.transform(testObj, {} as any)).to.not.be.instanceOf( - TestModel, - ); - }); - }); - describe('when validation vails', () => { - it('should throw an error', async () => { - const testObj = { prop1: 'value1' }; - return expect(target.transform(testObj, metadata)).to.be.rejected; - }); - }); - }); + let target: ValidationPipe; + const metadata: ArgumentMetadata = { + type: 'body', + metatype: TestModel, + data: '' + }; + beforeEach(() => { + target = new ValidationPipe(); + }); + describe('transform', () => { + describe('when validation passes', () => { + it('should return the value unchanged', async () => { + const testObj = { prop1: 'value1', prop2: 'value2' }; + expect(await target.transform(testObj, {} as any)).to.equal(testObj); + expect(await target.transform(testObj, {} as any)).to.not.be.instanceOf( + TestModel + ); + }); + }); + describe('when validation vails', () => { + it('should throw an error', async () => { + const testObj = { prop1: 'value1' }; + return expect(target.transform(testObj, metadata)).to.be.rejected; + }); + }); + }); }); diff --git a/src/common/test/utils/bind-resolve-values.util.spec.ts b/src/common/test/utils/bind-resolve-values.util.spec.ts index dce2cfe3c61..a6b90e6dd7c 100644 --- a/src/common/test/utils/bind-resolve-values.util.spec.ts +++ b/src/common/test/utils/bind-resolve-values.util.spec.ts @@ -5,25 +5,25 @@ import { BindResolveMiddlewareValues } from '../../utils/bind-resolve-values.uti import { NestMiddleware } from '../../interfaces/middlewares/nest-middleware.interface'; describe('BindResolveMiddlewareValues', () => { - let type; - const arg1 = 3, - arg2 = 4; + let type; + const arg1 = 3, + arg2 = 4; - class Test implements NestMiddleware { - public resolve(a, b) { - return () => [a, b]; - } + class Test implements NestMiddleware { + public resolve(a, b) { + return () => [a, b]; } + } - beforeEach(() => { - type = BindResolveMiddlewareValues([ arg1, arg2 ])(Test); - }); - it('should pass values to resolve() method', () => { - const obj = new type(); - const hof = obj.resolve(); - expect(hof()).to.deep.equal([arg1, arg2]); - }); - it('should set name of metatype', () => { - expect(type.name).to.eq((Test as any).name + JSON.stringify([ arg1, arg2 ])); - }); -}); \ No newline at end of file + beforeEach(() => { + type = BindResolveMiddlewareValues([arg1, arg2])(Test); + }); + it('should pass values to resolve() method', () => { + const obj = new type(); + const hof = obj.resolve(); + expect(hof()).to.deep.equal([arg1, arg2]); + }); + it('should set name of metatype', () => { + expect(type.name).to.eq((Test as any).name + JSON.stringify([arg1, arg2])); + }); +}); diff --git a/src/common/test/utils/merge-with-values.util.spec.ts b/src/common/test/utils/merge-with-values.util.spec.ts index d78d4bbc15b..7103e7c3701 100644 --- a/src/common/test/utils/merge-with-values.util.spec.ts +++ b/src/common/test/utils/merge-with-values.util.spec.ts @@ -3,17 +3,17 @@ import { expect } from 'chai'; import { MergeWithValues } from '../../utils/merge-with-values.util'; describe('MergeWithValues', () => { - let type; - const data = { test: [ 1, 2, 3 ] }; - class Test {} + let type; + const data = { test: [1, 2, 3] }; + class Test {} - beforeEach(() => { - type = MergeWithValues(data)(Test); - }); - it('should enrich prototype with given values', () => { - expect(type.prototype).to.contain(data); - }); - it('should set name of metatype', () => { - expect(type.name).to.eq(Test.name + JSON.stringify(data)); - }); -}); \ No newline at end of file + beforeEach(() => { + type = MergeWithValues(data)(Test); + }); + it('should enrich prototype with given values', () => { + expect(type.prototype).to.contain(data); + }); + it('should set name of metatype', () => { + expect(type.name).to.eq(Test.name + JSON.stringify(data)); + }); +}); diff --git a/src/common/test/utils/shared.utils.spec.ts b/src/common/test/utils/shared.utils.spec.ts index bf0c48438ba..cfec1b3732f 100644 --- a/src/common/test/utils/shared.utils.spec.ts +++ b/src/common/test/utils/shared.utils.spec.ts @@ -1,71 +1,80 @@ import { expect } from 'chai'; -import { isUndefined, isFunction, isObject, isString, isConstructor, validatePath, isNil, isEmpty } from '../../utils/shared.utils'; +import { + isUndefined, + isFunction, + isObject, + isString, + isConstructor, + validatePath, + isNil, + isEmpty +} from '../../utils/shared.utils'; describe('Shared utils', () => { - describe('isUndefined', () => { - it('should returns true when obj is undefined', () => { - expect(isUndefined(undefined)).to.be.true; - }); - it('should returns false when object is not undefined', () => { - expect(isUndefined({})).to.be.false; - }); - }); - describe('isFunction', () => { - it('should returns true when obj is function', () => { - expect(isFunction(() => ({}))).to.be.true; - }); - it('should returns false when object is not function', () => { - expect(isFunction(null)).to.be.false; - }); - }); - describe('isObject', () => { - it('should returns true when obj is object', () => { - expect(isObject({})).to.be.true; - }); - it('should returns false when object is not object', () => { - expect(isObject(3)).to.be.false; - }); - }); - describe('isString', () => { - it('should returns true when obj is string', () => { - expect(isString('true')).to.be.true; - }); - it('should returns false when object is not string', () => { - expect(isString(false)).to.be.false; - }); - }); - describe('isConstructor', () => { - it('should returns true when string is equal constructor', () => { - expect(isConstructor('constructor')).to.be.true; - }); - it('should returns false when string is not equal constructor', () => { - expect(isConstructor('nope')).to.be.false; - }); - }); - describe('validatePath', () => { - it('should returns validated path ("add / if not exists")', () => { - expect(validatePath('nope')).to.be.eql('/nope'); - }); - it('should returns same path', () => { - expect(validatePath('/nope')).to.be.eql('/nope'); - }); - }); - describe('isNil', () => { - it('should returns true when obj is undefined or null', () => { - expect(isNil(undefined)).to.be.true; - expect(isNil(null)).to.be.true; - }); - it('should returns false when object is not undefined and null', () => { - expect(isNil('3')).to.be.false; - }); - }); - describe('isEmpty', () => { - it('should returns true when array is empty or not exists', () => { - expect(isEmpty([])).to.be.true; - expect(isEmpty(null)).to.be.true; - }); - it('should returns false when array is not empty', () => { - expect(isEmpty([1, 2])).to.be.false; - }); - }); -}); \ No newline at end of file + describe('isUndefined', () => { + it('should returns true when obj is undefined', () => { + expect(isUndefined(undefined)).to.be.true; + }); + it('should returns false when object is not undefined', () => { + expect(isUndefined({})).to.be.false; + }); + }); + describe('isFunction', () => { + it('should returns true when obj is function', () => { + expect(isFunction(() => ({}))).to.be.true; + }); + it('should returns false when object is not function', () => { + expect(isFunction(null)).to.be.false; + }); + }); + describe('isObject', () => { + it('should returns true when obj is object', () => { + expect(isObject({})).to.be.true; + }); + it('should returns false when object is not object', () => { + expect(isObject(3)).to.be.false; + }); + }); + describe('isString', () => { + it('should returns true when obj is string', () => { + expect(isString('true')).to.be.true; + }); + it('should returns false when object is not string', () => { + expect(isString(false)).to.be.false; + }); + }); + describe('isConstructor', () => { + it('should returns true when string is equal constructor', () => { + expect(isConstructor('constructor')).to.be.true; + }); + it('should returns false when string is not equal constructor', () => { + expect(isConstructor('nope')).to.be.false; + }); + }); + describe('validatePath', () => { + it('should returns validated path ("add / if not exists")', () => { + expect(validatePath('nope')).to.be.eql('/nope'); + }); + it('should returns same path', () => { + expect(validatePath('/nope')).to.be.eql('/nope'); + }); + }); + describe('isNil', () => { + it('should returns true when obj is undefined or null', () => { + expect(isNil(undefined)).to.be.true; + expect(isNil(null)).to.be.true; + }); + it('should returns false when object is not undefined and null', () => { + expect(isNil('3')).to.be.false; + }); + }); + describe('isEmpty', () => { + it('should returns true when array is empty or not exists', () => { + expect(isEmpty([])).to.be.true; + expect(isEmpty(null)).to.be.true; + }); + it('should returns false when array is not empty', () => { + expect(isEmpty([1, 2])).to.be.false; + }); + }); +}); diff --git a/src/common/utils/bind-resolve-values.util.ts b/src/common/utils/bind-resolve-values.util.ts index 85b43c7c592..7408e6bbbf0 100644 --- a/src/common/utils/bind-resolve-values.util.ts +++ b/src/common/utils/bind-resolve-values.util.ts @@ -2,16 +2,20 @@ import { Constructor } from './merge-with-values.util'; import { NestMiddleware } from '../interfaces/middlewares/nest-middleware.interface'; import { Component } from '../decorators/core/component.decorator'; -export const BindResolveMiddlewareValues = >(data: Array) => { - return (Metatype: T): any => { - const type = class extends Metatype { - public resolve() { - return super.resolve(...data); - } - }; - const token = Metatype.name + JSON.stringify(data); - Object.defineProperty(type, 'name', { value: token }); - Component()(type); - return type; +export const BindResolveMiddlewareValues = < + T extends Constructor +>( + data: Array +) => { + return (Metatype: T): any => { + const type = class extends Metatype { + public resolve() { + return super.resolve(...data); + } }; -}; \ No newline at end of file + const token = Metatype.name + JSON.stringify(data); + Object.defineProperty(type, 'name', { value: token }); + Component()(type); + return type; + }; +}; diff --git a/src/common/utils/forward-ref.util.ts b/src/common/utils/forward-ref.util.ts index 3ba17a58200..2424be167cd 100644 --- a/src/common/utils/forward-ref.util.ts +++ b/src/common/utils/forward-ref.util.ts @@ -2,4 +2,4 @@ import { isFunction } from './shared.utils'; export function forwardRef(fn: () => any) { return { forwardRef: fn }; -} \ No newline at end of file +} diff --git a/src/common/utils/http-exception-body.util.ts b/src/common/utils/http-exception-body.util.ts index 2d5809d12d2..03f21e39f9a 100644 --- a/src/common/utils/http-exception-body.util.ts +++ b/src/common/utils/http-exception-body.util.ts @@ -1,8 +1,8 @@ export const createHttpExceptionBody = ( - message: any, - error: string, - status: number, + message: any, + error: string, + status: number ) => - message - ? { statusCode: status, error, message } - : { statusCode: status, error }; + message + ? { statusCode: status, error, message } + : { statusCode: status, error }; diff --git a/src/common/utils/index.ts b/src/common/utils/index.ts index 9a90a9947d8..c8719691cd3 100644 --- a/src/common/utils/index.ts +++ b/src/common/utils/index.ts @@ -1 +1 @@ -export * from './forward-ref.util'; \ No newline at end of file +export * from './forward-ref.util'; diff --git a/src/common/utils/merge-with-values.util.ts b/src/common/utils/merge-with-values.util.ts index 00e5880c26a..968a9058603 100644 --- a/src/common/utils/merge-with-values.util.ts +++ b/src/common/utils/merge-with-values.util.ts @@ -1,19 +1,21 @@ import 'reflect-metadata'; export interface Constructor { - new(...args: any[]): T; + new (...args: any[]): T; } -export const MergeWithValues = >(data: { [param: string]: any }) => { - return (Metatype: T): any => { - const Type = class extends Metatype { - constructor(...args) { - super(...args); - } - }; - const token = Metatype.name + JSON.stringify(data); - Object.defineProperty(Type, 'name', { value: token }); - Object.assign(Type.prototype, data); - return Type; +export const MergeWithValues = >(data: { + [param: string]: any; +}) => { + return (Metatype: T): any => { + const Type = class extends Metatype { + constructor(...args) { + super(...args); + } }; + const token = Metatype.name + JSON.stringify(data); + Object.defineProperty(Type, 'name', { value: token }); + Object.assign(Type.prototype, data); + return Type; + }; }; diff --git a/src/common/utils/shared.utils.ts b/src/common/utils/shared.utils.ts index 6c83fc18a0c..d0dde7994b5 100644 --- a/src/common/utils/shared.utils.ts +++ b/src/common/utils/shared.utils.ts @@ -1,8 +1,10 @@ -export const isUndefined = (obj): obj is undefined => typeof obj === 'undefined'; +export const isUndefined = (obj): obj is undefined => + typeof obj === 'undefined'; export const isFunction = (fn): boolean => typeof fn === 'function'; export const isObject = (fn): fn is object => typeof fn === 'object'; export const isString = (fn): fn is string => typeof fn === 'string'; export const isConstructor = (fn): boolean => fn === 'constructor'; -export const validatePath = (path): string => (path.charAt(0) !== '/') ? '/' + path : path; +export const validatePath = (path): string => + path.charAt(0) !== '/' ? '/' + path : path; export const isNil = (obj): boolean => isUndefined(obj) || obj === null; -export const isEmpty = (array): boolean => !(array && array.length > 0); \ No newline at end of file +export const isEmpty = (array): boolean => !(array && array.length > 0); diff --git a/src/core/adapters/express-adapter.ts b/src/core/adapters/express-adapter.ts index 9868d4410f7..e628a3fa26b 100644 --- a/src/core/adapters/express-adapter.ts +++ b/src/core/adapters/express-adapter.ts @@ -1,11 +1,11 @@ import * as express from 'express'; export class ExpressAdapter { - public static create(): any { - return express(); - } + public static create(): any { + return express(); + } - public static createRouter(): any { - return express.Router({ mergeParams: true }); - } -} \ No newline at end of file + public static createRouter(): any { + return express.Router({ mergeParams: true }); + } +} diff --git a/src/core/application-config.ts b/src/core/application-config.ts index ba5e2710905..99f91fa2533 100644 --- a/src/core/application-config.ts +++ b/src/core/application-config.ts @@ -1,61 +1,67 @@ import * as optional from 'optional'; -import { PipeTransform, WebSocketAdapter, ExceptionFilter, NestInterceptor, CanActivate } from '@nestjs/common'; +import { + PipeTransform, + WebSocketAdapter, + ExceptionFilter, + NestInterceptor, + CanActivate +} from '@nestjs/common'; import { ConfigurationProvider } from '@nestjs/common/interfaces/configuration-provider.interface'; export class ApplicationConfig implements ConfigurationProvider { - private globalPipes: PipeTransform[] = []; - private globalFilters: ExceptionFilter[] = []; - private globalInterceptors: NestInterceptor[] = []; - private globalGuards: CanActivate[] = []; - private globalPrefix = ''; - - constructor(private ioAdapter: WebSocketAdapter | null = null) {} - - public setGlobalPrefix(prefix: string) { - this.globalPrefix = prefix; - } - - public getGlobalPrefix() { - return this.globalPrefix; - } - - public setIoAdapter(ioAdapter: WebSocketAdapter) { - this.ioAdapter = ioAdapter; - } - - public getIoAdapter(): WebSocketAdapter { - return this.ioAdapter; - } - - public useGlobalPipes(...pipes: PipeTransform[]) { - this.globalPipes = pipes; - } - - public getGlobalFilters(): ExceptionFilter[] { - return this.globalFilters; - } - - public useGlobalFilters(...filters: ExceptionFilter[]) { - this.globalFilters = filters; - } - - public getGlobalPipes(): PipeTransform[] { - return this.globalPipes; - } - - public getGlobalInterceptors(): NestInterceptor[] { - return this.globalInterceptors; - } - - public useGlobalInterceptors(...interceptors: NestInterceptor[]) { - this.globalInterceptors = interceptors; - } - - public getGlobalGuards(): CanActivate[] { - return this.globalGuards; - } - - public useGlobalGuards(...guards: CanActivate[]) { - this.globalGuards = guards; - } -} \ No newline at end of file + private globalPipes: PipeTransform[] = []; + private globalFilters: ExceptionFilter[] = []; + private globalInterceptors: NestInterceptor[] = []; + private globalGuards: CanActivate[] = []; + private globalPrefix = ''; + + constructor(private ioAdapter: WebSocketAdapter | null = null) {} + + public setGlobalPrefix(prefix: string) { + this.globalPrefix = prefix; + } + + public getGlobalPrefix() { + return this.globalPrefix; + } + + public setIoAdapter(ioAdapter: WebSocketAdapter) { + this.ioAdapter = ioAdapter; + } + + public getIoAdapter(): WebSocketAdapter { + return this.ioAdapter; + } + + public useGlobalPipes(...pipes: PipeTransform[]) { + this.globalPipes = pipes; + } + + public getGlobalFilters(): ExceptionFilter[] { + return this.globalFilters; + } + + public useGlobalFilters(...filters: ExceptionFilter[]) { + this.globalFilters = filters; + } + + public getGlobalPipes(): PipeTransform[] { + return this.globalPipes; + } + + public getGlobalInterceptors(): NestInterceptor[] { + return this.globalInterceptors; + } + + public useGlobalInterceptors(...interceptors: NestInterceptor[]) { + this.globalInterceptors = interceptors; + } + + public getGlobalGuards(): CanActivate[] { + return this.globalGuards; + } + + public useGlobalGuards(...guards: CanActivate[]) { + this.globalGuards = guards; + } +} diff --git a/src/core/constants.ts b/src/core/constants.ts index b31a0f9a5c9..b0eaea5217d 100644 --- a/src/core/constants.ts +++ b/src/core/constants.ts @@ -1,6 +1,6 @@ export const messages = { - APPLICATION_START: `Starting Nest application...`, - APPLICATION_READY: `Nest application successfully started`, - MICROSERVICE_READY: `Nest microservice successfully started`, - UNKNOWN_EXCEPTION_MESSAGE: 'Internal server error', -}; \ No newline at end of file + APPLICATION_START: `Starting Nest application...`, + APPLICATION_READY: `Nest application successfully started`, + MICROSERVICE_READY: `Nest microservice successfully started`, + UNKNOWN_EXCEPTION_MESSAGE: 'Internal server error' +}; diff --git a/src/core/errors/exception-handler.ts b/src/core/errors/exception-handler.ts index 438e2beb40a..3b1c47c003f 100644 --- a/src/core/errors/exception-handler.ts +++ b/src/core/errors/exception-handler.ts @@ -2,13 +2,13 @@ import { RuntimeException } from './exceptions/runtime.exception'; import { Logger } from '@nestjs/common/services/logger.service'; export class ExceptionHandler { - private static readonly logger = new Logger(ExceptionHandler.name); + private static readonly logger = new Logger(ExceptionHandler.name); - public handle(exception: RuntimeException | Error) { - if (!(exception instanceof RuntimeException)) { - ExceptionHandler.logger.error(exception.message, exception.stack); - return; - } - ExceptionHandler.logger.error(exception.what(), exception.stack); + public handle(exception: RuntimeException | Error) { + if (!(exception instanceof RuntimeException)) { + ExceptionHandler.logger.error(exception.message, exception.stack); + return; } -} \ No newline at end of file + ExceptionHandler.logger.error(exception.what(), exception.stack); + } +} diff --git a/src/core/errors/exceptions-zone.ts b/src/core/errors/exceptions-zone.ts index 13373d4e9d2..48dfd9a219c 100644 --- a/src/core/errors/exceptions-zone.ts +++ b/src/core/errors/exceptions-zone.ts @@ -2,25 +2,23 @@ import { ExceptionHandler } from './exception-handler'; import { UNHANDLED_RUNTIME_EXCEPTION } from './messages'; export class ExceptionsZone { - private static readonly exceptionHandler = new ExceptionHandler(); + private static readonly exceptionHandler = new ExceptionHandler(); - public static run(fn: () => void) { - try { - fn(); - } - catch (e) { - this.exceptionHandler.handle(e); - throw UNHANDLED_RUNTIME_EXCEPTION; - } + public static run(fn: () => void) { + try { + fn(); + } catch (e) { + this.exceptionHandler.handle(e); + throw UNHANDLED_RUNTIME_EXCEPTION; } + } - public static async asyncRun(fn: () => Promise) { - try { - await fn(); - } - catch (e) { - this.exceptionHandler.handle(e); - throw UNHANDLED_RUNTIME_EXCEPTION; - } + public static async asyncRun(fn: () => Promise) { + try { + await fn(); + } catch (e) { + this.exceptionHandler.handle(e); + throw UNHANDLED_RUNTIME_EXCEPTION; } -} \ No newline at end of file + } +} diff --git a/src/core/errors/exceptions/invalid-exception-filter.exception.ts b/src/core/errors/exceptions/invalid-exception-filter.exception.ts index 42425b3a84d..5ea36ff63fc 100644 --- a/src/core/errors/exceptions/invalid-exception-filter.exception.ts +++ b/src/core/errors/exceptions/invalid-exception-filter.exception.ts @@ -2,7 +2,7 @@ import { RuntimeException } from './runtime.exception'; import { INVALID_EXCEPTION_FILTER } from '../messages'; export class InvalidExceptionFilterException extends RuntimeException { - constructor() { - super(INVALID_EXCEPTION_FILTER); - } -} \ No newline at end of file + constructor() { + super(INVALID_EXCEPTION_FILTER); + } +} diff --git a/src/core/errors/exceptions/invalid-middleware-configuration.exception.ts b/src/core/errors/exceptions/invalid-middleware-configuration.exception.ts index 492fcbc91ba..91309b2acc1 100644 --- a/src/core/errors/exceptions/invalid-middleware-configuration.exception.ts +++ b/src/core/errors/exceptions/invalid-middleware-configuration.exception.ts @@ -2,7 +2,7 @@ import { RuntimeException } from './runtime.exception'; import { INVALID_MIDDLEWARE_CONFIGURATION } from '../messages'; export class InvalidMiddlewareConfigurationException extends RuntimeException { - constructor() { - super(INVALID_MIDDLEWARE_CONFIGURATION); - } -} \ No newline at end of file + constructor() { + super(INVALID_MIDDLEWARE_CONFIGURATION); + } +} diff --git a/src/core/errors/exceptions/invalid-middleware.exception.ts b/src/core/errors/exceptions/invalid-middleware.exception.ts index b65736f98a2..6d262149935 100644 --- a/src/core/errors/exceptions/invalid-middleware.exception.ts +++ b/src/core/errors/exceptions/invalid-middleware.exception.ts @@ -2,7 +2,7 @@ import { RuntimeException } from './runtime.exception'; import { InvalidMiddlewareMessage } from '../messages'; export class InvalidMiddlewareException extends RuntimeException { - constructor(name: string) { - super(InvalidMiddlewareMessage(name)); - } -} \ No newline at end of file + constructor(name: string) { + super(InvalidMiddlewareMessage(name)); + } +} diff --git a/src/core/errors/exceptions/invalid-module.exception.ts b/src/core/errors/exceptions/invalid-module.exception.ts index 0f39f32606f..a6c6aa88e7c 100644 --- a/src/core/errors/exceptions/invalid-module.exception.ts +++ b/src/core/errors/exceptions/invalid-module.exception.ts @@ -3,7 +3,7 @@ import { InvalidModuleMessage } from '../messages'; export class InvalidModuleException extends RuntimeException { constructor(trace: any[]) { - const scope = (trace || []).map((module) => module.name).join(' -> '); + const scope = (trace || []).map(module => module.name).join(' -> '); super(InvalidModuleMessage(scope)); } -} \ No newline at end of file +} diff --git a/src/core/errors/exceptions/microservices-package-not-found.exception.ts b/src/core/errors/exceptions/microservices-package-not-found.exception.ts index ce73f2d527c..f59b54ccc16 100644 --- a/src/core/errors/exceptions/microservices-package-not-found.exception.ts +++ b/src/core/errors/exceptions/microservices-package-not-found.exception.ts @@ -2,7 +2,7 @@ import { RuntimeException } from './runtime.exception'; import { MICROSERVICES_PACKAGE_NOT_FOUND_EXCEPTION } from '../messages'; export class MicroservicesPackageNotFoundException extends RuntimeException { - constructor() { - super(MICROSERVICES_PACKAGE_NOT_FOUND_EXCEPTION); - } -} \ No newline at end of file + constructor() { + super(MICROSERVICES_PACKAGE_NOT_FOUND_EXCEPTION); + } +} diff --git a/src/core/errors/exceptions/runtime.exception.ts b/src/core/errors/exceptions/runtime.exception.ts index 6237cfdb804..5194419af0f 100644 --- a/src/core/errors/exceptions/runtime.exception.ts +++ b/src/core/errors/exceptions/runtime.exception.ts @@ -1,16 +1,16 @@ export declare class Error { - public name: string; - public message: string; - public stack: string; - constructor(message?: string); + public name: string; + public message: string; + public stack: string; + constructor(message?: string); } export class RuntimeException extends Error { - constructor(private msg = ``) { - super(msg); - } + constructor(private msg = ``) { + super(msg); + } - public what() { - return this.msg; - } -} \ No newline at end of file + public what() { + return this.msg; + } +} diff --git a/src/core/errors/exceptions/undefined-dependency.exception.ts b/src/core/errors/exceptions/undefined-dependency.exception.ts index b8116f2f9f8..99dac6b2e4e 100644 --- a/src/core/errors/exceptions/undefined-dependency.exception.ts +++ b/src/core/errors/exceptions/undefined-dependency.exception.ts @@ -2,7 +2,7 @@ import { RuntimeException } from './runtime.exception'; import { UnknownDependenciesMessage } from '../messages'; export class UndefinedDependencyException extends RuntimeException { - constructor(type: string, index: number, length: number) { - super(UnknownDependenciesMessage(type, index, length)); - } -} \ No newline at end of file + constructor(type: string, index: number, length: number) { + super(UnknownDependenciesMessage(type, index, length)); + } +} diff --git a/src/core/errors/exceptions/unknown-dependencies.exception.ts b/src/core/errors/exceptions/unknown-dependencies.exception.ts index e2c52f2a9ed..28b3d438237 100644 --- a/src/core/errors/exceptions/unknown-dependencies.exception.ts +++ b/src/core/errors/exceptions/unknown-dependencies.exception.ts @@ -2,7 +2,7 @@ import { RuntimeException } from './runtime.exception'; import { UnknownDependenciesMessage } from '../messages'; export class UnknownDependenciesException extends RuntimeException { - constructor(type: string, index: number, length: number) { - super(UnknownDependenciesMessage(type, index, length)); - } -} \ No newline at end of file + constructor(type: string, index: number, length: number) { + super(UnknownDependenciesMessage(type, index, length)); + } +} diff --git a/src/core/errors/exceptions/unknown-export.exception.ts b/src/core/errors/exceptions/unknown-export.exception.ts index 3426df0338e..d68bde6091e 100644 --- a/src/core/errors/exceptions/unknown-export.exception.ts +++ b/src/core/errors/exceptions/unknown-export.exception.ts @@ -2,7 +2,7 @@ import { RuntimeException } from './runtime.exception'; import { UnknownExportMessage } from '../messages'; export class UnknownExportException extends RuntimeException { - constructor(name: string) { - super(UnknownExportMessage(name)); - } -} \ No newline at end of file + constructor(name: string) { + super(UnknownExportMessage(name)); + } +} diff --git a/src/core/errors/exceptions/unknown-module.exception.ts b/src/core/errors/exceptions/unknown-module.exception.ts index d237cd49b38..091bad81eff 100644 --- a/src/core/errors/exceptions/unknown-module.exception.ts +++ b/src/core/errors/exceptions/unknown-module.exception.ts @@ -1,7 +1,7 @@ import { RuntimeException } from './runtime.exception'; export class UnknownModuleException extends RuntimeException { - constructor() { - super(); - } -} \ No newline at end of file + constructor() { + super(); + } +} diff --git a/src/core/errors/exceptions/unknown-request-mapping.exception.ts b/src/core/errors/exceptions/unknown-request-mapping.exception.ts index fe7de4e3c8f..b0d64b2128c 100644 --- a/src/core/errors/exceptions/unknown-request-mapping.exception.ts +++ b/src/core/errors/exceptions/unknown-request-mapping.exception.ts @@ -2,7 +2,7 @@ import { RuntimeException } from './runtime.exception'; import { UNKNOWN_REQUEST_MAPPING } from '../messages'; export class UnknownRequestMappingException extends RuntimeException { - constructor() { - super(UNKNOWN_REQUEST_MAPPING); - } -} \ No newline at end of file + constructor() { + super(UNKNOWN_REQUEST_MAPPING); + } +} diff --git a/src/core/errors/messages.ts b/src/core/errors/messages.ts index 62b08e8fa70..780f0c4e67f 100644 --- a/src/core/errors/messages.ts +++ b/src/core/errors/messages.ts @@ -1,4 +1,8 @@ -export const UnknownDependenciesMessage = (type: string, index: number, length: number) => { +export const UnknownDependenciesMessage = ( + type: string, + index: number, + length: number +) => { let message = `Nest can't resolve dependencies of the ${type}`; message += ` (`; @@ -11,16 +15,16 @@ export const UnknownDependenciesMessage = (type: string, index: number, length: }; export const InvalidMiddlewareMessage = (name: string) => - `The middleware doesn't provide the 'resolve' method (${name})`; + `The middleware doesn't provide the 'resolve' method (${name})`; export const InvalidModuleMessage = (scope: string) => - `Nest can't create the module instance. The frequent reason of this exception is the circular dependency between modules. Use forwardRef() to avoid it (read more https://docs.nestjs.com/advanced/circular-dependency). Scope [${scope}]`; + `Nest can't create the module instance. The frequent reason of this exception is the circular dependency between modules. Use forwardRef() to avoid it (read more https://docs.nestjs.com/advanced/circular-dependency). Scope [${scope}]`; export const UnknownExportMessage = (name: string) => - `You are trying to export unknown component (${name}). Remember - your component should be listed both in exports and components arrays!`; + `You are trying to export unknown component (${name}). Remember - your component should be listed both in exports and components arrays!`; export const INVALID_MIDDLEWARE_CONFIGURATION = `Invalid middleware configuration passed inside the module 'configure()' method.`; export const UNKNOWN_REQUEST_MAPPING = `Request mapping properties not defined in the @RequestMapping() annotation!`; export const UNHANDLED_RUNTIME_EXCEPTION = `Unhandled Runtime Exception.`; export const INVALID_EXCEPTION_FILTER = `Invalid exception filters (@UseFilters()).`; -export const MICROSERVICES_PACKAGE_NOT_FOUND_EXCEPTION = `Unable to load @nestjs/microservices packages (please, make sure whether it's installed already).` \ No newline at end of file +export const MICROSERVICES_PACKAGE_NOT_FOUND_EXCEPTION = `Unable to load @nestjs/microservices packages (please, make sure whether it's installed already).`; diff --git a/src/core/exceptions/base-exception-filter-context.ts b/src/core/exceptions/base-exception-filter-context.ts index 8962e2a5ecf..65bf575106e 100644 --- a/src/core/exceptions/base-exception-filter-context.ts +++ b/src/core/exceptions/base-exception-filter-context.ts @@ -2,8 +2,15 @@ import 'reflect-metadata'; import iterate from 'iterare'; import { Controller } from '@nestjs/common/interfaces/controllers/controller.interface'; import { ExceptionsHandler } from '../exceptions/exceptions-handler'; -import { EXCEPTION_FILTERS_METADATA, FILTER_CATCH_EXCEPTIONS } from '@nestjs/common/constants'; -import { isEmpty, isFunction, isUndefined } from '@nestjs/common/utils/shared.utils'; +import { + EXCEPTION_FILTERS_METADATA, + FILTER_CATCH_EXCEPTIONS +} from '@nestjs/common/constants'; +import { + isEmpty, + isFunction, + isUndefined +} from '@nestjs/common/utils/shared.utils'; import { Metatype } from '@nestjs/common/interfaces/index'; import { ExceptionFilterMetadata } from '@nestjs/common/interfaces/exceptions/exception-filter-metadata.interface'; import { UnknownModuleException } from '../errors/exceptions/unknown-module.exception'; @@ -13,21 +20,25 @@ import { ContextCreator } from './../helpers/context-creator'; import { ApplicationConfig } from './../application-config'; export class BaseExceptionFilterContext extends ContextCreator { - public createConcreteContext(metadata: T): R { - if (isUndefined(metadata) || isEmpty(metadata)) { - return [] as R; - } - return iterate(metadata) - .filter((instance) => instance.catch && isFunction(instance.catch)) - .map((instance) => ({ - func: instance.catch.bind(instance), - exceptionMetatypes: this.reflectCatchExceptions(instance), - })) - .toArray() as R; + public createConcreteContext( + metadata: T + ): R { + if (isUndefined(metadata) || isEmpty(metadata)) { + return [] as R; } + return iterate(metadata) + .filter(instance => instance.catch && isFunction(instance.catch)) + .map(instance => ({ + func: instance.catch.bind(instance), + exceptionMetatypes: this.reflectCatchExceptions(instance) + })) + .toArray() as R; + } - public reflectCatchExceptions(instance: ExceptionFilter): Metatype[] { - const prototype = Object.getPrototypeOf(instance); - return Reflect.getMetadata(FILTER_CATCH_EXCEPTIONS, prototype.constructor) || []; - } -} \ No newline at end of file + public reflectCatchExceptions(instance: ExceptionFilter): Metatype[] { + const prototype = Object.getPrototypeOf(instance); + return ( + Reflect.getMetadata(FILTER_CATCH_EXCEPTIONS, prototype.constructor) || [] + ); + } +} diff --git a/src/core/exceptions/exceptions-handler.ts b/src/core/exceptions/exceptions-handler.ts index 88b6f1217d7..5d48451ea58 100644 --- a/src/core/exceptions/exceptions-handler.ts +++ b/src/core/exceptions/exceptions-handler.ts @@ -7,47 +7,59 @@ import { InvalidExceptionFilterException } from '../errors/exceptions/invalid-ex import { HttpException } from '@nestjs/common'; export class ExceptionsHandler { - private static readonly logger = new Logger(ExceptionsHandler.name); - private filters: ExceptionFilterMetadata[] = []; + private static readonly logger = new Logger(ExceptionsHandler.name); + private filters: ExceptionFilterMetadata[] = []; - public next(exception: Error | HttpException | any, response) { - if (this.invokeCustomFilters(exception, response)) return; + public next(exception: Error | HttpException | any, response) { + if (this.invokeCustomFilters(exception, response)) return; - if (!(exception instanceof HttpException || exception instanceof DeprecatedHttpException)) { - response.status(500).json({ - statusCode: 500, - message: messages.UNKNOWN_EXCEPTION_MESSAGE, - }); - if (isObject(exception) && (exception as Error).message) { - return ExceptionsHandler.logger.error((exception as Error).message, (exception as Error).stack); - } - return ExceptionsHandler.logger.error(exception); - } - const res = exception.getResponse(); - const message = isObject(res) ? res : ({ - statusCode: exception.getStatus(), - message: res, - }); - response.status(exception.getStatus()).json(message); + if ( + !( + exception instanceof HttpException || + exception instanceof DeprecatedHttpException + ) + ) { + response.status(500).json({ + statusCode: 500, + message: messages.UNKNOWN_EXCEPTION_MESSAGE + }); + if (isObject(exception) && (exception as Error).message) { + return ExceptionsHandler.logger.error( + (exception as Error).message, + (exception as Error).stack + ); + } + return ExceptionsHandler.logger.error(exception); } + const res = exception.getResponse(); + const message = isObject(res) + ? res + : { + statusCode: exception.getStatus(), + message: res + }; + response.status(exception.getStatus()).json(message); + } - public setCustomFilters(filters: ExceptionFilterMetadata[]) { - if (!Array.isArray(filters)) { - throw new InvalidExceptionFilterException(); - } - this.filters = filters; + public setCustomFilters(filters: ExceptionFilterMetadata[]) { + if (!Array.isArray(filters)) { + throw new InvalidExceptionFilterException(); } + this.filters = filters; + } - public invokeCustomFilters(exception, response): boolean { - if (isEmpty(this.filters)) return false; + public invokeCustomFilters(exception, response): boolean { + if (isEmpty(this.filters)) return false; - const filter = this.filters.find(({ exceptionMetatypes, func }) => { - const hasMetatype = !!exceptionMetatypes.find( - ExceptionMetatype => exception instanceof ExceptionMetatype, - ); - return hasMetatype; - }); - filter && filter.func(exception, response); - return !!filter; - } + const filter = this.filters.find(({ exceptionMetatypes, func }) => { + const hasMetatype = + !exceptionMetatypes.length || + !!exceptionMetatypes.find( + ExceptionMetatype => exception instanceof ExceptionMetatype + ); + return hasMetatype; + }); + filter && filter.func(exception, response); + return !!filter; + } } diff --git a/src/core/exceptions/http-exception.ts b/src/core/exceptions/http-exception.ts index a6057e9577a..01067596028 100644 --- a/src/core/exceptions/http-exception.ts +++ b/src/core/exceptions/http-exception.ts @@ -19,17 +19,19 @@ export class HttpException { * @deprecated */ constructor( - private readonly response: string | object, - private readonly status: number, + private readonly response: string | object, + private readonly status: number ) { - this.logger.warn('DEPRECATED! Since version [4.3.2] HttpException class was moved to the @nestjs/common package!'); + this.logger.warn( + 'DEPRECATED! Since version [4.3.2] HttpException class was moved to the @nestjs/common package!' + ); } public getResponse(): string | object { - return this.response; + return this.response; } public getStatus(): number { - return this.status; + return this.status; } } diff --git a/src/core/guards/constants.ts b/src/core/guards/constants.ts index e9655620241..3ad49aa8f7b 100644 --- a/src/core/guards/constants.ts +++ b/src/core/guards/constants.ts @@ -1 +1 @@ -export const FORBIDDEN_MESSAGE = 'Forbidden resource'; \ No newline at end of file +export const FORBIDDEN_MESSAGE = 'Forbidden resource'; diff --git a/src/core/guards/guards-consumer.ts b/src/core/guards/guards-consumer.ts index 7ac769e4a00..07164403390 100644 --- a/src/core/guards/guards-consumer.ts +++ b/src/core/guards/guards-consumer.ts @@ -1,6 +1,11 @@ import iterate from 'iterare'; import { GUARDS_METADATA } from '@nestjs/common/constants'; -import { isUndefined, isFunction, isNil, isEmpty } from '@nestjs/common/utils/shared.utils'; +import { + isUndefined, + isFunction, + isNil, + isEmpty +} from '@nestjs/common/utils/shared.utils'; import { Controller } from '@nestjs/common/interfaces'; import { CanActivate, HttpStatus, ExecutionContext } from '@nestjs/common'; import { Observable } from 'rxjs/Observable'; @@ -8,35 +13,45 @@ import { FORBIDDEN_MESSAGE } from './constants'; import 'rxjs/add/operator/toPromise'; export class GuardsConsumer { - public async tryActivate(guards: CanActivate[], data, instance: Controller, callback: (...args) => any): Promise { - if (!guards || isEmpty(guards)) { - return true; - } - const context = this.createContext(instance, callback); - for (const guard of guards) { - const result = guard.canActivate(data, context); - if (await this.pickResult(result)) { - continue; - } - return false; - } - return true; + public async tryActivate( + guards: CanActivate[], + data, + instance: Controller, + callback: (...args) => any + ): Promise { + if (!guards || isEmpty(guards)) { + return true; } - - public createContext(instance: Controller, callback: (...args) => any): ExecutionContext { - return { - parent: instance.constructor, - handler: callback, - }; + const context = this.createContext(instance, callback); + for (const guard of guards) { + const result = guard.canActivate(data, context); + if (await this.pickResult(result)) { + continue; + } + return false; } + return true; + } + + public createContext( + instance: Controller, + callback: (...args) => any + ): ExecutionContext { + return { + parent: instance.constructor, + handler: callback + }; + } - public async pickResult(result: boolean | Promise | Observable): Promise { - if (result instanceof Observable) { - return await result.toPromise(); - } - if (result instanceof Promise) { - return await result; - } - return result; + public async pickResult( + result: boolean | Promise | Observable + ): Promise { + if (result instanceof Observable) { + return await result.toPromise(); + } + if (result instanceof Promise) { + return await result; } -} \ No newline at end of file + return result; + } +} diff --git a/src/core/guards/guards-context-creator.ts b/src/core/guards/guards-context-creator.ts index a1976cb1c19..e9fa40fed1c 100644 --- a/src/core/guards/guards-context-creator.ts +++ b/src/core/guards/guards-context-creator.ts @@ -2,60 +2,79 @@ import 'reflect-metadata'; import iterate from 'iterare'; import { Controller } from '@nestjs/common/interfaces'; import { GUARDS_METADATA } from '@nestjs/common/constants'; -import { isUndefined, isFunction, isNil, isEmpty } from '@nestjs/common/utils/shared.utils'; +import { + isUndefined, + isFunction, + isNil, + isEmpty +} from '@nestjs/common/utils/shared.utils'; import { ContextCreator } from './../helpers/context-creator'; import { NestContainer } from '../injector/container'; import { CanActivate } from '@nestjs/common'; import { ConfigurationProvider } from '@nestjs/common/interfaces/configuration-provider.interface'; export class GuardsContextCreator extends ContextCreator { - private moduleContext: string; + private moduleContext: string; - constructor( - private readonly container: NestContainer, - private readonly config?: ConfigurationProvider) { - super(); - } + constructor( + private readonly container: NestContainer, + private readonly config?: ConfigurationProvider + ) { + super(); + } - public create(instance: Controller, callback: (...args) => any, module: string): CanActivate[] { - this.moduleContext = module; - return this.createContext(instance, callback, GUARDS_METADATA); - } + public create( + instance: Controller, + callback: (...args) => any, + module: string + ): CanActivate[] { + this.moduleContext = module; + return this.createContext(instance, callback, GUARDS_METADATA); + } - public createConcreteContext(metadata: T): R { - if (isUndefined(metadata) || isEmpty(metadata) || !this.moduleContext) { - return [] as R; - } - const isGlobalMetadata = metadata === this.getGlobalMetadata(); - return isGlobalMetadata ? - this.createGlobalMetadataContext(metadata) : - iterate(metadata).filter((metatype: any) => metatype && metatype.name) - .map((metatype) => this.getInstanceByMetatype(metatype)) - .filter((wrapper: any) => wrapper && wrapper.instance) - .map((wrapper) => wrapper.instance) - .filter((guard: CanActivate) => guard && isFunction(guard.canActivate)) - .toArray() as R; + public createConcreteContext( + metadata: T + ): R { + if (isUndefined(metadata) || isEmpty(metadata) || !this.moduleContext) { + return [] as R; } + const isGlobalMetadata = metadata === this.getGlobalMetadata(); + return isGlobalMetadata + ? this.createGlobalMetadataContext(metadata) + : (iterate(metadata) + .filter((metatype: any) => metatype && metatype.name) + .map(metatype => this.getInstanceByMetatype(metatype)) + .filter((wrapper: any) => wrapper && wrapper.instance) + .map(wrapper => wrapper.instance) + .filter( + (guard: CanActivate) => guard && isFunction(guard.canActivate) + ) + .toArray() as R); + } - public createGlobalMetadataContext(metadata: T): R { - return iterate(metadata) - .filter((guard) => guard && guard.canActivate && isFunction(guard.canActivate)) - .toArray() as R; - } + public createGlobalMetadataContext( + metadata: T + ): R { + return iterate(metadata) + .filter( + guard => guard && guard.canActivate && isFunction(guard.canActivate) + ) + .toArray() as R; + } - public getInstanceByMetatype(metatype): { instance: any } | undefined { - const collection = this.container.getModules(); - const module = collection.get(this.moduleContext); - if (!module) { - return undefined; - } - return module.injectables.get((metatype as any).name); + public getInstanceByMetatype(metatype): { instance: any } | undefined { + const collection = this.container.getModules(); + const module = collection.get(this.moduleContext); + if (!module) { + return undefined; } + return module.injectables.get((metatype as any).name); + } - public getGlobalMetadata(): T { - if (!this.config) { - return [] as T; - } - return this.config.getGlobalGuards() as T; + public getGlobalMetadata(): T { + if (!this.config) { + return [] as T; } -} \ No newline at end of file + return this.config.getGlobalGuards() as T; + } +} diff --git a/src/core/helpers/context-creator.ts b/src/core/helpers/context-creator.ts index b26b62fb1fa..45edee82d43 100644 --- a/src/core/helpers/context-creator.ts +++ b/src/core/helpers/context-creator.ts @@ -5,30 +5,36 @@ import { isUndefined, isFunction } from '@nestjs/common/utils/shared.utils'; import { ApplicationConfig } from './../application-config'; export abstract class ContextCreator { - public abstract createConcreteContext(metadata: T): R; - public getGlobalMetadata?(): T; + public abstract createConcreteContext( + metadata: T + ): R; + public getGlobalMetadata?(): T; - public createContext( - instance: Controller, - callback: (...args) => any, - metadataKey: string): R { + public createContext( + instance: Controller, + callback: (...args) => any, + metadataKey: string + ): R { + const globalMetadata = + this.getGlobalMetadata && this.getGlobalMetadata(); + const classMetadata = this.reflectClassMetadata(instance, metadataKey); + const methodMetadata = this.reflectMethodMetadata(callback, metadataKey); + return [ + ...this.createConcreteContext(globalMetadata || ([] as T)), + ...this.createConcreteContext(classMetadata), + ...this.createConcreteContext(methodMetadata) + ] as R; + } - const globalMetadata = this.getGlobalMetadata && this.getGlobalMetadata(); - const classMetadata = this.reflectClassMetadata(instance, metadataKey); - const methodMetadata = this.reflectMethodMetadata(callback, metadataKey); - return [ - ...this.createConcreteContext(globalMetadata || [] as T), - ...this.createConcreteContext(classMetadata), - ...this.createConcreteContext(methodMetadata), - ] as R; - } + public reflectClassMetadata(instance: Controller, metadataKey: string): T { + const prototype = Object.getPrototypeOf(instance); + return Reflect.getMetadata(metadataKey, prototype.constructor); + } - public reflectClassMetadata(instance: Controller, metadataKey: string): T { - const prototype = Object.getPrototypeOf(instance); - return Reflect.getMetadata(metadataKey, prototype.constructor); - } - - public reflectMethodMetadata(callback: (...args) => any, metadataKey: string): T { - return Reflect.getMetadata(metadataKey, callback); - } -} \ No newline at end of file + public reflectMethodMetadata( + callback: (...args) => any, + metadataKey: string + ): T { + return Reflect.getMetadata(metadataKey, callback); + } +} diff --git a/src/core/helpers/external-context-creator.ts b/src/core/helpers/external-context-creator.ts index a858270dee6..394d41945d7 100644 --- a/src/core/helpers/external-context-creator.ts +++ b/src/core/helpers/external-context-creator.ts @@ -10,67 +10,67 @@ import { Module } from './../injector/module'; import { ModulesContainer } from './../injector/modules-container'; export class ExternalContextCreator { - constructor( - private readonly guardsContextCreator: GuardsContextCreator, - private readonly guardsConsumer: GuardsConsumer, - private readonly interceptorsContextCreator: InterceptorsContextCreator, - private readonly interceptorsConsumer: InterceptorsConsumer, - private readonly modulesContainer: ModulesContainer, - ) {} + constructor( + private readonly guardsContextCreator: GuardsContextCreator, + private readonly guardsConsumer: GuardsConsumer, + private readonly interceptorsContextCreator: InterceptorsContextCreator, + private readonly interceptorsConsumer: InterceptorsConsumer, + private readonly modulesContainer: ModulesContainer + ) {} - public create( - instance: Controller, - callback: (...args) => any, - methodName: string, - ) { - const module = this.findContextModuleName(instance.constructor); - const guards = this.guardsContextCreator.create(instance, callback, module); - const interceptors = this.interceptorsContextCreator.create( - instance, - callback, - module, - ); - return async (...args) => { - const [req] = args; - const canActivate = await this.guardsConsumer.tryActivate( - guards, - req, - instance, - callback, - ); - if (!canActivate) { - throw new HttpException(FORBIDDEN_MESSAGE, HttpStatus.FORBIDDEN); - } + public create( + instance: Controller, + callback: (...args) => any, + methodName: string + ) { + const module = this.findContextModuleName(instance.constructor); + const guards = this.guardsContextCreator.create(instance, callback, module); + const interceptors = this.interceptorsContextCreator.create( + instance, + callback, + module + ); + return async (...args) => { + const [req] = args; + const canActivate = await this.guardsConsumer.tryActivate( + guards, + req, + instance, + callback + ); + if (!canActivate) { + throw new HttpException(FORBIDDEN_MESSAGE, HttpStatus.FORBIDDEN); + } - const handler = () => callback.apply(instance, args); - return await this.interceptorsConsumer.intercept( - interceptors, - req, - instance, - callback, - handler, - ); - }; - } + const handler = () => callback.apply(instance, args); + return await this.interceptorsConsumer.intercept( + interceptors, + req, + instance, + callback, + handler + ); + }; + } - public findContextModuleName(constructor: Function): string { - const className = constructor.name; - if (!className) { - return ''; - } - for (const [key, module] of [...this.modulesContainer.entries()]) { - if (this.findComponentByClassName(module, className)) { - return key; - } - } - return ''; - } + public findContextModuleName(constructor: Function): string { + const className = constructor.name; + if (!className) { + return ''; + } + for (const [key, module] of [...this.modulesContainer.entries()]) { + if (this.findComponentByClassName(module, className)) { + return key; + } + } + return ''; + } - public findComponentByClassName(module: Module, className: string): boolean { - const { components } = module; - const hasComponent = [...components.keys()].find( - component => component === className, - ); - return !!hasComponent; - } + public findComponentByClassName(module: Module, className: string): boolean { + const { components } = module; + const hasComponent = [...components.keys()].find( + component => component === className + ); + return !!hasComponent; + } } diff --git a/src/core/helpers/messages.ts b/src/core/helpers/messages.ts index 0451609e07c..d01b3efd2b8 100644 --- a/src/core/helpers/messages.ts +++ b/src/core/helpers/messages.ts @@ -1,5 +1,8 @@ import { RequestMethod } from '@nestjs/common/enums/request-method.enum'; -export const ModuleInitMessage = (module: string) => `${module} dependencies initialized`; -export const RouteMappedMessage = (path: string, method) => `Mapped {${path}, ${RequestMethod[method]}} route`; -export const ControllerMappingMessage = (name: string, path: string) => `${name} {${path}}:`; \ No newline at end of file +export const ModuleInitMessage = (module: string) => + `${module} dependencies initialized`; +export const RouteMappedMessage = (path: string, method) => + `Mapped {${path}, ${RequestMethod[method]}} route`; +export const ControllerMappingMessage = (name: string, path: string) => + `${name} {${path}}:`; diff --git a/src/core/helpers/router-method-factory.ts b/src/core/helpers/router-method-factory.ts index d3930029ba9..ddb2b680965 100644 --- a/src/core/helpers/router-method-factory.ts +++ b/src/core/helpers/router-method-factory.ts @@ -1,18 +1,25 @@ import { RequestMethod } from '@nestjs/common/enums/request-method.enum'; export class RouterMethodFactory { - public get(target, requestMethod: RequestMethod) { - switch (requestMethod) { - case RequestMethod.POST: return target.post; - case RequestMethod.ALL: return target.all; - case RequestMethod.DELETE: return target.delete; - case RequestMethod.PUT: return target.put; - case RequestMethod.PATCH: return target.patch; - case RequestMethod.OPTIONS: return target.options; - case RequestMethod.HEAD: return target.head; - default: { - return target.get; - } - } + public get(target, requestMethod: RequestMethod) { + switch (requestMethod) { + case RequestMethod.POST: + return target.post; + case RequestMethod.ALL: + return target.all; + case RequestMethod.DELETE: + return target.delete; + case RequestMethod.PUT: + return target.put; + case RequestMethod.PATCH: + return target.patch; + case RequestMethod.OPTIONS: + return target.options; + case RequestMethod.HEAD: + return target.head; + default: { + return target.get; + } } -} \ No newline at end of file + } +} diff --git a/src/core/index.ts b/src/core/index.ts index 52bae15e0a9..ceba4f70a22 100644 --- a/src/core/index.ts +++ b/src/core/index.ts @@ -11,4 +11,4 @@ export { ModuleRef } from './injector/module-ref'; export * from './services/reflector.service'; export * from './nest-factory'; export * from './nest-application'; -export * from './nest-application-context'; \ No newline at end of file +export * from './nest-application-context'; diff --git a/src/core/injector/container.ts b/src/core/injector/container.ts index 667576c35af..2be0caf9450 100644 --- a/src/core/injector/container.ts +++ b/src/core/injector/container.ts @@ -13,157 +13,176 @@ import { DynamicModule } from '@nestjs/common'; import { ModulesContainer } from './modules-container'; export class NestContainer { - private readonly globalModules = new Set(); - private readonly modules = new ModulesContainer(); - private readonly dynamicModulesMetadata = new Map>(); - private readonly moduleTokenFactory = new ModuleTokenFactory(); - - public addModule(metatype: NestModuleMetatype | DynamicModule, scope: NestModuleMetatype[]) { - if (!metatype) { - throw new InvalidModuleException(scope); - } - const { type, dynamicMetadata } = this.extractMetadata(metatype); - const token = this.moduleTokenFactory.create(type, scope, dynamicMetadata); - if (this.modules.has(token)) { - return; - } - const module = new Module(type, scope, this); - this.modules.set(token, module); - - this.addDynamicMetadata(token, dynamicMetadata); - this.isGlobalModule(type) && this.addGlobalModule(module); - } - - public extractMetadata( - metatype: NestModuleMetatype | DynamicModule, - ): { type: NestModuleMetatype, dynamicMetadata?: Partial | undefined } { - if (!this.isDynamicModule(metatype)) { - return { type: metatype }; - } - const { module: type, ...dynamicMetadata } = metatype; - return { type, dynamicMetadata }; - } - - public isDynamicModule(module: NestModuleMetatype | DynamicModule): module is DynamicModule { - return (module as DynamicModule).module; - } - - public addDynamicMetadata(token: string, dynamicModuleMetadata: Partial) { - if (!dynamicModuleMetadata) { - return undefined; - } - this.dynamicModulesMetadata.set(token, dynamicModuleMetadata); - } - - public isGlobalModule(metatype: NestModuleMetatype): boolean { - return !!Reflect.getMetadata(GLOBAL_MODULE_METADATA, metatype); - } - - public addGlobalModule(module: Module) { - this.globalModules.add(module); - } - - public getModules(): ModulesContainer { - return this.modules; - } - - public addRelatedModule( - relatedModule: NestModuleMetatype | DynamicModule, - token: string, - ) { - if (!this.modules.has(token)) return; - - const module = this.modules.get(token); - const parent = module.metatype; - - const { type, dynamicMetadata } = this.extractMetadata(relatedModule); - const relatedModuleToken = this.moduleTokenFactory.create( - type, - [].concat(module.scope, parent), - dynamicMetadata, - ); - const related = this.modules.get(relatedModuleToken); - module.addRelatedModule(related); - } - - public addComponent(component: Metatype, token: string) { - if (!this.modules.has(token)) { - throw new UnknownModuleException(); - } - const module = this.modules.get(token); - module.addComponent(component); - } - - public addInjectable(injectable: Metatype, token: string) { - if (!this.modules.has(token)) { - throw new UnknownModuleException(); - } - const module = this.modules.get(token); - module.addInjectable(injectable); - } - - public addExportedComponent(exportedComponent: Metatype, token: string) { - if (!this.modules.has(token)) { - throw new UnknownModuleException(); - } - const module = this.modules.get(token); - module.addExportedComponent(exportedComponent); - } - - public addController(controller: Metatype, token: string) { - if (!this.modules.has(token)) { - throw new UnknownModuleException(); - } - const module = this.modules.get(token); - module.addRoute(controller); - } - - public clear() { - this.modules.clear(); - } - - public replace(toReplace, options: any & { scope: any[] | null }) { - [...this.modules.values()].forEach((module) => { - module.replace(toReplace, options); - }); - } - - public bindGlobalScope() { - this.modules.forEach((module) => this.bindGlobalsToRelatedModules(module)); - } - - public bindGlobalsToRelatedModules(module: Module) { - this.globalModules.forEach((globalModule) => this.bindGlobalModuleToModule(module, globalModule)); - } - - public bindGlobalModuleToModule(module: Module, globalModule: Module) { - if (module === globalModule) { - return undefined; - } - module.addRelatedModule(globalModule); - } - - public getDynamicMetadataByToken( - token: string, - metadataKey: keyof DynamicModule, - ): any[] { - const metadata = this.dynamicModulesMetadata.get(token); - if (metadata && metadata[metadataKey]) { - return metadata[metadataKey]; - } - return []; - } + private readonly globalModules = new Set(); + private readonly modules = new ModulesContainer(); + private readonly dynamicModulesMetadata = new Map< + string, + Partial + >(); + private readonly moduleTokenFactory = new ModuleTokenFactory(); + + public addModule( + metatype: NestModuleMetatype | DynamicModule, + scope: NestModuleMetatype[] + ) { + if (!metatype) { + throw new InvalidModuleException(scope); + } + const { type, dynamicMetadata } = this.extractMetadata(metatype); + const token = this.moduleTokenFactory.create(type, scope, dynamicMetadata); + if (this.modules.has(token)) { + return; + } + const module = new Module(type, scope, this); + this.modules.set(token, module); + + this.addDynamicMetadata(token, dynamicMetadata); + this.isGlobalModule(type) && this.addGlobalModule(module); + } + + public extractMetadata( + metatype: NestModuleMetatype | DynamicModule + ): { + type: NestModuleMetatype; + dynamicMetadata?: Partial | undefined; + } { + if (!this.isDynamicModule(metatype)) { + return { type: metatype }; + } + const { module: type, ...dynamicMetadata } = metatype; + return { type, dynamicMetadata }; + } + + public isDynamicModule( + module: NestModuleMetatype | DynamicModule + ): module is DynamicModule { + return (module as DynamicModule).module; + } + + public addDynamicMetadata( + token: string, + dynamicModuleMetadata: Partial + ) { + if (!dynamicModuleMetadata) { + return undefined; + } + this.dynamicModulesMetadata.set(token, dynamicModuleMetadata); + } + + public isGlobalModule(metatype: NestModuleMetatype): boolean { + return !!Reflect.getMetadata(GLOBAL_MODULE_METADATA, metatype); + } + + public addGlobalModule(module: Module) { + this.globalModules.add(module); + } + + public getModules(): ModulesContainer { + return this.modules; + } + + public addRelatedModule( + relatedModule: NestModuleMetatype | DynamicModule, + token: string + ) { + if (!this.modules.has(token)) return; + + const module = this.modules.get(token); + const parent = module.metatype; + + const { type, dynamicMetadata } = this.extractMetadata(relatedModule); + const relatedModuleToken = this.moduleTokenFactory.create( + type, + [].concat(module.scope, parent), + dynamicMetadata + ); + const related = this.modules.get(relatedModuleToken); + module.addRelatedModule(related); + } + + public addComponent(component: Metatype, token: string) { + if (!this.modules.has(token)) { + throw new UnknownModuleException(); + } + const module = this.modules.get(token); + module.addComponent(component); + } + + public addInjectable(injectable: Metatype, token: string) { + if (!this.modules.has(token)) { + throw new UnknownModuleException(); + } + const module = this.modules.get(token); + module.addInjectable(injectable); + } + + public addExportedComponent( + exportedComponent: Metatype, + token: string + ) { + if (!this.modules.has(token)) { + throw new UnknownModuleException(); + } + const module = this.modules.get(token); + module.addExportedComponent(exportedComponent); + } + + public addController(controller: Metatype, token: string) { + if (!this.modules.has(token)) { + throw new UnknownModuleException(); + } + const module = this.modules.get(token); + module.addRoute(controller); + } + + public clear() { + this.modules.clear(); + } + + public replace(toReplace, options: any & { scope: any[] | null }) { + [...this.modules.values()].forEach(module => { + module.replace(toReplace, options); + }); + } + + public bindGlobalScope() { + this.modules.forEach(module => this.bindGlobalsToRelatedModules(module)); + } + + public bindGlobalsToRelatedModules(module: Module) { + this.globalModules.forEach(globalModule => + this.bindGlobalModuleToModule(module, globalModule) + ); + } + + public bindGlobalModuleToModule(module: Module, globalModule: Module) { + if (module === globalModule) { + return undefined; + } + module.addRelatedModule(globalModule); + } + + public getDynamicMetadataByToken( + token: string, + metadataKey: keyof DynamicModule + ): any[] { + const metadata = this.dynamicModulesMetadata.get(token); + if (metadata && metadata[metadataKey]) { + return metadata[metadataKey]; + } + return []; + } } export interface InstanceWrapper { - name: any; - metatype: Metatype; - instance: T; - isResolved: boolean; - isPending?: boolean; - done$?: Promise; - inject?: Metatype[]; - isNotMetatype?: boolean; - forwardRef?: boolean; - async?: boolean; -} \ No newline at end of file + name: any; + metatype: Metatype; + instance: T; + isResolved: boolean; + isPending?: boolean; + done$?: Promise; + inject?: Metatype[]; + isNotMetatype?: boolean; + forwardRef?: boolean; + async?: boolean; +} diff --git a/src/core/injector/index.ts b/src/core/injector/index.ts index 33c5d1ef0f9..8bf3475df98 100644 --- a/src/core/injector/index.ts +++ b/src/core/injector/index.ts @@ -1 +1 @@ -export * from './modules-container'; \ No newline at end of file +export * from './modules-container'; diff --git a/src/core/injector/injector.ts b/src/core/injector/injector.ts index f058bd26f44..e37726abb5e 100644 --- a/src/core/injector/injector.ts +++ b/src/core/injector/injector.ts @@ -7,39 +7,61 @@ import { Metatype } from '@nestjs/common/interfaces/metatype.interface'; import { Controller } from '@nestjs/common/interfaces/controllers/controller.interface'; import { Injectable } from '@nestjs/common/interfaces/injectable.interface'; import { MiddlewareWrapper } from '../middlewares/container'; -import { isUndefined, isNil, isFunction } from '@nestjs/common/utils/shared.utils'; -import { PARAMTYPES_METADATA, SELF_DECLARED_DEPS_METADATA } from '@nestjs/common/constants'; +import { + isUndefined, + isNil, + isFunction +} from '@nestjs/common/utils/shared.utils'; +import { + PARAMTYPES_METADATA, + SELF_DECLARED_DEPS_METADATA +} from '@nestjs/common/constants'; import { UndefinedDependencyException } from './../errors/exceptions/undefined-dependency.exception'; export class Injector { public async loadInstanceOfMiddleware( wrapper: MiddlewareWrapper, collection: Map, - module: Module) { - + module: Module + ) { const { metatype } = wrapper; const currentMetatype = collection.get(metatype.name); if (currentMetatype.instance !== null) return; - await this.resolveConstructorParams(wrapper as any, module, null, null, (instances) => { - collection.set(metatype.name, { - instance: new metatype(...instances), - metatype, - }); - }); + await this.resolveConstructorParams( + wrapper as any, + module, + null, + null, + instances => { + collection.set(metatype.name, { + instance: new metatype(...instances), + metatype + }); + } + ); } - public async loadInstanceOfRoute(wrapper: InstanceWrapper, module: Module) { + public async loadInstanceOfRoute( + wrapper: InstanceWrapper, + module: Module + ) { const routes = module.routes; await this.loadInstance(wrapper, routes, module); } - public async loadInstanceOfInjectable(wrapper: InstanceWrapper, module: Module) { + public async loadInstanceOfInjectable( + wrapper: InstanceWrapper, + module: Module + ) { const injectables = module.injectables; await this.loadInstance(wrapper, injectables, module); } - public loadPrototypeOfInstance({ metatype, name }: InstanceWrapper, collection: Map>) { + public loadPrototypeOfInstance( + { metatype, name }: InstanceWrapper, + collection: Map> + ) { if (!collection) return null; const target = collection.get(name); @@ -47,23 +69,34 @@ export class Injector { collection.set(name, { ...collection.get(name), - instance: Object.create(metatype.prototype), + instance: Object.create(metatype.prototype) }); } - public async loadInstanceOfComponent(wrapper: InstanceWrapper, module: Module, context: Module[] = []) { + public async loadInstanceOfComponent( + wrapper: InstanceWrapper, + module: Module, + context: Module[] = [] + ) { const components = module.components; await this.loadInstance(wrapper, components, module, context); } public applyDoneSubject(wrapper: InstanceWrapper): () => void { let done: () => void; - wrapper.done$ = new Promise((resolve, reject) => { done = resolve; }); + wrapper.done$ = new Promise((resolve, reject) => { + done = resolve; + }); wrapper.isPending = true; return done; } - public async loadInstance(wrapper: InstanceWrapper, collection, module: Module, context: Module[] = []) { + public async loadInstance( + wrapper: InstanceWrapper, + collection, + module: Module, + context: Module[] = [] + ) { if (wrapper.isPending) { return await wrapper.done$; } @@ -75,19 +108,27 @@ export class Injector { } if (currentMetatype.isResolved) return null; - await this.resolveConstructorParams(wrapper, module, inject, context, async (instances) => { - if (isNil(inject)) { - currentMetatype.instance = Object.assign( - currentMetatype.instance, - new metatype(...instances), - ); - } else { - const factoryResult = currentMetatype.metatype(...instances); - currentMetatype.instance = await this.resolveFactoryInstance(factoryResult); + await this.resolveConstructorParams( + wrapper, + module, + inject, + context, + async instances => { + if (isNil(inject)) { + currentMetatype.instance = Object.assign( + currentMetatype.instance, + new metatype(...instances) + ); + } else { + const factoryResult = currentMetatype.metatype(...instances); + currentMetatype.instance = await this.resolveFactoryInstance( + factoryResult + ); + } + currentMetatype.isResolved = true; + done(); } - currentMetatype.isResolved = true; - done(); - }); + ); } public async resolveConstructorParams( @@ -95,32 +136,36 @@ export class Injector { module: Module, inject: any[], context: Module[], - callback: (args) => void) { - + callback: (args) => void + ) { let isResolved = true; - const args = isNil(inject) ? this.reflectConstructorParams(wrapper.metatype) : inject; + const args = isNil(inject) + ? this.reflectConstructorParams(wrapper.metatype) + : inject; - const instances = await Promise.all(args.map(async (param, index) => { - const paramWrapper = await this.resolveSingleParam( - wrapper, - param, - { index, length: args.length }, - module, - context, - ); - if (!paramWrapper.isResolved && !paramWrapper.forwardRef) { - isResolved = false; - } - return paramWrapper.instance; - })); - isResolved && await callback(instances); + const instances = await Promise.all( + args.map(async (param, index) => { + const paramWrapper = await this.resolveSingleParam( + wrapper, + param, + { index, length: args.length }, + module, + context + ); + if (!paramWrapper.isResolved && !paramWrapper.forwardRef) { + isResolved = false; + } + return paramWrapper.instance; + }) + ); + isResolved && (await callback(instances)); } public reflectConstructorParams(type: Metatype): any[] { const paramtypes = Reflect.getMetadata(PARAMTYPES_METADATA, type) || []; const selfParams = this.reflectSelfParams(type); - selfParams.forEach(({ index, param }) => paramtypes[index] = param); + selfParams.forEach(({ index, param }) => (paramtypes[index] = param)); return paramtypes; } @@ -131,9 +176,9 @@ export class Injector { public async resolveSingleParam( wrapper: InstanceWrapper, param: Metatype | string | symbol | any, - { index, length }: { index: number, length: number }, + { index, length }: { index: number; length: number }, module: Module, - context: Module[], + context: Module[] ) { if (isUndefined(param)) { throw new UndefinedDependencyException(wrapper.name, index, length); @@ -144,13 +189,13 @@ export class Injector { isFunction(token) ? (token as Metatype).name : token, { index, length }, wrapper, - context, + context ); } public resolveParamToken( wrapper: InstanceWrapper, - param: Metatype | string | symbol | any, + param: Metatype | string | symbol | any ) { if (!param.forwardRef) { return param; @@ -162,9 +207,9 @@ export class Injector { public async resolveComponentInstance( module: Module, name: any, - { index, length }: { index: number, length: number }, + { index, length }: { index: number; length: number }, wrapper: InstanceWrapper, - context: Module[], + context: Module[] ) { const components = module.components; const instanceWrapper = await this.scanForComponent( @@ -172,7 +217,7 @@ export class Injector { module, { name, index, length }, wrapper, - context, + context ); if (!instanceWrapper.isResolved && !instanceWrapper.forwardRef) { await this.loadInstanceOfComponent(instanceWrapper, module); @@ -186,32 +231,41 @@ export class Injector { public async scanForComponent( components: Map, module: Module, - { name, index, length }: { name: any, index: number, length: number }, + { name, index, length }: { name: any; index: number; length: number }, { metatype }, - context: Module[] = [], + context: Module[] = [] ) { - const component = await this.scanForComponentInScopes(context, { name, index, length }, metatype); + const component = await this.scanForComponentInScopes( + context, + { name, index, length }, + metatype + ); if (component) { return component; } - const scanInExports = () => this.scanForComponentInExports( - components, - { name, index, length }, - module, - metatype, - context, - ); + const scanInExports = () => + this.scanForComponentInExports( + components, + { name, index, length }, + module, + metatype, + context + ); return components.has(name) ? components.get(name) : await scanInExports(); } public async scanForComponentInExports( components: Map, - { name, index, length }: { name: any, index: number, length: number }, + { name, index, length }: { name: any; index: number; length: number }, module: Module, metatype, - context: Module[] = [], + context: Module[] = [] ) { - const instanceWrapper = await this.scanForComponentInRelatedModules(module, name, context); + const instanceWrapper = await this.scanForComponentInRelatedModules( + module, + name, + context + ); if (isNil(instanceWrapper)) { throw new UnknownDependenciesException(metatype.name, index, length); } @@ -220,12 +274,16 @@ export class Injector { public async scanForComponentInScopes( context: Module[], - { name, index, length }: { name: any, index: number, length: number }, - metatype, + { name, index, length }: { name: any; index: number; length: number }, + metatype ) { context = context || []; for (const ctx of context) { - const component = await this.scanForComponentInScope(ctx, { name, index, length }, metatype); + const component = await this.scanForComponentInScope( + ctx, + { name, index, length }, + metatype + ); if (component) return component; } return null; @@ -233,19 +291,22 @@ export class Injector { public async scanForComponentInScope( context: Module, - { name, index, length }: { name: any, index: number, length: number }, - metatype, + { name, index, length }: { name: any; index: number; length: number }, + metatype ) { try { const component = await this.scanForComponent( - context.components, context, { name, index, length }, { metatype }, null, + context.components, + context, + { name, index, length }, + { metatype }, + null ); if (!component.isResolved && !component.forwardRef) { await this.loadInstanceOfComponent(component, context); } return component; - } - catch (e) { + } catch (e) { if (e instanceof UndefinedDependencyException) { throw e; } @@ -253,7 +314,11 @@ export class Injector { } } - public async scanForComponentInRelatedModules(module: Module, name: any, context: Module[]) { + public async scanForComponentInRelatedModules( + module: Module, + name: any, + context: Module[] + ) { let component = null; const relatedModules = module.relatedModules || []; @@ -282,12 +347,17 @@ export class Injector { } public flatMap(modules: Module[]): Module[] { - return modules.concat.apply(modules, modules.map((module: Module) => { - const { relatedModules, exports } = module; - return this.flatMap([...relatedModules.values()].filter((related) => { - const { metatype } = related; - return exports.has(metatype.name); - })); - })); + return modules.concat.apply( + modules, + modules.map((module: Module) => { + const { relatedModules, exports } = module; + return this.flatMap( + [...relatedModules.values()].filter(related => { + const { metatype } = related; + return exports.has(metatype.name); + }) + ); + }) + ); } -} \ No newline at end of file +} diff --git a/src/core/injector/instance-loader.ts b/src/core/injector/instance-loader.ts index f66a2e01348..586f506781b 100644 --- a/src/core/injector/instance-loader.ts +++ b/src/core/injector/instance-loader.ts @@ -9,70 +9,82 @@ import { ModuleInitMessage } from '../helpers/messages'; import { isUndefined, isNil } from '@nestjs/common/utils/shared.utils'; export class InstanceLoader { - private readonly injector = new Injector(); - private readonly logger = new Logger(InstanceLoader.name, true); + private readonly injector = new Injector(); + private readonly logger = new Logger(InstanceLoader.name, true); - constructor(private readonly container: NestContainer) {} + constructor(private readonly container: NestContainer) {} - public async createInstancesOfDependencies() { - const modules = this.container.getModules(); + public async createInstancesOfDependencies() { + const modules = this.container.getModules(); - this.createPrototypes(modules); - await this.createInstances(modules); - } + this.createPrototypes(modules); + await this.createInstances(modules); + } - private createPrototypes(modules: Map) { - modules.forEach((module) => { - this.createPrototypesOfComponents(module); - this.createPrototypesOfInjectables(module); - this.createPrototypesOfRoutes(module); - }); - } + private createPrototypes(modules: Map) { + modules.forEach(module => { + this.createPrototypesOfComponents(module); + this.createPrototypesOfInjectables(module); + this.createPrototypesOfRoutes(module); + }); + } - private async createInstances(modules: Map) { - for (const module of [...modules.values()]) { - await this.createInstancesOfComponents(module); - await this.createInstancesOfInjectables(module); - await this.createInstancesOfRoutes(module); + private async createInstances(modules: Map) { + for (const module of [...modules.values()]) { + await this.createInstancesOfComponents(module); + await this.createInstancesOfInjectables(module); + await this.createInstancesOfRoutes(module); - const { name } = module.metatype; - this.logger.log(ModuleInitMessage(name)); - } + const { name } = module.metatype; + this.logger.log(ModuleInitMessage(name)); } + } - private createPrototypesOfComponents(module: Module) { - module.components.forEach((wrapper) => { - this.injector.loadPrototypeOfInstance(wrapper, module.components); - }); - } + private createPrototypesOfComponents(module: Module) { + module.components.forEach(wrapper => { + this.injector.loadPrototypeOfInstance( + wrapper, + module.components + ); + }); + } - private async createInstancesOfComponents(module: Module) { - for (const [key, wrapper] of module.components) { - await this.injector.loadInstanceOfComponent(wrapper, module); - } + private async createInstancesOfComponents(module: Module) { + for (const [key, wrapper] of module.components) { + await this.injector.loadInstanceOfComponent(wrapper, module); } + } - private createPrototypesOfRoutes(module: Module) { - module.routes.forEach((wrapper) => { - this.injector.loadPrototypeOfInstance(wrapper, module.routes); - }); - } + private createPrototypesOfRoutes(module: Module) { + module.routes.forEach(wrapper => { + this.injector.loadPrototypeOfInstance(wrapper, module.routes); + }); + } - private async createInstancesOfRoutes(module: Module) { - await Promise.all([...module.routes.values()].map(async (wrapper) => - await this.injector.loadInstanceOfRoute(wrapper, module), - )); - } + private async createInstancesOfRoutes(module: Module) { + await Promise.all( + [...module.routes.values()].map( + async wrapper => + await this.injector.loadInstanceOfRoute(wrapper, module) + ) + ); + } - private createPrototypesOfInjectables(module: Module) { - module.injectables.forEach((wrapper) => { - this.injector.loadPrototypeOfInstance(wrapper, module.injectables); - }); - } + private createPrototypesOfInjectables(module: Module) { + module.injectables.forEach(wrapper => { + this.injector.loadPrototypeOfInstance( + wrapper, + module.injectables + ); + }); + } - private async createInstancesOfInjectables(module: Module) { - await Promise.all([...module.injectables.values()].map(async (wrapper) => - await this.injector.loadInstanceOfInjectable(wrapper, module), - )); - } -} \ No newline at end of file + private async createInstancesOfInjectables(module: Module) { + await Promise.all( + [...module.injectables.values()].map( + async wrapper => + await this.injector.loadInstanceOfInjectable(wrapper, module) + ) + ); + } +} diff --git a/src/core/injector/module-ref.ts b/src/core/injector/module-ref.ts index 701f26a8cc2..5a9a6359f08 100644 --- a/src/core/injector/module-ref.ts +++ b/src/core/injector/module-ref.ts @@ -1,5 +1,5 @@ import { OpaqueToken } from './module'; export abstract class ModuleRef { - public abstract get(type: OpaqueToken): T; -} \ No newline at end of file + public abstract get(type: OpaqueToken): T; +} diff --git a/src/core/injector/module-token-factory.ts b/src/core/injector/module-token-factory.ts index 9920ff2bb68..d9404004c75 100644 --- a/src/core/injector/module-token-factory.ts +++ b/src/core/injector/module-token-factory.ts @@ -3,40 +3,50 @@ import { SHARED_MODULE_METADATA } from '@nestjs/common/constants'; import { DynamicModule } from '@nestjs/common'; export class ModuleTokenFactory { - public create( - metatype: NestModuleMetatype, - scope: NestModuleMetatype[], - dynamicModuleMetadata?: Partial | undefined, - ) { - const reflectedScope = this.reflectScope(metatype); - const isSingleScoped = reflectedScope === true; - const opaqueToken = { - module: this.getModuleName(metatype), - dynamic: this.getDynamicMetadataToken(dynamicModuleMetadata), - scope: isSingleScoped ? this.getScopeStack(scope) : reflectedScope, - }; - return JSON.stringify(opaqueToken); - } + public create( + metatype: NestModuleMetatype, + scope: NestModuleMetatype[], + dynamicModuleMetadata?: Partial | undefined + ) { + const reflectedScope = this.reflectScope(metatype); + const isSingleScoped = reflectedScope === true; + const opaqueToken = { + module: this.getModuleName(metatype), + dynamic: this.getDynamicMetadataToken(dynamicModuleMetadata), + scope: isSingleScoped ? this.getScopeStack(scope) : reflectedScope + }; + return JSON.stringify(opaqueToken); + } - public getDynamicMetadataToken(dynamicModuleMetadata: Partial | undefined): string { - return dynamicModuleMetadata ? JSON.stringify(dynamicModuleMetadata) : ''; - } + public getDynamicMetadataToken( + dynamicModuleMetadata: Partial | undefined + ): string { + return dynamicModuleMetadata ? JSON.stringify(dynamicModuleMetadata) : ''; + } - public getModuleName(metatype: NestModuleMetatype): string { - return metatype.name; - } + public getModuleName(metatype: NestModuleMetatype): string { + return metatype.name; + } - public getScopeStack(scope: NestModuleMetatype[]): string[] { - const reversedScope = scope.reverse(); - const firstGlobalIndex = reversedScope.findIndex((s) => this.reflectScope(s) === 'global'); - scope.reverse(); + public getScopeStack(scope: NestModuleMetatype[]): string[] { + const reversedScope = scope.reverse(); + const firstGlobalIndex = reversedScope.findIndex( + s => this.reflectScope(s) === 'global' + ); + scope.reverse(); - const stack = firstGlobalIndex >= 0 ? scope.slice(scope.length - firstGlobalIndex - 1) : scope; - return stack.map((module) => module.name); - } + const stack = + firstGlobalIndex >= 0 + ? scope.slice(scope.length - firstGlobalIndex - 1) + : scope; + return stack.map(module => module.name); + } - private reflectScope(metatype: NestModuleMetatype) { - const reflectedScope = Reflect.getMetadata(SHARED_MODULE_METADATA, metatype); - return reflectedScope ? reflectedScope : 'global'; - } -} \ No newline at end of file + private reflectScope(metatype: NestModuleMetatype) { + const reflectedScope = Reflect.getMetadata( + SHARED_MODULE_METADATA, + metatype + ); + return reflectedScope ? reflectedScope : 'global'; + } +} diff --git a/src/core/injector/module.ts b/src/core/injector/module.ts index fcab29c38c7..c75ebf00c08 100644 --- a/src/core/injector/module.ts +++ b/src/core/injector/module.ts @@ -4,7 +4,11 @@ import { UnknownExportException } from '../errors/exceptions/unknown-export.exce import { NestModuleMetatype } from '@nestjs/common/interfaces/modules/module-metatype.interface'; import { Metatype } from '@nestjs/common/interfaces/metatype.interface'; import { ModuleRef } from './module-ref'; -import { isFunction, isNil, isUndefined } from '@nestjs/common/utils/shared.utils'; +import { + isFunction, + isNil, + isUndefined +} from '@nestjs/common/utils/shared.utils'; import { RuntimeException } from '../errors/exceptions/runtime.exception'; import { Reflector } from '../services/reflector.service'; import { ExternalContextCreator } from './../helpers/external-context-creator'; @@ -15,258 +19,276 @@ import { GuardsConsumer } from './../guards/guards-consumer'; import { ModulesContainer } from './modules-container'; export interface CustomComponent { - provide: any; - name: string; + provide: any; + name: string; } export type OpaqueToken = string | symbol | object | Metatype; export type CustomClass = CustomComponent & { useClass: Metatype }; -export type CustomFactory = CustomComponent & { useFactory: (...args) => any, inject?: Metatype[] }; +export type CustomFactory = CustomComponent & { + useFactory: (...args) => any; + inject?: Metatype[]; +}; export type CustomValue = CustomComponent & { useValue: any }; -export type ComponentMetatype = Metatype | CustomFactory | CustomValue | CustomClass; +export type ComponentMetatype = + | Metatype + | CustomFactory + | CustomValue + | CustomClass; export class Module { - private _relatedModules = new Set(); - private _components = new Map>(); - private _injectables = new Map>(); - private _routes = new Map>(); - private _exports = new Set(); - - constructor( - private _metatype: NestModuleMetatype, - private _scope: NestModuleMetatype[], - container: NestContainer, - ) { - this.addCoreInjectables(container); - } + private _relatedModules = new Set(); + private _components = new Map>(); + private _injectables = new Map>(); + private _routes = new Map>(); + private _exports = new Set(); + + constructor( + private _metatype: NestModuleMetatype, + private _scope: NestModuleMetatype[], + container: NestContainer + ) { + this.addCoreInjectables(container); + } - get scope(): NestModuleMetatype[] { - return this._scope; - } + get scope(): NestModuleMetatype[] { + return this._scope; + } - get relatedModules(): Set { - return this._relatedModules; - } + get relatedModules(): Set { + return this._relatedModules; + } - get components(): Map> { - return this._components; - } + get components(): Map> { + return this._components; + } - get injectables(): Map> { - return this._injectables; - } + get injectables(): Map> { + return this._injectables; + } - get routes(): Map> { - return this._routes; - } + get routes(): Map> { + return this._routes; + } - get exports(): Set { - return this._exports; - } + get exports(): Set { + return this._exports; + } - get instance(): NestModule { - if (!this._components.has(this._metatype.name)) { - throw new RuntimeException(); - } - const module = this._components.get(this._metatype.name); - return module.instance as NestModule; + get instance(): NestModule { + if (!this._components.has(this._metatype.name)) { + throw new RuntimeException(); } + const module = this._components.get(this._metatype.name); + return module.instance as NestModule; + } - get metatype(): NestModuleMetatype { - return this._metatype; - } + get metatype(): NestModuleMetatype { + return this._metatype; + } - public addCoreInjectables(container: NestContainer) { - this.addModuleRef(); - this.addModuleAsComponent(); - this.addReflector(); - this.addExternalContextCreator(container); - this.addModulesContainer(container); - } + public addCoreInjectables(container: NestContainer) { + this.addModuleRef(); + this.addModuleAsComponent(); + this.addReflector(); + this.addExternalContextCreator(container); + this.addModulesContainer(container); + } - public addModuleRef() { - const moduleRef = this.createModuleRefMetatype(this._components); - this._components.set(ModuleRef.name, { - name: ModuleRef.name, - metatype: ModuleRef as any, - isResolved: true, - instance: new moduleRef(), - }); - } + public addModuleRef() { + const moduleRef = this.createModuleRefMetatype(this._components); + this._components.set(ModuleRef.name, { + name: ModuleRef.name, + metatype: ModuleRef as any, + isResolved: true, + instance: new moduleRef() + }); + } - public addModuleAsComponent() { - this._components.set(this._metatype.name, { - name: this._metatype.name, - metatype: this._metatype, - isResolved: false, - instance: null, - }); - } + public addModuleAsComponent() { + this._components.set(this._metatype.name, { + name: this._metatype.name, + metatype: this._metatype, + isResolved: false, + instance: null + }); + } - public addReflector() { - this._components.set(Reflector.name, { - name: Reflector.name, - metatype: Reflector, - isResolved: false, - instance: null, - }); - } + public addReflector() { + this._components.set(Reflector.name, { + name: Reflector.name, + metatype: Reflector, + isResolved: false, + instance: null + }); + } - public addExternalContextCreator(container: NestContainer) { - this._components.set(ExternalContextCreator.name, { - name: ExternalContextCreator.name, - metatype: ExternalContextCreator, - isResolved: true, - instance: new ExternalContextCreator( - new GuardsContextCreator(container), - new GuardsConsumer(), - new InterceptorsContextCreator(container), - new InterceptorsConsumer(), - container.getModules(), - ), - }); - } + public addExternalContextCreator(container: NestContainer) { + this._components.set(ExternalContextCreator.name, { + name: ExternalContextCreator.name, + metatype: ExternalContextCreator, + isResolved: true, + instance: new ExternalContextCreator( + new GuardsContextCreator(container), + new GuardsConsumer(), + new InterceptorsContextCreator(container), + new InterceptorsConsumer(), + container.getModules() + ) + }); + } - public addModulesContainer(container: NestContainer) { - this._components.set(ModulesContainer.name, { - name: ModulesContainer.name, - metatype: ModulesContainer, - isResolved: true, - instance: container.getModules(), - }); + public addModulesContainer(container: NestContainer) { + this._components.set(ModulesContainer.name, { + name: ModulesContainer.name, + metatype: ModulesContainer, + isResolved: true, + instance: container.getModules() + }); } - public addInjectable(injectable: Metatype) { - if (this.isCustomProvider(injectable)) { - return this.addCustomProvider(injectable, this._injectables); - } - this._injectables.set(injectable.name, { - name: injectable.name, - metatype: injectable, - instance: null, - isResolved: false, - }); + public addInjectable(injectable: Metatype) { + if (this.isCustomProvider(injectable)) { + return this.addCustomProvider(injectable, this._injectables); } + this._injectables.set(injectable.name, { + name: injectable.name, + metatype: injectable, + instance: null, + isResolved: false + }); + } - public addComponent(component: ComponentMetatype) { - if (this.isCustomProvider(component)) { - this.addCustomProvider(component, this._components); - return; - } - this._components.set((component as Metatype).name, { - name: (component as Metatype).name, - metatype: component as Metatype, - instance: null, - isResolved: false, - }); + public addComponent(component: ComponentMetatype) { + if (this.isCustomProvider(component)) { + this.addCustomProvider(component, this._components); + return; } + this._components.set((component as Metatype).name, { + name: (component as Metatype).name, + metatype: component as Metatype, + instance: null, + isResolved: false + }); + } - public isCustomProvider(component: ComponentMetatype): component is CustomClass | CustomFactory | CustomValue { - return !isNil((component as CustomComponent).provide); - } + public isCustomProvider( + component: ComponentMetatype + ): component is CustomClass | CustomFactory | CustomValue { + return !isNil((component as CustomComponent).provide); + } - public addCustomProvider(component: CustomFactory | CustomValue | CustomClass, collection: Map) { - const { provide } = component; - const name = isFunction(provide) ? provide.name : provide; - const comp = { - ...component, - name, - }; - - if (this.isCustomClass(comp)) this.addCustomClass(comp, collection); - else if (this.isCustomValue(comp)) this.addCustomValue(comp, collection); - else if (this.isCustomFactory(comp)) this.addCustomFactory(comp, collection); - } + public addCustomProvider( + component: CustomFactory | CustomValue | CustomClass, + collection: Map + ) { + const { provide } = component; + const name = isFunction(provide) ? provide.name : provide; + const comp = { + ...component, + name + }; + + if (this.isCustomClass(comp)) this.addCustomClass(comp, collection); + else if (this.isCustomValue(comp)) this.addCustomValue(comp, collection); + else if (this.isCustomFactory(comp)) + this.addCustomFactory(comp, collection); + } - public isCustomClass(component): component is CustomClass { - return !isUndefined((component as CustomClass).useClass); - } + public isCustomClass(component): component is CustomClass { + return !isUndefined((component as CustomClass).useClass); + } - public isCustomValue(component): component is CustomValue { - return !isUndefined((component as CustomValue).useValue); - } + public isCustomValue(component): component is CustomValue { + return !isUndefined((component as CustomValue).useValue); + } - public isCustomFactory(component): component is CustomFactory { - return !isUndefined((component as CustomFactory).useFactory); - } + public isCustomFactory(component): component is CustomFactory { + return !isUndefined((component as CustomFactory).useFactory); + } - public addCustomClass(component: CustomClass, collection: Map) { - const { provide, name, useClass } = component; - collection.set(name, { - name, - metatype: useClass, - instance: null, - isResolved: false, - }); - } + public addCustomClass(component: CustomClass, collection: Map) { + const { provide, name, useClass } = component; + collection.set(name, { + name, + metatype: useClass, + instance: null, + isResolved: false + }); + } - public addCustomValue(component: CustomValue, collection: Map) { - const { provide, name, useValue: value } = component; - collection.set(name, { - name, - metatype: null, - instance: value, - isResolved: true, - isNotMetatype: true, - async: value instanceof Promise, - }); - } + public addCustomValue(component: CustomValue, collection: Map) { + const { provide, name, useValue: value } = component; + collection.set(name, { + name, + metatype: null, + instance: value, + isResolved: true, + isNotMetatype: true, + async: value instanceof Promise + }); + } - public addCustomFactory(component: CustomFactory, collection: Map) { - const { provide, name, useFactory: factory, inject } = component; - collection.set(name, { - name, - metatype: factory as any, - instance: null, - isResolved: false, - inject: inject || [], - isNotMetatype: true, - }); - } + public addCustomFactory( + component: CustomFactory, + collection: Map + ) { + const { provide, name, useFactory: factory, inject } = component; + collection.set(name, { + name, + metatype: factory as any, + instance: null, + isResolved: false, + inject: inject || [], + isNotMetatype: true + }); + } - public addExportedComponent(exportedComponent: ComponentMetatype) { - if (this.isCustomProvider(exportedComponent)) { - return this.addCustomExportedComponent(exportedComponent); - } - this._exports.add(exportedComponent.name); + public addExportedComponent(exportedComponent: ComponentMetatype) { + if (this.isCustomProvider(exportedComponent)) { + return this.addCustomExportedComponent(exportedComponent); } + this._exports.add(exportedComponent.name); + } - public addCustomExportedComponent(exportedComponent: CustomFactory | CustomValue | CustomClass) { - this._exports.add(exportedComponent.provide); - } + public addCustomExportedComponent( + exportedComponent: CustomFactory | CustomValue | CustomClass + ) { + this._exports.add(exportedComponent.provide); + } - public addRoute(route: Metatype) { - this._routes.set(route.name, { - name: route.name, - metatype: route, - instance: null, - isResolved: false, - }); - } + public addRoute(route: Metatype) { + this._routes.set(route.name, { + name: route.name, + metatype: route, + instance: null, + isResolved: false + }); + } - public addRelatedModule(relatedModule) { - this._relatedModules.add(relatedModule); - } + public addRelatedModule(relatedModule) { + this._relatedModules.add(relatedModule); + } - public replace(toReplace, options) { - if (options.isComponent) { - return this.addComponent({ provide: toReplace, ...options }); - } - this.addInjectable({ - provide: toReplace, - ...options, - }); + public replace(toReplace, options) { + if (options.isComponent) { + return this.addComponent({ provide: toReplace, ...options }); } + this.addInjectable({ + provide: toReplace, + ...options + }); + } - public createModuleRefMetatype(components) { - return class { - public readonly components = components; + public createModuleRefMetatype(components) { + return class { + public readonly components = components; - public get(type: OpaqueToken): T { - const name = isFunction(type) ? (type as Metatype).name : type; - const exists = this.components.has(name); + public get(type: OpaqueToken): T { + const name = isFunction(type) ? (type as Metatype).name : type; + const exists = this.components.has(name); - return exists ? this.components.get(name).instance as T : null; - } - }; - } -} \ No newline at end of file + return exists ? (this.components.get(name).instance as T) : null; + } + }; + } +} diff --git a/src/core/interceptors/interceptors-consumer.ts b/src/core/interceptors/interceptors-consumer.ts index 01dcb87157f..d7d68112343 100644 --- a/src/core/interceptors/interceptors-consumer.ts +++ b/src/core/interceptors/interceptors-consumer.ts @@ -1,6 +1,11 @@ import iterate from 'iterare'; import { GUARDS_METADATA } from '@nestjs/common/constants'; -import { isUndefined, isFunction, isNil, isEmpty } from '@nestjs/common/utils/shared.utils'; +import { + isUndefined, + isFunction, + isNil, + isEmpty +} from '@nestjs/common/utils/shared.utils'; import { Controller } from '@nestjs/common/interfaces'; import { HttpStatus, ExecutionContext, NestInterceptor } from '@nestjs/common'; import { Observable } from 'rxjs/Observable'; @@ -9,35 +14,39 @@ import 'rxjs/add/observable/defer'; import 'rxjs/add/operator/take'; export class InterceptorsConsumer { - public async intercept( - interceptors: NestInterceptor[], - dataOrRequest: any, - instance: Controller, - callback: (...args) => any, - next: () => Promise, - ): Promise { - if (!interceptors || isEmpty(interceptors)) { - return await next(); - } - const context = this.createContext(instance, callback); - const start$ = Observable.defer(() => this.transformDeffered(next)); - const result$ = await interceptors.reduce( - async (stream$, interceptor) => await interceptor.intercept(dataOrRequest, context, await stream$), - Promise.resolve(start$), - ); - return await result$.toPromise(); + public async intercept( + interceptors: NestInterceptor[], + dataOrRequest: any, + instance: Controller, + callback: (...args) => any, + next: () => Promise + ): Promise { + if (!interceptors || isEmpty(interceptors)) { + return await next(); } + const context = this.createContext(instance, callback); + const start$ = Observable.defer(() => this.transformDeffered(next)); + const result$ = await interceptors.reduce( + async (stream$, interceptor) => + await interceptor.intercept(dataOrRequest, context, await stream$), + Promise.resolve(start$) + ); + return await result$.toPromise(); + } - public createContext(instance: Controller, callback: (...args) => any): ExecutionContext { - return { - parent: instance.constructor, - handler: callback, - }; - } + public createContext( + instance: Controller, + callback: (...args) => any + ): ExecutionContext { + return { + parent: instance.constructor, + handler: callback + }; + } - public transformDeffered(next: () => any): Promise | Observable { - const res = next(); - const isDeffered = res instanceof Promise || res instanceof Observable; - return isDeffered ? res : Promise.resolve(res); - } -} \ No newline at end of file + public transformDeffered(next: () => any): Promise | Observable { + const res = next(); + const isDeffered = res instanceof Promise || res instanceof Observable; + return isDeffered ? res : Promise.resolve(res); + } +} diff --git a/src/core/interceptors/interceptors-context-creator.ts b/src/core/interceptors/interceptors-context-creator.ts index 623a11a3f39..31689083ea1 100644 --- a/src/core/interceptors/interceptors-context-creator.ts +++ b/src/core/interceptors/interceptors-context-creator.ts @@ -2,59 +2,82 @@ import 'reflect-metadata'; import iterate from 'iterare'; import { Controller, NestInterceptor } from '@nestjs/common/interfaces'; import { INTERCEPTORS_METADATA } from '@nestjs/common/constants'; -import { isUndefined, isFunction, isNil, isEmpty } from '@nestjs/common/utils/shared.utils'; +import { + isUndefined, + isFunction, + isNil, + isEmpty +} from '@nestjs/common/utils/shared.utils'; import { ContextCreator } from './../helpers/context-creator'; import { NestContainer } from '../injector/container'; import { ConfigurationProvider } from '@nestjs/common/interfaces/configuration-provider.interface'; export class InterceptorsContextCreator extends ContextCreator { - private moduleContext: string; + private moduleContext: string; - constructor( - private readonly container: NestContainer, - private readonly config?: ConfigurationProvider) { - super(); - } + constructor( + private readonly container: NestContainer, + private readonly config?: ConfigurationProvider + ) { + super(); + } - public create(instance: Controller, callback: (...args) => any, module: string): NestInterceptor[] { - this.moduleContext = module; - return this.createContext(instance, callback, INTERCEPTORS_METADATA); - } + public create( + instance: Controller, + callback: (...args) => any, + module: string + ): NestInterceptor[] { + this.moduleContext = module; + return this.createContext(instance, callback, INTERCEPTORS_METADATA); + } - public createConcreteContext(metadata: T): R { - if (isUndefined(metadata) || isEmpty(metadata) || !this.moduleContext) { - return [] as R; - } - const isGlobalMetadata = metadata === this.getGlobalMetadata(); - return isGlobalMetadata ? - this.createGlobalMetadataContext(metadata) : - iterate(metadata).filter((metatype: any) => metatype && metatype.name) - .map((metatype) => this.getInstanceByMetatype(metatype)) - .filter((wrapper: any) => wrapper && wrapper.instance) - .map((wrapper) => wrapper.instance) - .filter((interceptor: NestInterceptor) => interceptor && isFunction(interceptor.intercept)) - .toArray() as R; + public createConcreteContext( + metadata: T + ): R { + if (isUndefined(metadata) || isEmpty(metadata) || !this.moduleContext) { + return [] as R; } + const isGlobalMetadata = metadata === this.getGlobalMetadata(); + return isGlobalMetadata + ? this.createGlobalMetadataContext(metadata) + : (iterate(metadata) + .filter((metatype: any) => metatype && metatype.name) + .map(metatype => this.getInstanceByMetatype(metatype)) + .filter((wrapper: any) => wrapper && wrapper.instance) + .map(wrapper => wrapper.instance) + .filter( + (interceptor: NestInterceptor) => + interceptor && isFunction(interceptor.intercept) + ) + .toArray() as R); + } - public createGlobalMetadataContext(metadata: T): R { - return iterate(metadata) - .filter((interceptor) => interceptor && interceptor.intercept && isFunction(interceptor.intercept)) - .toArray() as R; - } + public createGlobalMetadataContext( + metadata: T + ): R { + return iterate(metadata) + .filter( + interceptor => + interceptor && + interceptor.intercept && + isFunction(interceptor.intercept) + ) + .toArray() as R; + } - public getInstanceByMetatype(metatype): { instance: any } | undefined { - const collection = this.container.getModules(); - const module = collection.get(this.moduleContext); - if (!module) { - return undefined; - } - return module.injectables.get((metatype as any).name); + public getInstanceByMetatype(metatype): { instance: any } | undefined { + const collection = this.container.getModules(); + const module = collection.get(this.moduleContext); + if (!module) { + return undefined; } + return module.injectables.get((metatype as any).name); + } - public getGlobalMetadata(): T { - if (!this.config) { - return [] as T; - } - return this.config.getGlobalInterceptors() as T; + public getGlobalMetadata(): T { + if (!this.config) { + return [] as T; } -} \ No newline at end of file + return this.config.getGlobalInterceptors() as T; + } +} diff --git a/src/core/metadata-scanner.ts b/src/core/metadata-scanner.ts index e0d52b7ab6c..992893f026c 100644 --- a/src/core/metadata-scanner.ts +++ b/src/core/metadata-scanner.ts @@ -1,19 +1,27 @@ import iterate from 'iterare'; import { Injectable } from '@nestjs/common/interfaces/injectable.interface'; -import { isConstructor, isFunction, isNil } from '@nestjs/common/utils/shared.utils'; +import { + isConstructor, + isFunction, + isNil +} from '@nestjs/common/utils/shared.utils'; export class MetadataScanner { - public scanFromPrototype(instance: T, prototype, callback: (name: string) => R): R[] { - return iterate(Object.getOwnPropertyNames(prototype)) - .filter((method) => { - const descriptor = Object.getOwnPropertyDescriptor(prototype, method); - if (descriptor.set || descriptor.get) { - return false; - } - return !isConstructor(method) && isFunction(prototype[method]); - }) - .map(callback) - .filter((metadata) => !isNil(metadata)) - .toArray(); - } -} \ No newline at end of file + public scanFromPrototype( + instance: T, + prototype, + callback: (name: string) => R + ): R[] { + return iterate(Object.getOwnPropertyNames(prototype)) + .filter(method => { + const descriptor = Object.getOwnPropertyDescriptor(prototype, method); + if (descriptor.set || descriptor.get) { + return false; + } + return !isConstructor(method) && isFunction(prototype[method]); + }) + .map(callback) + .filter(metadata => !isNil(metadata)) + .toArray(); + } +} diff --git a/src/core/middlewares/builder.ts b/src/core/middlewares/builder.ts index 280b036f285..e4c19fba682 100644 --- a/src/core/middlewares/builder.ts +++ b/src/core/middlewares/builder.ts @@ -1,6 +1,10 @@ import { MiddlewareConfiguration } from '@nestjs/common/interfaces/middlewares/middleware-configuration.interface'; import { InvalidMiddlewareConfigurationException } from '../errors/exceptions/invalid-middleware-configuration.exception'; -import { isUndefined, isNil, isFunction } from '@nestjs/common/utils/shared.utils'; +import { + isUndefined, + isNil, + isFunction +} from '@nestjs/common/utils/shared.utils'; import { BindResolveMiddlewareValues } from '@nestjs/common/utils/bind-resolve-values.util'; import { Logger } from '@nestjs/common/services/logger.service'; import { Metatype, MiddlewaresConsumer } from '@nestjs/common/interfaces'; @@ -10,77 +14,81 @@ import { NestMiddleware } from '@nestjs/common'; import { filterMiddlewares } from './utils'; export class MiddlewareBuilder implements MiddlewaresConsumer { - private readonly middlewaresCollection = new Set(); - private readonly logger = new Logger(MiddlewareBuilder.name); + private readonly middlewaresCollection = new Set(); + private readonly logger = new Logger(MiddlewareBuilder.name); - constructor(private readonly routesMapper: RoutesMapper) {} + constructor(private readonly routesMapper: RoutesMapper) {} - public apply(middlewares: any | any[]): MiddlewareConfigProxy { - return new MiddlewareBuilder.ConfigProxy(this, middlewares); - } - - /** - * @deprecated - * Since version RC.6 this method is deprecated. Use apply() instead. - */ - public use(configuration: MiddlewareConfiguration) { - this.logger.warn('DEPRECATED! Since version RC.6 `use()` method is deprecated. Use `apply()` instead.'); + public apply(middlewares: any | any[]): MiddlewareConfigProxy { + return new MiddlewareBuilder.ConfigProxy(this, middlewares); + } - const { middlewares, forRoutes } = configuration; - if (isUndefined(middlewares) || isUndefined(forRoutes)) { - throw new InvalidMiddlewareConfigurationException(); - } + /** + * @deprecated + * Since version RC.6 this method is deprecated. Use apply() instead. + */ + public use(configuration: MiddlewareConfiguration) { + this.logger.warn( + 'DEPRECATED! Since version RC.6 `use()` method is deprecated. Use `apply()` instead.' + ); - this.middlewaresCollection.add(configuration); - return this; + const { middlewares, forRoutes } = configuration; + if (isUndefined(middlewares) || isUndefined(forRoutes)) { + throw new InvalidMiddlewareConfigurationException(); } - public build() { - return [...this.middlewaresCollection]; - } + this.middlewaresCollection.add(configuration); + return this; + } + + public build() { + return [...this.middlewaresCollection]; + } - private bindValuesToResolve(middlewares: Metatype | Metatype[], resolveParams: any[]) { - if (isNil(resolveParams)) { - return middlewares; - } - const bindArgs = BindResolveMiddlewareValues(resolveParams); - return [].concat(middlewares).map(bindArgs); + private bindValuesToResolve( + middlewares: Metatype | Metatype[], + resolveParams: any[] + ) { + if (isNil(resolveParams)) { + return middlewares; } + const bindArgs = BindResolveMiddlewareValues(resolveParams); + return [].concat(middlewares).map(bindArgs); + } - private static ConfigProxy = class implements MiddlewareConfigProxy { - private contextArgs = null; - private includedRoutes: any[]; + private static ConfigProxy = class implements MiddlewareConfigProxy { + private contextArgs = null; + private includedRoutes: any[]; - constructor( - private readonly builder: MiddlewareBuilder, - middlewares, - ) { - this.includedRoutes = filterMiddlewares(middlewares); - } + constructor(private readonly builder: MiddlewareBuilder, middlewares) { + this.includedRoutes = filterMiddlewares(middlewares); + } - public with(...args): MiddlewareConfigProxy { - this.contextArgs = args; - return this; - } + public with(...args): MiddlewareConfigProxy { + this.contextArgs = args; + return this; + } - public forRoutes(...routes): MiddlewaresConsumer { - const { middlewaresCollection, bindValuesToResolve, routesMapper } = this.builder; + public forRoutes(...routes): MiddlewaresConsumer { + const { + middlewaresCollection, + bindValuesToResolve, + routesMapper + } = this.builder; - const forRoutes = this.mapRoutesToFlatList( - routes.map((route) => routesMapper.mapRouteToRouteProps(route), - )); - const configuration = { - middlewares: bindValuesToResolve( - this.includedRoutes, this.contextArgs, - ), - forRoutes, - }; - middlewaresCollection.add(configuration); - return this.builder; - } + const forRoutes = this.mapRoutesToFlatList( + routes.map(route => routesMapper.mapRouteToRouteProps(route)) + ); + const configuration = { + middlewares: bindValuesToResolve(this.includedRoutes, this.contextArgs), + forRoutes + }; + middlewaresCollection.add(configuration); + return this.builder; + } - private mapRoutesToFlatList(forRoutes) { - return forRoutes.reduce((a, b) => a.concat(b)); - } - }; -} \ No newline at end of file + private mapRoutesToFlatList(forRoutes) { + return forRoutes.reduce((a, b) => a.concat(b)); + } + }; +} diff --git a/src/core/middlewares/container.ts b/src/core/middlewares/container.ts index 32af0a2f89d..5d4266975df 100644 --- a/src/core/middlewares/container.ts +++ b/src/core/middlewares/container.ts @@ -3,50 +3,53 @@ import { NestMiddleware } from '@nestjs/common/interfaces/middlewares/nest-middl import { Metatype } from '@nestjs/common/interfaces/metatype.interface'; export class MiddlewaresContainer { - private readonly middlewares = new Map>(); - private readonly configs = new Map>(); - - public getMiddlewares(module: string): Map { - return this.middlewares.get(module) || new Map(); - } - - public getConfigs(): Map> { - return this.configs; - } - - public addConfig(configList: MiddlewareConfiguration[], module: string) { - const middlewares = this.getCurrentMiddlewares(module); - const currentConfig = this.getCurrentConfig(module); - - const configurations = configList || []; - configurations.map((config) => { - [].concat(config.middlewares).map((metatype) => { - const token = metatype.name; - middlewares.set(token, { - instance: null, - metatype, - }); - }); - currentConfig.add(config); + private readonly middlewares = new Map< + string, + Map + >(); + private readonly configs = new Map>(); + + public getMiddlewares(module: string): Map { + return this.middlewares.get(module) || new Map(); + } + + public getConfigs(): Map> { + return this.configs; + } + + public addConfig(configList: MiddlewareConfiguration[], module: string) { + const middlewares = this.getCurrentMiddlewares(module); + const currentConfig = this.getCurrentConfig(module); + + const configurations = configList || []; + configurations.map(config => { + [].concat(config.middlewares).map(metatype => { + const token = metatype.name; + middlewares.set(token, { + instance: null, + metatype }); + }); + currentConfig.add(config); + }); + } + + private getCurrentMiddlewares(module: string) { + if (!this.middlewares.has(module)) { + this.middlewares.set(module, new Map()); } + return this.middlewares.get(module); + } - private getCurrentMiddlewares(module: string) { - if (!this.middlewares.has(module)) { - this.middlewares.set(module, new Map()); - } - return this.middlewares.get(module); - } - - private getCurrentConfig(module: string) { - if (!this.configs.has(module)) { - this.configs.set(module, new Set()); - } - return this.configs.get(module); + private getCurrentConfig(module: string) { + if (!this.configs.has(module)) { + this.configs.set(module, new Set()); } + return this.configs.get(module); + } } export interface MiddlewareWrapper { - instance: NestMiddleware; - metatype: Metatype; -} \ No newline at end of file + instance: NestMiddleware; + metatype: Metatype; +} diff --git a/src/core/middlewares/middlewares-module.ts b/src/core/middlewares/middlewares-module.ts index 5e51c0426f6..6ed5c40ed51 100644 --- a/src/core/middlewares/middlewares-module.ts +++ b/src/core/middlewares/middlewares-module.ts @@ -20,127 +20,155 @@ import { ApplicationConfig } from './../application-config'; import { RouterExceptionFilters } from './../router/router-exception-filters'; export class MiddlewaresModule { - private readonly routesMapper = new RoutesMapper(); - private readonly routerProxy = new RouterProxy(); - private readonly routerMethodFactory = new RouterMethodFactory(); - private routerExceptionFilter: RouterExceptionFilters; - private resolver: MiddlewaresResolver; - - public async setup( - middlewaresContainer: MiddlewaresContainer, - container: NestContainer, - config: ApplicationConfig, - ) { - this.routerExceptionFilter = new RouterExceptionFilters(config); - this.resolver = new MiddlewaresResolver(middlewaresContainer); - - const modules = container.getModules(); - await this.resolveMiddlewares(middlewaresContainer, modules); - } - - public async resolveMiddlewares( - middlewaresContainer: MiddlewaresContainer, - modules: Map, - ) { - await Promise.all([...modules.entries()].map(async ([name, module]) => { - const instance = module.instance; - - this.loadConfiguration(middlewaresContainer, instance, name); - await this.resolver.resolveInstances(module, name); - })); - } - - public loadConfiguration( - middlewaresContainer: MiddlewaresContainer, - instance: NestModule, - module: string, - ) { - if (!instance.configure) return; - - const middlewaresBuilder = new MiddlewareBuilder(this.routesMapper); - instance.configure(middlewaresBuilder); - - if (!(middlewaresBuilder instanceof MiddlewareBuilder)) return; - - const config = middlewaresBuilder.build(); - middlewaresContainer.addConfig(config, module); - } - - public async setupMiddlewares(middlewaresContainer: MiddlewaresContainer, app) { - const configs = middlewaresContainer.getConfigs(); - await Promise.all([...configs.entries()].map(async ([module, moduleConfigs]) => { - await Promise.all([...moduleConfigs].map(async (config: MiddlewareConfiguration) => { - await this.setupMiddlewareConfig(middlewaresContainer, config, module, app); - })); - })); - } - - public async setupMiddlewareConfig( - middlewaresContainer: MiddlewaresContainer, - config: MiddlewareConfiguration, - module: string, - app, - ) { - const { forRoutes } = config; - await Promise.all(forRoutes.map(async (route: ControllerMetadata & { method: RequestMethod }) => { - await this.setupRouteMiddleware(middlewaresContainer, route, config, module, app); - })); - } - - public async setupRouteMiddleware( - middlewaresContainer: MiddlewaresContainer, - route: ControllerMetadata & { method: RequestMethod }, - config: MiddlewareConfiguration, - module: string, - app, - ) { - const { path, method } = route; - - const middlewares = [].concat(config.middlewares); - await Promise.all(middlewares.map(async (metatype: Metatype) => { - const collection = middlewaresContainer.getMiddlewares(module); - const middleware = collection.get(metatype.name); - if (isUndefined(middleware)) { - throw new RuntimeException(); - } - - const { instance } = (middleware as MiddlewareWrapper); - await this.setupHandler(instance, metatype, app, method, path); - })); - } - - private async setupHandler( - instance: NestMiddleware, - metatype: Metatype, - app: any, - method: RequestMethod, - path: string) { - - if (isUndefined(instance.resolve)) { - throw new InvalidMiddlewareException(metatype.name); - } - const exceptionsHandler = this.routerExceptionFilter.create(instance, instance.resolve); - const router = this.routerMethodFactory.get(app, method).bind(app); - - const setupWithProxy = (middleware) => this.setupHandlerWithProxy( - exceptionsHandler, router, middleware, path, + private readonly routesMapper = new RoutesMapper(); + private readonly routerProxy = new RouterProxy(); + private readonly routerMethodFactory = new RouterMethodFactory(); + private routerExceptionFilter: RouterExceptionFilters; + private resolver: MiddlewaresResolver; + + public async setup( + middlewaresContainer: MiddlewaresContainer, + container: NestContainer, + config: ApplicationConfig + ) { + this.routerExceptionFilter = new RouterExceptionFilters(config); + this.resolver = new MiddlewaresResolver(middlewaresContainer); + + const modules = container.getModules(); + await this.resolveMiddlewares(middlewaresContainer, modules); + } + + public async resolveMiddlewares( + middlewaresContainer: MiddlewaresContainer, + modules: Map + ) { + await Promise.all( + [...modules.entries()].map(async ([name, module]) => { + const instance = module.instance; + + this.loadConfiguration(middlewaresContainer, instance, name); + await this.resolver.resolveInstances(module, name); + }) + ); + } + + public loadConfiguration( + middlewaresContainer: MiddlewaresContainer, + instance: NestModule, + module: string + ) { + if (!instance.configure) return; + + const middlewaresBuilder = new MiddlewareBuilder(this.routesMapper); + instance.configure(middlewaresBuilder); + + if (!(middlewaresBuilder instanceof MiddlewareBuilder)) return; + + const config = middlewaresBuilder.build(); + middlewaresContainer.addConfig(config, module); + } + + public async setupMiddlewares( + middlewaresContainer: MiddlewaresContainer, + app + ) { + const configs = middlewaresContainer.getConfigs(); + await Promise.all( + [...configs.entries()].map(async ([module, moduleConfigs]) => { + await Promise.all( + [...moduleConfigs].map(async (config: MiddlewareConfiguration) => { + await this.setupMiddlewareConfig( + middlewaresContainer, + config, + module, + app + ); + }) ); - const resolve = instance.resolve(); - if (!(resolve instanceof Promise)) { - setupWithProxy(resolve); - return; + }) + ); + } + + public async setupMiddlewareConfig( + middlewaresContainer: MiddlewaresContainer, + config: MiddlewareConfiguration, + module: string, + app + ) { + const { forRoutes } = config; + await Promise.all( + forRoutes.map( + async (route: ControllerMetadata & { method: RequestMethod }) => { + await this.setupRouteMiddleware( + middlewaresContainer, + route, + config, + module, + app + ); + } + ) + ); + } + + public async setupRouteMiddleware( + middlewaresContainer: MiddlewaresContainer, + route: ControllerMetadata & { method: RequestMethod }, + config: MiddlewareConfiguration, + module: string, + app + ) { + const { path, method } = route; + + const middlewares = [].concat(config.middlewares); + await Promise.all( + middlewares.map(async (metatype: Metatype) => { + const collection = middlewaresContainer.getMiddlewares(module); + const middleware = collection.get(metatype.name); + if (isUndefined(middleware)) { + throw new RuntimeException(); } - const middleware = await resolve; - setupWithProxy(middleware); - } - - private setupHandlerWithProxy( - exceptionsHandler: ExceptionsHandler, - router: (...args) => void, - middleware: (req, res, next) => void, - path: string) { - const proxy = this.routerProxy.createProxy(middleware, exceptionsHandler); - router(path, proxy); + const { instance } = middleware as MiddlewareWrapper; + await this.setupHandler(instance, metatype, app, method, path); + }) + ); + } + + private async setupHandler( + instance: NestMiddleware, + metatype: Metatype, + app: any, + method: RequestMethod, + path: string + ) { + if (isUndefined(instance.resolve)) { + throw new InvalidMiddlewareException(metatype.name); + } + const exceptionsHandler = this.routerExceptionFilter.create( + instance, + instance.resolve + ); + const router = this.routerMethodFactory.get(app, method).bind(app); + + const setupWithProxy = middleware => + this.setupHandlerWithProxy(exceptionsHandler, router, middleware, path); + const resolve = instance.resolve(); + if (!(resolve instanceof Promise)) { + setupWithProxy(resolve); + return; } -} \ No newline at end of file + const middleware = await resolve; + setupWithProxy(middleware); + } + + private setupHandlerWithProxy( + exceptionsHandler: ExceptionsHandler, + router: (...args) => void, + middleware: (req, res, next) => void, + path: string + ) { + const proxy = this.routerProxy.createProxy(middleware, exceptionsHandler); + router(path, proxy); + } +} diff --git a/src/core/middlewares/resolver.ts b/src/core/middlewares/resolver.ts index 4a0708528d1..3da0858f503 100644 --- a/src/core/middlewares/resolver.ts +++ b/src/core/middlewares/resolver.ts @@ -3,27 +3,29 @@ import { Injector } from '../injector/injector'; import { Module } from '../injector/module'; export class MiddlewaresResolver { - private readonly instanceLoader = new Injector(); + private readonly instanceLoader = new Injector(); - constructor(private readonly middlewaresContainer: MiddlewaresContainer) {} + constructor(private readonly middlewaresContainer: MiddlewaresContainer) {} - public async resolveInstances(module: Module, moduleName: string) { - const middlewares = this.middlewaresContainer.getMiddlewares(moduleName); - await Promise.all([...middlewares.values()].map(async (wrapper) => - await this.resolveMiddlewareInstance(wrapper, middlewares, module), - )); - } - - private async resolveMiddlewareInstance( - wrapper: MiddlewareWrapper, - middlewares: Map, - module: Module) { - - await this.instanceLoader.loadInstanceOfMiddleware( - wrapper, - middlewares, - module, - ); - } + public async resolveInstances(module: Module, moduleName: string) { + const middlewares = this.middlewaresContainer.getMiddlewares(moduleName); + await Promise.all( + [...middlewares.values()].map( + async wrapper => + await this.resolveMiddlewareInstance(wrapper, middlewares, module) + ) + ); + } + private async resolveMiddlewareInstance( + wrapper: MiddlewareWrapper, + middlewares: Map, + module: Module + ) { + await this.instanceLoader.loadInstanceOfMiddleware( + wrapper, + middlewares, + module + ); + } } diff --git a/src/core/middlewares/routes-mapper.ts b/src/core/middlewares/routes-mapper.ts index c11586c9f80..3781e23ad1e 100644 --- a/src/core/middlewares/routes-mapper.ts +++ b/src/core/middlewares/routes-mapper.ts @@ -7,37 +7,43 @@ import { PATH_METADATA } from '@nestjs/common/constants'; import { MetadataScanner } from '../metadata-scanner'; export class RoutesMapper { - private readonly routerExplorer = new ExpressRouterExplorer(new MetadataScanner()); + private readonly routerExplorer = new ExpressRouterExplorer( + new MetadataScanner() + ); - public mapRouteToRouteProps(routeMetatype) { - const routePath: string = Reflect.getMetadata(PATH_METADATA, routeMetatype); - if (isUndefined(routePath)) { - return [this.mapObjectToRouteProps(routeMetatype)]; - } - const paths = this.routerExplorer.scanForPaths(Object.create(routeMetatype), routeMetatype.prototype); - return paths.map((route) => ({ - path: this.validateGlobalPath(routePath) + this.validateRoutePath(route.path), - method: route.requestMethod, - })); + public mapRouteToRouteProps(routeMetatype) { + const routePath: string = Reflect.getMetadata(PATH_METADATA, routeMetatype); + if (isUndefined(routePath)) { + return [this.mapObjectToRouteProps(routeMetatype)]; } + const paths = this.routerExplorer.scanForPaths( + Object.create(routeMetatype), + routeMetatype.prototype + ); + return paths.map(route => ({ + path: + this.validateGlobalPath(routePath) + this.validateRoutePath(route.path), + method: route.requestMethod + })); + } - private mapObjectToRouteProps(route) { - const { path, method } = route; - if (isUndefined(path)) { - throw new UnknownRequestMappingException(); - } - return { - path: this.validateRoutePath(path), - method: isUndefined(method) ? RequestMethod.ALL : method, - }; + private mapObjectToRouteProps(route) { + const { path, method } = route; + if (isUndefined(path)) { + throw new UnknownRequestMappingException(); } + return { + path: this.validateRoutePath(path), + method: isUndefined(method) ? RequestMethod.ALL : method + }; + } - private validateGlobalPath(path: string): string { - const prefix = validatePath(path); - return prefix === '/' ? '' : prefix; - } + private validateGlobalPath(path: string): string { + const prefix = validatePath(path); + return prefix === '/' ? '' : prefix; + } - private validateRoutePath(path: string): string { - return validatePath(path); - } + private validateRoutePath(path: string): string { + return validatePath(path); + } } diff --git a/src/core/middlewares/utils.ts b/src/core/middlewares/utils.ts index 21435c22903..ef5c3ab8451 100644 --- a/src/core/middlewares/utils.ts +++ b/src/core/middlewares/utils.ts @@ -1,27 +1,31 @@ import { isFunction } from '@nestjs/common/utils/shared.utils'; import { Metatype } from '@nestjs/common/interfaces'; -export const filterMiddlewares = (middlewares) => { - return [].concat(middlewares) - .filter(isFunction) - .map((middleware) => mapToClass(middleware)); +export const filterMiddlewares = middlewares => { + return [] + .concat(middlewares) + .filter(isFunction) + .map(middleware => mapToClass(middleware)); }; -export const mapToClass = (middleware) => { - if (this.isClass(middleware)) { - return middleware; +export const mapToClass = middleware => { + if (this.isClass(middleware)) { + return middleware; + } + return assignToken( + class { + public resolve = (...args) => (req, res, next) => + middleware(req, res, next); } - return assignToken(class { - public resolve = (...args) => (req, res, next) => middleware(req, res, next); - }); + ); }; -export const isClass = (middleware) => { - return middleware.toString().substring(0, 5) === 'class'; +export const isClass = middleware => { + return middleware.toString().substring(0, 5) === 'class'; }; export const assignToken = (metatype): Metatype => { - this.id = this.id || 1; - Object.defineProperty(metatype, 'name', { value: ++this.id }); - return metatype; -}; \ No newline at end of file + this.id = this.id || 1; + Object.defineProperty(metatype, 'name', { value: ++this.id }); + return metatype; +}; diff --git a/src/core/nest-application-context.ts b/src/core/nest-application-context.ts index 02d793a16fe..f157eeb06f1 100644 --- a/src/core/nest-application-context.ts +++ b/src/core/nest-application-context.ts @@ -1,4 +1,3 @@ - import { ModuleTokenFactory } from './injector/module-token-factory'; import { NestContainer, InstanceWrapper } from './injector/container'; import { NestModuleMetatype } from '@nestjs/common/interfaces/modules/module-metatype.interface'; @@ -7,40 +6,44 @@ import { isFunction } from '@nestjs/common/utils/shared.utils'; import { INestApplicationContext } from '@nestjs/common'; export class NestApplicationContext implements INestApplicationContext { - private readonly moduleTokenFactory = new ModuleTokenFactory(); + private readonly moduleTokenFactory = new ModuleTokenFactory(); - constructor( - protected readonly container: NestContainer, - private readonly scope: NestModuleMetatype[], - protected contextModule, - ) {} + constructor( + protected readonly container: NestContainer, + private readonly scope: NestModuleMetatype[], + protected contextModule + ) {} - public select(module: Metatype): INestApplicationContext { - const modules = this.container.getModules(); - const moduleMetatype = this.contextModule.metatype; - const scope = this.scope.concat(moduleMetatype); + public select(module: Metatype): INestApplicationContext { + const modules = this.container.getModules(); + const moduleMetatype = this.contextModule.metatype; + const scope = this.scope.concat(moduleMetatype); - const token = this.moduleTokenFactory.create(module as any, scope); - const selectedModule = modules.get(token); - return selectedModule - ? new NestApplicationContext(this.container, scope, selectedModule) - : null; - } + const token = this.moduleTokenFactory.create(module as any, scope); + const selectedModule = modules.get(token); + return selectedModule + ? new NestApplicationContext(this.container, scope, selectedModule) + : null; + } - public get(metatypeOrToken: Metatype | string | symbol): T { - return this.findInstanceByPrototypeOrToken(metatypeOrToken); - } + public get(metatypeOrToken: Metatype | string | symbol): T { + return this.findInstanceByPrototypeOrToken(metatypeOrToken); + } - private findInstanceByPrototypeOrToken(metatypeOrToken: Metatype | string | symbol) { - const dependencies = new Map([ - ...this.contextModule.components, - ...this.contextModule.routes, - ...this.contextModule.injectables, - ]); - const name = isFunction(metatypeOrToken) ? (metatypeOrToken as any).name : metatypeOrToken; - const instanceWrapper = dependencies.get(name); - return instanceWrapper - ? (instanceWrapper as InstanceWrapper).instance - : null; - } -} \ No newline at end of file + private findInstanceByPrototypeOrToken( + metatypeOrToken: Metatype | string | symbol + ) { + const dependencies = new Map([ + ...this.contextModule.components, + ...this.contextModule.routes, + ...this.contextModule.injectables + ]); + const name = isFunction(metatypeOrToken) + ? (metatypeOrToken as any).name + : metatypeOrToken; + const instanceWrapper = dependencies.get(name); + return instanceWrapper + ? (instanceWrapper as InstanceWrapper).instance + : null; + } +} diff --git a/src/core/nest-application.ts b/src/core/nest-application.ts index e29ffcfeb77..9d4b4727a79 100644 --- a/src/core/nest-application.ts +++ b/src/core/nest-application.ts @@ -3,16 +3,24 @@ import * as optional from 'optional'; import * as bodyParser from 'body-parser'; import iterate from 'iterare'; import { - CanActivate, - ExceptionFilter, - NestInterceptor, - OnModuleDestroy, - PipeTransform, - WebSocketAdapter, - } from '@nestjs/common'; -import { INestApplication, INestMicroservice, OnModuleInit } from '@nestjs/common'; + CanActivate, + ExceptionFilter, + NestInterceptor, + OnModuleDestroy, + PipeTransform, + WebSocketAdapter +} from '@nestjs/common'; +import { + INestApplication, + INestMicroservice, + OnModuleInit +} from '@nestjs/common'; import { Logger } from '@nestjs/common/services/logger.service'; -import { isNil, isUndefined, validatePath } from '@nestjs/common/utils/shared.utils'; +import { + isNil, + isUndefined, + validatePath +} from '@nestjs/common/utils/shared.utils'; import { MicroserviceConfiguration } from '@nestjs/common/interfaces/microservices/microservice-configuration.interface'; import { ExpressAdapter } from './adapters/express-adapter'; import { ApplicationConfig } from './application-config'; @@ -26,224 +34,239 @@ import { MicroservicesPackageNotFoundException } from './errors/exceptions/micro import { MiddlewaresContainer } from './middlewares/container'; import { NestApplicationContext } from './nest-application-context'; -const { SocketModule } = optional('@nestjs/websockets/socket-module') || {} as any; -const { MicroservicesModule } = optional('@nestjs/microservices/microservices-module') || {} as any; -const { NestMicroservice } = optional('@nestjs/microservices/nest-microservice') || {} as any; -const { IoAdapter } = optional('@nestjs/websockets/adapters/io-adapter') || {} as any; - -export class NestApplication extends NestApplicationContext implements INestApplication { - private readonly logger = new Logger(NestApplication.name, true); - private readonly middlewaresModule = new MiddlewaresModule(); - private readonly middlewaresContainer = new MiddlewaresContainer(); - private readonly microservicesModule = MicroservicesModule - ? new MicroservicesModule() - : null; - private readonly socketModule = SocketModule - ? new SocketModule() - : null; - - private readonly httpServer: http.Server = null; - private readonly routesResolver: Resolver = null; - private readonly config: ApplicationConfig; - private readonly microservices = []; - private isInitialized = false; - - constructor(container: NestContainer, private readonly express) { - super(container, [], null); - - const modules = this.container.getModules().values(); - this.contextModule = modules.next().value; - this.httpServer = http.createServer(express); - - const ioAdapter = IoAdapter ? new IoAdapter(this.httpServer) : null; - this.config = new ApplicationConfig(ioAdapter); - this.routesResolver = new RoutesResolver( - container, ExpressAdapter, this.config, - ); - } - - public async setupModules() { - this.socketModule && this.socketModule.setup(this.container, this.config); - - if (this.microservicesModule) { - this.microservicesModule.setup(this.container, this.config); - this.microservicesModule.setupClients(this.container); - } - await this.middlewaresModule.setup( - this.middlewaresContainer, - this.container, - this.config, - ); - } - - public async init() { - this.setupParserMiddlewares(); - - await this.setupModules(); - await this.setupRouter(); - - this.callInitHook(); - this.logger.log(messages.APPLICATION_READY); - this.isInitialized = true; - } - - public setupParserMiddlewares() { - const parserMiddlewares = { - jsonParser: bodyParser.json(), - urlencodedParser: bodyParser.urlencoded({ extended: true }), - }; - Object.keys(parserMiddlewares) - .filter((parser) => !this.isMiddlewareApplied(this.express, parser)) - .forEach((parserKey) => this.express.use(parserMiddlewares[parserKey])); - } - - public isMiddlewareApplied(app, name: string): boolean { - return !!app._router && !!app._router.stack.filter( - (layer) => layer && layer.handle && layer.handle.name === name, - ).length; - } - - public async setupRouter() { - const router = ExpressAdapter.createRouter(); - await this.setupMiddlewares(router); - - this.routesResolver.resolve(router); - this.express.use(validatePath(this.config.getGlobalPrefix()), router); - } - - public connectMicroservice(config: MicroserviceConfiguration): INestMicroservice { - if (!NestMicroservice) { - throw new MicroservicesPackageNotFoundException(); - } - const instance = new NestMicroservice(this.container as any, config as any); - instance.setupListeners(); - instance.setIsInitialized(true); - instance.setIsInitHookCalled(true); - - this.microservices.push(instance); - return instance; - } - - public getMicroservices(): INestMicroservice[] { - return this.microservices; - } - - public getHttpServer() { - return this.httpServer; - } - - public startAllMicroservices(callback?: () => void) { - Promise.all( - this.microservices.map(this.listenToPromise), - ).then(() => callback && callback()); - } - - public startAllMicroservicesAsync(): Promise { - return new Promise((resolve) => this.startAllMicroservices(resolve)); - } - - public use(...args) { - this.express.use(...args); - } - - public set(...args) { - this.express.set(...args); - } - - public async listen(port: number, callback?: () => void); - public async listen(port: number, hostname: string, callback?: () => void); - public async listen(port: number, ...args) { - (!this.isInitialized) && await this.init(); - - this.httpServer.listen(port, ...args); - return this.httpServer; - } - - public listenAsync(port: number, hostname?: string): Promise { - return new Promise((resolve) => { - const server = this.listen(port, hostname, () => resolve(server)); - }); - } - - public close() { - this.socketModule && this.socketModule.close(); - this.httpServer && this.httpServer.close(); - this.microservices.forEach((microservice) => { - microservice.setIsTerminated(true); - microservice.close(); - }); - this.callDestroyHook(); - } - - public setGlobalPrefix(prefix: string) { - this.config.setGlobalPrefix(prefix); - } - - public useWebSocketAdapter(adapter: WebSocketAdapter) { - this.config.setIoAdapter(adapter); - } - - public useGlobalFilters(...filters: ExceptionFilter[]) { - this.config.useGlobalFilters(...filters); - } - - public useGlobalPipes(...pipes: PipeTransform[]) { - this.config.useGlobalPipes(...pipes); - } - - public useGlobalInterceptors(...interceptors: NestInterceptor[]) { - this.config.useGlobalInterceptors(...interceptors); +const { SocketModule } = + optional('@nestjs/websockets/socket-module') || ({} as any); +const { MicroservicesModule } = + optional('@nestjs/microservices/microservices-module') || ({} as any); +const { NestMicroservice } = + optional('@nestjs/microservices/nest-microservice') || ({} as any); +const { IoAdapter } = + optional('@nestjs/websockets/adapters/io-adapter') || ({} as any); + +export class NestApplication extends NestApplicationContext + implements INestApplication { + private readonly logger = new Logger(NestApplication.name, true); + private readonly middlewaresModule = new MiddlewaresModule(); + private readonly middlewaresContainer = new MiddlewaresContainer(); + private readonly microservicesModule = MicroservicesModule + ? new MicroservicesModule() + : null; + private readonly socketModule = SocketModule ? new SocketModule() : null; + + private readonly httpServer: http.Server = null; + private readonly routesResolver: Resolver = null; + private readonly config: ApplicationConfig; + private readonly microservices = []; + private isInitialized = false; + + constructor(container: NestContainer, private readonly express) { + super(container, [], null); + + const modules = this.container.getModules().values(); + this.contextModule = modules.next().value; + this.httpServer = http.createServer(express); + + const ioAdapter = IoAdapter ? new IoAdapter(this.httpServer) : null; + this.config = new ApplicationConfig(ioAdapter); + this.routesResolver = new RoutesResolver( + container, + ExpressAdapter, + this.config + ); + } + + public async setupModules() { + this.socketModule && this.socketModule.setup(this.container, this.config); + + if (this.microservicesModule) { + this.microservicesModule.setup(this.container, this.config); + this.microservicesModule.setupClients(this.container); } - - public useGlobalGuards(...guards: CanActivate[]) { - this.config.useGlobalGuards(...guards); - } - - private async setupMiddlewares(instance) { - await this.middlewaresModule.setupMiddlewares(this.middlewaresContainer, instance); - } - - private listenToPromise(microservice: INestMicroservice) { - return new Promise(async (resolve, reject) => { - await microservice.listen(resolve); - }); - } - - private callInitHook() { - const modules = this.container.getModules(); - modules.forEach((module) => { - this.callModuleInitHook(module); - }); - } - - private callModuleInitHook(module: Module) { - const components = [...module.routes, ...module.components]; - iterate(components).map(([key, {instance}]) => instance) - .filter((instance) => !isNil(instance)) - .filter(this.hasOnModuleInitHook) - .forEach((instance) => (instance as OnModuleInit).onModuleInit()); - } - - private hasOnModuleInitHook(instance): instance is OnModuleInit { - return !isUndefined((instance as OnModuleInit).onModuleInit); - } - - private callDestroyHook() { - const modules = this.container.getModules(); - modules.forEach((module) => { - this.callModuleDestroyHook(module); - }); - } - - private callModuleDestroyHook(module: Module) { - const components = [...module.routes, ...module.components]; - iterate(components).map(([key, {instance}]) => instance) - .filter((instance) => !isNil(instance)) - .filter(this.hasOnModuleDestroyHook) - .forEach((instance) => (instance as OnModuleDestroy).onModuleDestroy()); - } - - private hasOnModuleDestroyHook(instance): instance is OnModuleDestroy { - return !isUndefined((instance as OnModuleDestroy).onModuleDestroy); + await this.middlewaresModule.setup( + this.middlewaresContainer, + this.container, + this.config + ); + } + + public async init() { + this.setupParserMiddlewares(); + + await this.setupModules(); + await this.setupRouter(); + + this.callInitHook(); + this.logger.log(messages.APPLICATION_READY); + this.isInitialized = true; + } + + public setupParserMiddlewares() { + const parserMiddlewares = { + jsonParser: bodyParser.json(), + urlencodedParser: bodyParser.urlencoded({ extended: true }) + }; + Object.keys(parserMiddlewares) + .filter(parser => !this.isMiddlewareApplied(this.express, parser)) + .forEach(parserKey => this.express.use(parserMiddlewares[parserKey])); + } + + public isMiddlewareApplied(app, name: string): boolean { + return ( + !!app._router && + !!app._router.stack.filter( + layer => layer && layer.handle && layer.handle.name === name + ).length + ); + } + + public async setupRouter() { + const router = ExpressAdapter.createRouter(); + await this.setupMiddlewares(router); + + this.routesResolver.resolve(router); + this.express.use(validatePath(this.config.getGlobalPrefix()), router); + } + + public connectMicroservice( + config: MicroserviceConfiguration + ): INestMicroservice { + if (!NestMicroservice) { + throw new MicroservicesPackageNotFoundException(); } -} \ No newline at end of file + const instance = new NestMicroservice(this.container as any, config as any); + instance.setupListeners(); + instance.setIsInitialized(true); + instance.setIsInitHookCalled(true); + + this.microservices.push(instance); + return instance; + } + + public getMicroservices(): INestMicroservice[] { + return this.microservices; + } + + public getHttpServer() { + return this.httpServer; + } + + public startAllMicroservices(callback?: () => void) { + Promise.all(this.microservices.map(this.listenToPromise)).then( + () => callback && callback() + ); + } + + public startAllMicroservicesAsync(): Promise { + return new Promise(resolve => this.startAllMicroservices(resolve)); + } + + public use(...args) { + this.express.use(...args); + } + + public set(...args) { + this.express.set(...args); + } + + public async listen(port: number, callback?: () => void); + public async listen(port: number, hostname: string, callback?: () => void); + public async listen(port: number, ...args) { + !this.isInitialized && (await this.init()); + + this.httpServer.listen(port, ...args); + return this.httpServer; + } + + public listenAsync(port: number, hostname?: string): Promise { + return new Promise(resolve => { + const server = this.listen(port, hostname, () => resolve(server)); + }); + } + + public close() { + this.socketModule && this.socketModule.close(); + this.httpServer && this.httpServer.close(); + this.microservices.forEach(microservice => { + microservice.setIsTerminated(true); + microservice.close(); + }); + this.callDestroyHook(); + } + + public setGlobalPrefix(prefix: string) { + this.config.setGlobalPrefix(prefix); + } + + public useWebSocketAdapter(adapter: WebSocketAdapter) { + this.config.setIoAdapter(adapter); + } + + public useGlobalFilters(...filters: ExceptionFilter[]) { + this.config.useGlobalFilters(...filters); + } + + public useGlobalPipes(...pipes: PipeTransform[]) { + this.config.useGlobalPipes(...pipes); + } + + public useGlobalInterceptors(...interceptors: NestInterceptor[]) { + this.config.useGlobalInterceptors(...interceptors); + } + + public useGlobalGuards(...guards: CanActivate[]) { + this.config.useGlobalGuards(...guards); + } + + private async setupMiddlewares(instance) { + await this.middlewaresModule.setupMiddlewares( + this.middlewaresContainer, + instance + ); + } + + private listenToPromise(microservice: INestMicroservice) { + return new Promise(async (resolve, reject) => { + await microservice.listen(resolve); + }); + } + + private callInitHook() { + const modules = this.container.getModules(); + modules.forEach(module => { + this.callModuleInitHook(module); + }); + } + + private callModuleInitHook(module: Module) { + const components = [...module.routes, ...module.components]; + iterate(components) + .map(([key, { instance }]) => instance) + .filter(instance => !isNil(instance)) + .filter(this.hasOnModuleInitHook) + .forEach(instance => (instance as OnModuleInit).onModuleInit()); + } + + private hasOnModuleInitHook(instance): instance is OnModuleInit { + return !isUndefined((instance as OnModuleInit).onModuleInit); + } + + private callDestroyHook() { + const modules = this.container.getModules(); + modules.forEach(module => { + this.callModuleDestroyHook(module); + }); + } + + private callModuleDestroyHook(module: Module) { + const components = [...module.routes, ...module.components]; + iterate(components) + .map(([key, { instance }]) => instance) + .filter(instance => !isNil(instance)) + .filter(this.hasOnModuleDestroyHook) + .forEach(instance => (instance as OnModuleDestroy).onModuleDestroy()); + } + + private hasOnModuleDestroyHook(instance): instance is OnModuleDestroy { + return !isUndefined((instance as OnModuleDestroy).onModuleDestroy); + } +} diff --git a/src/core/nest-factory.ts b/src/core/nest-factory.ts index 05f0632591e..913bba20bbb 100644 --- a/src/core/nest-factory.ts +++ b/src/core/nest-factory.ts @@ -10,115 +10,123 @@ import { NestApplication } from './nest-application'; import { isFunction } from '@nestjs/common/utils/shared.utils'; import { MicroserviceConfiguration } from '@nestjs/common/interfaces/microservices/microservice-configuration.interface'; import { ExpressAdapter } from './adapters/express-adapter'; -import { INestApplication, INestMicroservice, INestApplicationContext } from '@nestjs/common'; +import { + INestApplication, + INestMicroservice, + INestApplicationContext +} from '@nestjs/common'; import { MetadataScanner } from './metadata-scanner'; import { MicroservicesPackageNotFoundException } from './errors/exceptions/microservices-package-not-found.exception'; import { NestApplicationContext } from './nest-application-context'; -const { NestMicroservice } = optional('@nestjs/microservices/nest-microservice') || {} as any; +const { NestMicroservice } = + optional('@nestjs/microservices/nest-microservice') || ({} as any); export class NestFactoryStatic { - private container = new NestContainer(); - private instanceLoader = new InstanceLoader(this.container); - private logger = new Logger('NestFactory', true); - private dependenciesScanner = new DependenciesScanner( - this.container, new MetadataScanner(), + private container = new NestContainer(); + private instanceLoader = new InstanceLoader(this.container); + private logger = new Logger('NestFactory', true); + private dependenciesScanner = new DependenciesScanner( + this.container, + new MetadataScanner() + ); + + /** + * Creates an instance of the NestApplication (returns Promise) + * + * @param {} module Entry (root) application module class + * @param {} express Optional express() server instance + * @returns an `Promise` of the INestApplication instance + */ + public async create( + module, + express = ExpressAdapter.create() + ): Promise { + await this.initialize(module); + return this.createNestInstance( + new NestApplication(this.container, express) ); + } - /** - * Creates an instance of the NestApplication (returns Promise) - * - * @param {} module Entry (root) application module class - * @param {} express Optional express() server instance - * @returns an `Promise` of the INestApplication instance - */ - public async create(module, express = ExpressAdapter.create()): Promise { - await this.initialize(module); - return this.createNestInstance( - new NestApplication(this.container, express), - ); + /** + * Creates an instance of the NestMicroservice (returns Promise) + * + * @param {} module Entry (root) application module class + * @param {MicroserviceConfiguration} config Optional microservice configuration + * @returns an `Promise` of the INestMicroservice instance + */ + public async createMicroservice( + module, + config?: MicroserviceConfiguration + ): Promise { + if (!NestMicroservice) { + throw new MicroservicesPackageNotFoundException(); } - /** - * Creates an instance of the NestMicroservice (returns Promise) - * - * @param {} module Entry (root) application module class - * @param {MicroserviceConfiguration} config Optional microservice configuration - * @returns an `Promise` of the INestMicroservice instance - */ - public async createMicroservice( - module, - config?: MicroserviceConfiguration): Promise { - - if (!NestMicroservice) { - throw new MicroservicesPackageNotFoundException(); - } - - await this.initialize(module); - return this.createNestInstance( - new NestMicroservice(this.container, config as any), - ); - } + await this.initialize(module); + return this.createNestInstance( + new NestMicroservice(this.container, config as any) + ); + } - /** - * Creates an instance of the NestApplicationContext (returns Promise) - * - * @param {} module Entry (root) application module class - * @returns an `Promise` of the INestApplicationContext instance - */ - public async createApplicationContext(module): Promise { - await this.initialize(module); + /** + * Creates an instance of the NestApplicationContext (returns Promise) + * + * @param {} module Entry (root) application module class + * @returns an `Promise` of the INestApplicationContext instance + */ + public async createApplicationContext( + module + ): Promise { + await this.initialize(module); - const modules = this.container.getModules().values(); - const root = modules.next().value; - return this.createNestInstance( - new NestApplicationContext(this.container, [], root), - ); - } + const modules = this.container.getModules().values(); + const root = modules.next().value; + return this.createNestInstance( + new NestApplicationContext(this.container, [], root) + ); + } - private createNestInstance(instance: T) { - return this.createProxy(instance); - } + private createNestInstance(instance: T) { + return this.createProxy(instance); + } - private async initialize(module) { - try { - this.logger.log(messages.APPLICATION_START); - await ExceptionsZone.asyncRun(async () => { - this.dependenciesScanner.scan(module); - await this.instanceLoader.createInstancesOfDependencies(); - }); - } - catch (e) { - process.abort(); - } + private async initialize(module) { + try { + this.logger.log(messages.APPLICATION_START); + await ExceptionsZone.asyncRun(async () => { + this.dependenciesScanner.scan(module); + await this.instanceLoader.createInstancesOfDependencies(); + }); + } catch (e) { + process.abort(); } + } - private createProxy(target) { - const proxy = this.createExceptionProxy(); - return new Proxy(target, { - get: proxy, - set: proxy, - }); - } + private createProxy(target) { + const proxy = this.createExceptionProxy(); + return new Proxy(target, { + get: proxy, + set: proxy + }); + } - private createExceptionProxy() { - return (receiver, prop) => { - if (!(prop in receiver)) - return; + private createExceptionProxy() { + return (receiver, prop) => { + if (!(prop in receiver)) return; - if (isFunction(receiver[prop])) { - return (...args) => { - let result; - ExceptionsZone.run(() => { - result = receiver[prop](...args); - }); - return result; - }; - } - return receiver[prop]; + if (isFunction(receiver[prop])) { + return (...args) => { + let result; + ExceptionsZone.run(() => { + result = receiver[prop](...args); + }); + return result; }; - } + } + return receiver[prop]; + }; + } } export const NestFactory = new NestFactoryStatic(); - diff --git a/src/core/pipes/params-token-factory.ts b/src/core/pipes/params-token-factory.ts index c68724df706..00f8bc0c418 100644 --- a/src/core/pipes/params-token-factory.ts +++ b/src/core/pipes/params-token-factory.ts @@ -2,12 +2,16 @@ import { RouteParamtypes } from '@nestjs/common/enums/route-paramtypes.enum'; import { Paramtype } from '@nestjs/common'; export class ParamsTokenFactory { - public exchangeEnumForString(type: RouteParamtypes): Paramtype { - switch (type) { - case RouteParamtypes.BODY: return 'body'; - case RouteParamtypes.PARAM: return 'param'; - case RouteParamtypes.QUERY: return 'query'; - default: return 'custom'; - } + public exchangeEnumForString(type: RouteParamtypes): Paramtype { + switch (type) { + case RouteParamtypes.BODY: + return 'body'; + case RouteParamtypes.PARAM: + return 'param'; + case RouteParamtypes.QUERY: + return 'query'; + default: + return 'custom'; } -} \ No newline at end of file + } +} diff --git a/src/core/pipes/pipes-consumer.ts b/src/core/pipes/pipes-consumer.ts index 457e1a665f2..1034062220c 100644 --- a/src/core/pipes/pipes-consumer.ts +++ b/src/core/pipes/pipes-consumer.ts @@ -3,21 +3,33 @@ import { RouteParamtypes } from '@nestjs/common/enums/route-paramtypes.enum'; import { ParamsTokenFactory } from './../pipes/params-token-factory'; export class PipesConsumer { - private readonly paramsTokenFactory = new ParamsTokenFactory(); + private readonly paramsTokenFactory = new ParamsTokenFactory(); - public async apply(value, { metatype, type, data }, transforms: Transform[]) { - const token = this.paramsTokenFactory.exchangeEnumForString(type); - return await this.applyPipes(value, { metatype, type: token, data }, transforms); - } + public async apply( + value, + { metatype, type, data }, + transforms: Transform[] + ) { + const token = this.paramsTokenFactory.exchangeEnumForString(type); + return await this.applyPipes( + value, + { metatype, type: token, data }, + transforms + ); + } - public async applyPipes(value, { metatype, type, data }: { metatype, type?, data? }, transforms: Transform[]) { - return await transforms.reduce(async (defferedValue, fn) => { - const val = await defferedValue; - const result = fn(val, { metatype, type, data }); - if (result instanceof Promise) { - return result; - } - return Promise.resolve(result); - }, Promise.resolve(value)); - } -} \ No newline at end of file + public async applyPipes( + value, + { metatype, type, data }: { metatype; type?; data? }, + transforms: Transform[] + ) { + return await transforms.reduce(async (defferedValue, fn) => { + const val = await defferedValue; + const result = fn(val, { metatype, type, data }); + if (result instanceof Promise) { + return result; + } + return Promise.resolve(result); + }, Promise.resolve(value)); + } +} diff --git a/src/core/pipes/pipes-context-creator.ts b/src/core/pipes/pipes-context-creator.ts index 22b403a6a1d..dba638910b5 100644 --- a/src/core/pipes/pipes-context-creator.ts +++ b/src/core/pipes/pipes-context-creator.ts @@ -1,33 +1,47 @@ import 'reflect-metadata'; import iterate from 'iterare'; -import { Controller, PipeTransform, Transform } from '@nestjs/common/interfaces'; +import { + Controller, + PipeTransform, + Transform +} from '@nestjs/common/interfaces'; import { PIPES_METADATA } from '@nestjs/common/constants'; -import { isUndefined, isFunction, isEmpty } from '@nestjs/common/utils/shared.utils'; +import { + isUndefined, + isFunction, + isEmpty +} from '@nestjs/common/utils/shared.utils'; import { ApplicationConfig } from './../application-config'; import { ContextCreator } from './../helpers/context-creator'; export class PipesContextCreator extends ContextCreator { - constructor(private readonly config?: ApplicationConfig) { - super(); - } + constructor(private readonly config?: ApplicationConfig) { + super(); + } - public create(instance: Controller, callback: (...args) => any): Transform[] { - return this.createContext(instance, callback, PIPES_METADATA); - } + public create( + instance: Controller, + callback: (...args) => any + ): Transform[] { + return this.createContext(instance, callback, PIPES_METADATA); + } - public createConcreteContext(metadata: T): R { - if (isUndefined(metadata) || isEmpty(metadata)) { - return [] as R; - } - return iterate(metadata).filter((pipe) => pipe && pipe.transform && isFunction(pipe.transform)) - .map((pipe) => pipe.transform.bind(pipe)) - .toArray() as R; + public createConcreteContext( + metadata: T + ): R { + if (isUndefined(metadata) || isEmpty(metadata)) { + return [] as R; } + return iterate(metadata) + .filter(pipe => pipe && pipe.transform && isFunction(pipe.transform)) + .map(pipe => pipe.transform.bind(pipe)) + .toArray() as R; + } - public getGlobalMetadata(): T { - if (!this.config) { - return [] as T; - } - return this.config.getGlobalPipes() as T; + public getGlobalMetadata(): T { + if (!this.config) { + return [] as T; } -} \ No newline at end of file + return this.config.getGlobalPipes() as T; + } +} diff --git a/src/core/router/interfaces/exceptions-filter.interface.ts b/src/core/router/interfaces/exceptions-filter.interface.ts index 3acd3cec63e..38f01c80d4d 100644 --- a/src/core/router/interfaces/exceptions-filter.interface.ts +++ b/src/core/router/interfaces/exceptions-filter.interface.ts @@ -2,5 +2,5 @@ import { Controller } from '@nestjs/common/interfaces/controllers/controller.int import { ExceptionsHandler } from '../../exceptions/exceptions-handler'; export interface ExceptionsFilter { - create(instance: Controller, callback): ExceptionsHandler; -} \ No newline at end of file + create(instance: Controller, callback): ExceptionsHandler; +} diff --git a/src/core/router/interfaces/explorer.inteface.ts b/src/core/router/interfaces/explorer.inteface.ts index 15b4fc430ee..4805b568209 100644 --- a/src/core/router/interfaces/explorer.inteface.ts +++ b/src/core/router/interfaces/explorer.inteface.ts @@ -2,6 +2,6 @@ import { Controller } from '@nestjs/common/interfaces/index'; import { Metatype } from '@nestjs/common/interfaces/metatype.interface'; export interface RouterExplorer { - explore(instance: Controller, metatype: Metatype, module: string); - fetchRouterPath(metatype: Metatype): string; -} \ No newline at end of file + explore(instance: Controller, metatype: Metatype, module: string); + fetchRouterPath(metatype: Metatype): string; +} diff --git a/src/core/router/interfaces/resolver.interface.ts b/src/core/router/interfaces/resolver.interface.ts index ee036b74e05..966acdea135 100644 --- a/src/core/router/interfaces/resolver.interface.ts +++ b/src/core/router/interfaces/resolver.interface.ts @@ -1,3 +1,3 @@ export interface Resolver { resolve(express); -} \ No newline at end of file +} diff --git a/src/core/router/interfaces/route-params-factory.interface.ts b/src/core/router/interfaces/route-params-factory.interface.ts index f8fe2003bab..55e3986acd5 100644 --- a/src/core/router/interfaces/route-params-factory.interface.ts +++ b/src/core/router/interfaces/route-params-factory.interface.ts @@ -1,5 +1,5 @@ import { RouteParamtypes } from '@nestjs/common/enums/route-paramtypes.enum'; export interface IRouteParamsFactory { - exchangeKeyForValue(key: RouteParamtypes | string, data, { req, res, next }); -} \ No newline at end of file + exchangeKeyForValue(key: RouteParamtypes | string, data, { req, res, next }); +} diff --git a/src/core/router/route-params-factory.ts b/src/core/router/route-params-factory.ts index caf603f93fa..3f69ff1981f 100644 --- a/src/core/router/route-params-factory.ts +++ b/src/core/router/route-params-factory.ts @@ -2,17 +2,30 @@ import { RouteParamtypes } from '@nestjs/common/enums/route-paramtypes.enum'; import { IRouteParamsFactory } from './interfaces/route-params-factory.interface'; export class RouteParamsFactory implements IRouteParamsFactory { - public exchangeKeyForValue(key: RouteParamtypes | string, data, { req, res, next }) { - switch (key) { - case RouteParamtypes.NEXT: return next; - case RouteParamtypes.REQUEST: return req; - case RouteParamtypes.RESPONSE: return res; - case RouteParamtypes.BODY: return data && req.body ? req.body[data] : req.body; - case RouteParamtypes.PARAM: return data ? req.params[data] : req.params; - case RouteParamtypes.QUERY: return data ? req.query[data] : req.query; - case RouteParamtypes.HEADERS: return data ? req.headers[data] : req.headers; - case RouteParamtypes.SESSION: return req.session; - default: return null; - } + public exchangeKeyForValue( + key: RouteParamtypes | string, + data, + { req, res, next } + ) { + switch (key) { + case RouteParamtypes.NEXT: + return next; + case RouteParamtypes.REQUEST: + return req; + case RouteParamtypes.RESPONSE: + return res; + case RouteParamtypes.BODY: + return data && req.body ? req.body[data] : req.body; + case RouteParamtypes.PARAM: + return data ? req.params[data] : req.params; + case RouteParamtypes.QUERY: + return data ? req.query[data] : req.query; + case RouteParamtypes.HEADERS: + return data ? req.headers[data] : req.headers; + case RouteParamtypes.SESSION: + return req.session; + default: + return null; } -} \ No newline at end of file + } +} diff --git a/src/core/router/router-exception-filters.ts b/src/core/router/router-exception-filters.ts index 6779d906a13..10f0e0cc9ac 100644 --- a/src/core/router/router-exception-filters.ts +++ b/src/core/router/router-exception-filters.ts @@ -2,8 +2,15 @@ import 'reflect-metadata'; import iterate from 'iterare'; import { Controller } from '@nestjs/common/interfaces/controllers/controller.interface'; import { ExceptionsHandler } from '../exceptions/exceptions-handler'; -import { EXCEPTION_FILTERS_METADATA, FILTER_CATCH_EXCEPTIONS } from '@nestjs/common/constants'; -import { isEmpty, isFunction, isUndefined } from '@nestjs/common/utils/shared.utils'; +import { + EXCEPTION_FILTERS_METADATA, + FILTER_CATCH_EXCEPTIONS +} from '@nestjs/common/constants'; +import { + isEmpty, + isFunction, + isUndefined +} from '@nestjs/common/utils/shared.utils'; import { Metatype } from '@nestjs/common/interfaces/index'; import { ExceptionFilterMetadata } from '@nestjs/common/interfaces/exceptions/exception-filter-metadata.interface'; import { UnknownModuleException } from '../errors/exceptions/unknown-module.exception'; @@ -13,21 +20,28 @@ import { ApplicationConfig } from './../application-config'; import { BaseExceptionFilterContext } from '../exceptions/base-exception-filter-context'; export class RouterExceptionFilters extends BaseExceptionFilterContext { - constructor(private readonly config: ApplicationConfig) { - super(); - } + constructor(private readonly config: ApplicationConfig) { + super(); + } - public create(instance: Controller, callback: RouterProxyCallback): ExceptionsHandler { - const exceptionHandler = new ExceptionsHandler(); - const filters = this.createContext(instance, callback, EXCEPTION_FILTERS_METADATA); - if (isEmpty(filters)) { - return exceptionHandler; - } - exceptionHandler.setCustomFilters(filters); - return exceptionHandler; + public create( + instance: Controller, + callback: RouterProxyCallback + ): ExceptionsHandler { + const exceptionHandler = new ExceptionsHandler(); + const filters = this.createContext( + instance, + callback, + EXCEPTION_FILTERS_METADATA + ); + if (isEmpty(filters)) { + return exceptionHandler; } + exceptionHandler.setCustomFilters(filters); + return exceptionHandler; + } - public getGlobalMetadata(): T { - return this.config.getGlobalFilters() as T; - } -} \ No newline at end of file + public getGlobalMetadata(): T { + return this.config.getGlobalFilters() as T; + } +} diff --git a/src/core/router/router-execution-context.ts b/src/core/router/router-execution-context.ts index 3700a92d01b..ce1da135fe0 100644 --- a/src/core/router/router-execution-context.ts +++ b/src/core/router/router-execution-context.ts @@ -1,13 +1,28 @@ import 'reflect-metadata'; -import { ROUTE_ARGS_METADATA, PARAMTYPES_METADATA, HTTP_CODE_METADATA, CUSTOM_ROUTE_AGRS_METADATA } from '@nestjs/common/constants'; -import { isUndefined, isFunction, isString } from '@nestjs/common/utils/shared.utils'; +import { + ROUTE_ARGS_METADATA, + PARAMTYPES_METADATA, + HTTP_CODE_METADATA, + CUSTOM_ROUTE_AGRS_METADATA +} from '@nestjs/common/constants'; +import { + isUndefined, + isFunction, + isString +} from '@nestjs/common/utils/shared.utils'; import { RouteParamtypes } from '@nestjs/common/enums/route-paramtypes.enum'; import { Controller, Transform } from '@nestjs/common/interfaces'; import { RouteParamsMetadata } from '@nestjs/common/decorators'; import { IRouteParamsFactory } from './interfaces/route-params-factory.interface'; import { PipesContextCreator } from './../pipes/pipes-context-creator'; import { PipesConsumer } from './../pipes/pipes-consumer'; -import { ParamData, PipeTransform, HttpStatus, RequestMethod, HttpException } from '@nestjs/common'; +import { + ParamData, + PipeTransform, + HttpStatus, + RequestMethod, + HttpException +} from '@nestjs/common'; import { GuardsContextCreator } from '../guards/guards-context-creator'; import { GuardsConsumer } from '../guards/guards-consumer'; import { FORBIDDEN_MESSAGE } from '../guards/constants'; @@ -16,132 +31,188 @@ import { InterceptorsContextCreator } from '../interceptors/interceptors-context import { InterceptorsConsumer } from '../interceptors/interceptors-consumer'; export interface ParamProperties { - index: number; - type: RouteParamtypes | string; - data: ParamData; - pipes: PipeTransform[]; - extractValue: (req, res, next) => any; + index: number; + type: RouteParamtypes | string; + data: ParamData; + pipes: PipeTransform[]; + extractValue: (req, res, next) => any; } export class RouterExecutionContext { - private readonly responseController = new RouterResponseController(); - constructor( - private readonly paramsFactory: IRouteParamsFactory, - private readonly pipesContextCreator: PipesContextCreator, - private readonly pipesConsumer: PipesConsumer, - private readonly guardsContextCreator: GuardsContextCreator, - private readonly guardsConsumer: GuardsConsumer, - private readonly interceptorsContextCreator: InterceptorsContextCreator, - private readonly interceptorsConsumer: InterceptorsConsumer) {} - - public create(instance: Controller, callback: (...args) => any, methodName: string, module: string, requestMethod: RequestMethod) { - const metadata = this.reflectCallbackMetadata(instance, methodName) || {}; - const keys = Object.keys(metadata); - const argsLength = this.getArgumentsLength(keys, metadata); - const pipes = this.pipesContextCreator.create(instance, callback); - const paramtypes = this.reflectCallbackParamtypes(instance, methodName); - const guards = this.guardsContextCreator.create(instance, callback, module); - const interceptors = this.interceptorsContextCreator.create(instance, callback, module); - const httpCode = this.reflectHttpStatusCode(callback); - const paramsMetadata = this.exchangeKeysForValues(keys, metadata); - const isResponseHandled = paramsMetadata.some(({ type }) => type === RouteParamtypes.RESPONSE || type === RouteParamtypes.NEXT); - const paramsOptions = this.mergeParamsMetatypes(paramsMetadata, paramtypes); - - return async (req, res, next) => { - const args = this.createNullArray(argsLength); - const canActivate = await this.guardsConsumer.tryActivate(guards, req, instance, callback); - if (!canActivate) { - throw new HttpException(FORBIDDEN_MESSAGE, HttpStatus.FORBIDDEN); - } - - await Promise.all(paramsOptions.map(async (param) => { - const { index, extractValue, type, data, metatype, pipes: paramPipes } = param; - const value = extractValue(req, res, next); - - args[index] = await this.getParamValue( - value, { metatype, type, data }, - pipes.concat(this.pipesContextCreator.createConcreteContext(paramPipes)), - ); - })); - const handler = () => callback.apply(instance, args); - const result = await this.interceptorsConsumer.intercept( - interceptors, req, instance, callback, handler, - ); - return !isResponseHandled ? - this.responseController.apply(result, res, requestMethod, httpCode) : - undefined; - }; - } - - public mapParamType(key: string): string { - const keyPair = key.split(':'); - return keyPair[0]; - } - - public reflectCallbackMetadata(instance: Controller, methodName: string): RouteParamsMetadata { - return Reflect.getMetadata(ROUTE_ARGS_METADATA, instance, methodName); - } - - public reflectCallbackParamtypes(instance: Controller, methodName: string): any[] { - return Reflect.getMetadata(PARAMTYPES_METADATA, instance, methodName); - } - - public reflectHttpStatusCode(callback: (...args) => any): number { - return Reflect.getMetadata(HTTP_CODE_METADATA, callback); - } - - public getArgumentsLength(keys: string[], metadata: RouteParamsMetadata): number { - return Math.max(...keys.map(key => metadata[key].index)) + 1; - } - - public createNullArray(length: number): any[] { - return Array.apply(null, { length }).fill(null); - } - - public exchangeKeysForValues(keys: string[], metadata: RouteParamsMetadata): ParamProperties[] { - return keys.map(key => { - const { index, data, pipes } = metadata[key]; - const type = this.mapParamType(key); - - if (key.includes(CUSTOM_ROUTE_AGRS_METADATA)) { - const { factory } = metadata[key]; - const customExtractValue = this.getCustomFactory(factory, data); - return { index, extractValue: customExtractValue, type, data, pipes }; - } - const nType = Number(type); - const extractValue = (req, res, next) => this.paramsFactory.exchangeKeyForValue(nType, data, { req, res, next }); - return { index, extractValue, type: nType, data, pipes }; - }); - } - - public getCustomFactory(factory: (...args) => void, data): (...args) => any { - return !isUndefined(factory) && isFunction(factory) - ? (req, res, next) => factory(data, req) - : () => null; - } + private readonly responseController = new RouterResponseController(); + constructor( + private readonly paramsFactory: IRouteParamsFactory, + private readonly pipesContextCreator: PipesContextCreator, + private readonly pipesConsumer: PipesConsumer, + private readonly guardsContextCreator: GuardsContextCreator, + private readonly guardsConsumer: GuardsConsumer, + private readonly interceptorsContextCreator: InterceptorsContextCreator, + private readonly interceptorsConsumer: InterceptorsConsumer + ) {} + + public create( + instance: Controller, + callback: (...args) => any, + methodName: string, + module: string, + requestMethod: RequestMethod + ) { + const metadata = this.reflectCallbackMetadata(instance, methodName) || {}; + const keys = Object.keys(metadata); + const argsLength = this.getArgumentsLength(keys, metadata); + const pipes = this.pipesContextCreator.create(instance, callback); + const paramtypes = this.reflectCallbackParamtypes(instance, methodName); + const guards = this.guardsContextCreator.create(instance, callback, module); + const interceptors = this.interceptorsContextCreator.create( + instance, + callback, + module + ); + const httpCode = this.reflectHttpStatusCode(callback); + const paramsMetadata = this.exchangeKeysForValues(keys, metadata); + const isResponseHandled = paramsMetadata.some( + ({ type }) => + type === RouteParamtypes.RESPONSE || type === RouteParamtypes.NEXT + ); + const paramsOptions = this.mergeParamsMetatypes(paramsMetadata, paramtypes); + + return async (req, res, next) => { + const args = this.createNullArray(argsLength); + const canActivate = await this.guardsConsumer.tryActivate( + guards, + req, + instance, + callback + ); + if (!canActivate) { + throw new HttpException(FORBIDDEN_MESSAGE, HttpStatus.FORBIDDEN); + } - public mergeParamsMetatypes( - paramsProperties: ParamProperties[], - paramtypes: any[], - ): (ParamProperties & { metatype?: any })[] { - if (!paramtypes) { - return paramsProperties; + await Promise.all( + paramsOptions.map(async param => { + const { + index, + extractValue, + type, + data, + metatype, + pipes: paramPipes + } = param; + const value = extractValue(req, res, next); + + args[index] = await this.getParamValue( + value, + { metatype, type, data }, + pipes.concat( + this.pipesContextCreator.createConcreteContext(paramPipes) + ) + ); + }) + ); + const handler = () => callback.apply(instance, args); + const result = await this.interceptorsConsumer.intercept( + interceptors, + req, + instance, + callback, + handler + ); + return !isResponseHandled + ? this.responseController.apply(result, res, requestMethod, httpCode) + : undefined; + }; + } + + public mapParamType(key: string): string { + const keyPair = key.split(':'); + return keyPair[0]; + } + + public reflectCallbackMetadata( + instance: Controller, + methodName: string + ): RouteParamsMetadata { + return Reflect.getMetadata(ROUTE_ARGS_METADATA, instance, methodName); + } + + public reflectCallbackParamtypes( + instance: Controller, + methodName: string + ): any[] { + return Reflect.getMetadata(PARAMTYPES_METADATA, instance, methodName); + } + + public reflectHttpStatusCode(callback: (...args) => any): number { + return Reflect.getMetadata(HTTP_CODE_METADATA, callback); + } + + public getArgumentsLength( + keys: string[], + metadata: RouteParamsMetadata + ): number { + return Math.max(...keys.map(key => metadata[key].index)) + 1; + } + + public createNullArray(length: number): any[] { + return Array.apply(null, { length }).fill(null); + } + + public exchangeKeysForValues( + keys: string[], + metadata: RouteParamsMetadata + ): ParamProperties[] { + return keys.map(key => { + const { index, data, pipes } = metadata[key]; + const type = this.mapParamType(key); + + if (key.includes(CUSTOM_ROUTE_AGRS_METADATA)) { + const { factory } = metadata[key]; + const customExtractValue = this.getCustomFactory(factory, data); + return { index, extractValue: customExtractValue, type, data, pipes }; } - return paramsProperties.map((param) => ({ ...param, metatype: paramtypes[param.index] })); + const nType = Number(type); + const extractValue = (req, res, next) => + this.paramsFactory.exchangeKeyForValue(nType, data, { req, res, next }); + return { index, extractValue, type: nType, data, pipes }; + }); + } + + public getCustomFactory(factory: (...args) => void, data): (...args) => any { + return !isUndefined(factory) && isFunction(factory) + ? (req, res, next) => factory(data, req) + : () => null; + } + + public mergeParamsMetatypes( + paramsProperties: ParamProperties[], + paramtypes: any[] + ): (ParamProperties & { metatype?: any })[] { + if (!paramtypes) { + return paramsProperties; } - - public async getParamValue( - value: T, + return paramsProperties.map(param => ({ + ...param, + metatype: paramtypes[param.index] + })); + } + + public async getParamValue( + value: T, + { metatype, type, data }, + transforms: Transform[] + ): Promise { + if ( + type === RouteParamtypes.BODY || + type === RouteParamtypes.QUERY || + type === RouteParamtypes.PARAM || + isString(type) + ) { + return await this.pipesConsumer.apply( + value, { metatype, type, data }, - transforms: Transform[]): Promise { - - if (type === RouteParamtypes.BODY - || type === RouteParamtypes.QUERY - || type === RouteParamtypes.PARAM - || isString(type)) { - - return await this.pipesConsumer.apply(value, { metatype, type, data }, transforms); - } - return Promise.resolve(value); + transforms + ); } -} \ No newline at end of file + return Promise.resolve(value); + } +} diff --git a/src/core/router/router-explorer.ts b/src/core/router/router-explorer.ts index 4cba4ec87fc..9f10970aee7 100644 --- a/src/core/router/router-explorer.ts +++ b/src/core/router/router-explorer.ts @@ -25,111 +25,145 @@ import { InterceptorsContextCreator } from '../interceptors/interceptors-context import { InterceptorsConsumer } from '../interceptors/interceptors-consumer'; export class ExpressRouterExplorer implements RouterExplorer { - private readonly executionContextCreator: RouterExecutionContext; - private readonly routerMethodFactory = new RouterMethodFactory(); - private readonly logger = new Logger('RouterExplorer', true); - - constructor( - private readonly metadataScanner?: MetadataScanner, - private readonly routerProxy?: RouterProxy, - private readonly expressAdapter?: ExpressAdapter, - private readonly exceptionsFilter?: ExceptionsFilter, - private readonly config?: ApplicationConfig, - container?: NestContainer) { - - this.executionContextCreator = new RouterExecutionContext( - new RouteParamsFactory(), - new PipesContextCreator(config), - new PipesConsumer(), - new GuardsContextCreator(container, config), - new GuardsConsumer(), - new InterceptorsContextCreator(container, config), - new InterceptorsConsumer(), - ); - } - - public explore(instance: Controller, metatype: Metatype, module: string) { - const router = (this.expressAdapter as any).createRouter(); - const routerPaths = this.scanForPaths(instance); - - this.applyPathsToRouterProxy(router, routerPaths, instance, module); - return router; - } - - public fetchRouterPath(metatype: Metatype): string { - const path = Reflect.getMetadata(PATH_METADATA, metatype); - return this.validateRoutePath(path); - } - - public validateRoutePath(path: string): string { - if (isUndefined(path)) { - throw new UnknownRequestMappingException(); - } - return validatePath(path); + private readonly executionContextCreator: RouterExecutionContext; + private readonly routerMethodFactory = new RouterMethodFactory(); + private readonly logger = new Logger('RouterExplorer', true); + + constructor( + private readonly metadataScanner?: MetadataScanner, + private readonly routerProxy?: RouterProxy, + private readonly expressAdapter?: ExpressAdapter, + private readonly exceptionsFilter?: ExceptionsFilter, + private readonly config?: ApplicationConfig, + container?: NestContainer + ) { + this.executionContextCreator = new RouterExecutionContext( + new RouteParamsFactory(), + new PipesContextCreator(config), + new PipesConsumer(), + new GuardsContextCreator(container, config), + new GuardsConsumer(), + new InterceptorsContextCreator(container, config), + new InterceptorsConsumer() + ); + } + + public explore( + instance: Controller, + metatype: Metatype, + module: string + ) { + const router = (this.expressAdapter as any).createRouter(); + const routerPaths = this.scanForPaths(instance); + + this.applyPathsToRouterProxy(router, routerPaths, instance, module); + return router; + } + + public fetchRouterPath(metatype: Metatype): string { + const path = Reflect.getMetadata(PATH_METADATA, metatype); + return this.validateRoutePath(path); + } + + public validateRoutePath(path: string): string { + if (isUndefined(path)) { + throw new UnknownRequestMappingException(); } - - public scanForPaths(instance: Controller, prototype?): RoutePathProperties[] { - const instancePrototype = isUndefined(prototype) ? Object.getPrototypeOf(instance) : prototype; - return this.metadataScanner.scanFromPrototype( - instance, - instancePrototype, - (method) => this.exploreMethodMetadata(instance, instancePrototype, method), - ); + return validatePath(path); + } + + public scanForPaths(instance: Controller, prototype?): RoutePathProperties[] { + const instancePrototype = isUndefined(prototype) + ? Object.getPrototypeOf(instance) + : prototype; + return this.metadataScanner.scanFromPrototype< + Controller, + RoutePathProperties + >(instance, instancePrototype, method => + this.exploreMethodMetadata(instance, instancePrototype, method) + ); + } + + public exploreMethodMetadata( + instance: Controller, + instancePrototype, + methodName: string + ): RoutePathProperties { + const targetCallback = instancePrototype[methodName]; + const routePath = Reflect.getMetadata(PATH_METADATA, targetCallback); + if (isUndefined(routePath)) { + return null; } - public exploreMethodMetadata(instance: Controller, instancePrototype, methodName: string): RoutePathProperties { - const targetCallback = instancePrototype[methodName]; - const routePath = Reflect.getMetadata(PATH_METADATA, targetCallback); - if (isUndefined(routePath)) { - return null; - } - - const requestMethod: RequestMethod = Reflect.getMetadata(METHOD_METADATA, targetCallback); - return { - path: this.validateRoutePath(routePath), - requestMethod, - targetCallback, - methodName, - }; - } - - public applyPathsToRouterProxy( - router, - routePaths: RoutePathProperties[], - instance: Controller, - module: string) { - - (routePaths || []).map((pathProperties) => { - const { path, requestMethod } = pathProperties; - this.applyCallbackToRouter(router, pathProperties, instance, module); - this.logger.log(RouteMappedMessage(path, requestMethod)); - }); - } - - private applyCallbackToRouter( - router, - pathProperties: RoutePathProperties, - instance: Controller, - module: string) { - - const { path, requestMethod, targetCallback, methodName } = pathProperties; - - const routerMethod = this.routerMethodFactory.get(router, requestMethod).bind(router); - const proxy = this.createCallbackProxy(instance, targetCallback, methodName, module, requestMethod); - routerMethod(path, proxy); - } - - private createCallbackProxy(instance: Controller, callback: RouterProxyCallback, methodName: string, module: string, requestMethod) { - const executionContext = this.executionContextCreator.create(instance, callback, methodName, module, requestMethod); - const exceptionFilter = this.exceptionsFilter.create(instance, callback); - - return this.routerProxy.createProxy(executionContext, exceptionFilter); - } + const requestMethod: RequestMethod = Reflect.getMetadata( + METHOD_METADATA, + targetCallback + ); + return { + path: this.validateRoutePath(routePath), + requestMethod, + targetCallback, + methodName + }; + } + + public applyPathsToRouterProxy( + router, + routePaths: RoutePathProperties[], + instance: Controller, + module: string + ) { + (routePaths || []).map(pathProperties => { + const { path, requestMethod } = pathProperties; + this.applyCallbackToRouter(router, pathProperties, instance, module); + this.logger.log(RouteMappedMessage(path, requestMethod)); + }); + } + + private applyCallbackToRouter( + router, + pathProperties: RoutePathProperties, + instance: Controller, + module: string + ) { + const { path, requestMethod, targetCallback, methodName } = pathProperties; + + const routerMethod = this.routerMethodFactory + .get(router, requestMethod) + .bind(router); + const proxy = this.createCallbackProxy( + instance, + targetCallback, + methodName, + module, + requestMethod + ); + routerMethod(path, proxy); + } + + private createCallbackProxy( + instance: Controller, + callback: RouterProxyCallback, + methodName: string, + module: string, + requestMethod + ) { + const executionContext = this.executionContextCreator.create( + instance, + callback, + methodName, + module, + requestMethod + ); + const exceptionFilter = this.exceptionsFilter.create(instance, callback); + + return this.routerProxy.createProxy(executionContext, exceptionFilter); + } } export interface RoutePathProperties { - path: string; - requestMethod: RequestMethod; - targetCallback: RouterProxyCallback; - methodName: string; -} \ No newline at end of file + path: string; + requestMethod: RequestMethod; + targetCallback: RouterProxyCallback; + methodName: string; +} diff --git a/src/core/router/router-proxy.ts b/src/core/router/router-proxy.ts index 3c63f226718..d06fe13ca16 100644 --- a/src/core/router/router-proxy.ts +++ b/src/core/router/router-proxy.ts @@ -3,37 +3,33 @@ import { ExceptionsHandler } from '../exceptions/exceptions-handler'; export type RouterProxyCallback = (req?, res?, next?) => void; export class RouterProxy { - public createProxy( - targetCallback: RouterProxyCallback, - exceptionsHandler: ExceptionsHandler) { + public createProxy( + targetCallback: RouterProxyCallback, + exceptionsHandler: ExceptionsHandler + ) { + return (req, res, next) => { + try { + Promise.resolve(targetCallback(req, res, next)).catch(e => { + exceptionsHandler.next(e, res); + }); + } catch (e) { + exceptionsHandler.next(e, res); + } + }; + } - return (req, res, next) => { - try { - Promise.resolve(targetCallback(req, res, next)) - .catch((e) => { - exceptionsHandler.next(e, res); - }); - } - catch (e) { - exceptionsHandler.next(e, res); - } - }; - } - - public createExceptionLayerProxy( - targetCallback: (err, req, res, next) => void, - exceptionsHandler: ExceptionsHandler) { - - return (err, req, res, next) => { - try { - Promise.resolve(targetCallback(err, req, res, next)) - .catch((e) => { - exceptionsHandler.next(e, res); - }); - } - catch (e) { - exceptionsHandler.next(e, res); - } - }; - } + public createExceptionLayerProxy( + targetCallback: (err, req, res, next) => void, + exceptionsHandler: ExceptionsHandler + ) { + return (err, req, res, next) => { + try { + Promise.resolve(targetCallback(err, req, res, next)).catch(e => { + exceptionsHandler.next(e, res); + }); + } catch (e) { + exceptionsHandler.next(e, res); + } + }; + } } diff --git a/src/core/router/router-response-controller.ts b/src/core/router/router-response-controller.ts index d7c9a162c3d..d78cfe3dc85 100644 --- a/src/core/router/router-response-controller.ts +++ b/src/core/router/router-response-controller.ts @@ -3,9 +3,16 @@ import { isNil, isObject, isFunction } from '@nestjs/common/utils/shared.utils'; import 'rxjs/add/operator/toPromise'; export class RouterResponseController { - public async apply(resultOrDeffered, response, requestMethod: RequestMethod, httpCode: number) { + public async apply( + resultOrDeffered, + response, + requestMethod: RequestMethod, + httpCode: number + ) { const result = await this.transformToResult(resultOrDeffered); - const statusCode = httpCode ? httpCode : this.getStatusByMethod(requestMethod); + const statusCode = httpCode + ? httpCode + : this.getStatusByMethod(requestMethod); const res = response.status(statusCode); if (isNil(result)) { return res.send(); @@ -16,8 +23,7 @@ export class RouterResponseController { public async transformToResult(resultOrDeffered) { if (resultOrDeffered instanceof Promise) { return await resultOrDeffered; - } - else if (resultOrDeffered && isFunction(resultOrDeffered.subscribe)) { + } else if (resultOrDeffered && isFunction(resultOrDeffered.subscribe)) { return await resultOrDeffered.toPromise(); } return resultOrDeffered; @@ -25,8 +31,10 @@ export class RouterResponseController { public getStatusByMethod(requestMethod: RequestMethod): number { switch (requestMethod) { - case RequestMethod.POST: return HttpStatus.CREATED; - default: return HttpStatus.OK; + case RequestMethod.POST: + return HttpStatus.CREATED; + default: + return HttpStatus.OK; } } -} \ No newline at end of file +} diff --git a/src/core/router/routes-resolver.ts b/src/core/router/routes-resolver.ts index f7fd633545e..ac4c139b5fd 100644 --- a/src/core/router/routes-resolver.ts +++ b/src/core/router/routes-resolver.ts @@ -13,62 +13,77 @@ import { ApplicationConfig } from './../application-config'; import { NotFoundException } from '@nestjs/common'; export class RoutesResolver implements Resolver { - private readonly logger = new Logger(RoutesResolver.name, true); - private readonly routerProxy = new RouterProxy(); - private readonly routerExceptionsFilter: RouterExceptionFilters; - private readonly routerBuilder: RouterExplorer; + private readonly logger = new Logger(RoutesResolver.name, true); + private readonly routerProxy = new RouterProxy(); + private readonly routerExceptionsFilter: RouterExceptionFilters; + private readonly routerBuilder: RouterExplorer; - constructor( - private readonly container: NestContainer, - private readonly expressAdapter, - private readonly config: ApplicationConfig) { + constructor( + private readonly container: NestContainer, + private readonly expressAdapter, + private readonly config: ApplicationConfig + ) { + this.routerExceptionsFilter = new RouterExceptionFilters(config); + this.routerBuilder = new ExpressRouterExplorer( + new MetadataScanner(), + this.routerProxy, + expressAdapter, + this.routerExceptionsFilter, + config, + this.container + ); + } - this.routerExceptionsFilter = new RouterExceptionFilters(config); - this.routerBuilder = new ExpressRouterExplorer( - new MetadataScanner(), this.routerProxy, expressAdapter, - this.routerExceptionsFilter, config, this.container, - ); - } + public resolve(express: Application) { + const modules = this.container.getModules(); + modules.forEach(({ routes }, moduleName) => + this.setupRouters(routes, moduleName, express) + ); - public resolve(express: Application) { - const modules = this.container.getModules(); - modules.forEach(({ routes }, moduleName) => this.setupRouters(routes, moduleName, express)); + this.setupNotFoundHandler(express); + this.setupExceptionHandler(express); + } - this.setupNotFoundHandler(express); - this.setupExceptionHandler(express); - } + public setupRouters( + routes: Map>, + moduleName: string, + express: Application + ) { + routes.forEach(({ instance, metatype }) => { + const path = this.routerBuilder.fetchRouterPath(metatype); + const controllerName = metatype.name; - public setupRouters( - routes: Map>, - moduleName: string, - express: Application) { + this.logger.log(ControllerMappingMessage(controllerName, path)); - routes.forEach(({ instance, metatype }) => { - const path = this.routerBuilder.fetchRouterPath(metatype); - const controllerName = metatype.name; + const router = this.routerBuilder.explore(instance, metatype, moduleName); + express.use(path, router); + }); + } - this.logger.log(ControllerMappingMessage(controllerName, path)); + public setupNotFoundHandler(express: Application) { + const callback = (req, res) => { + throw new NotFoundException(`Cannot ${req.method} ${req.url}`); + }; + const exceptionHandler = this.routerExceptionsFilter.create( + {}, + callback as any + ); + const proxy = this.routerProxy.createProxy(callback, exceptionHandler); + express.use(proxy); + } - const router = this.routerBuilder.explore(instance, metatype, moduleName); - express.use(path, router); - }); - } - - public setupNotFoundHandler(express: Application) { - const callback = (req, res) => { - throw new NotFoundException(`Cannot ${req.method} ${req.url}`); - }; - const exceptionHandler = this.routerExceptionsFilter.create({}, callback as any); - const proxy = this.routerProxy.createProxy(callback, exceptionHandler); - express.use(proxy); - } - - public setupExceptionHandler(express: Application) { - const callback = (err, req, res, next) => { - throw err; - }; - const exceptionHandler = this.routerExceptionsFilter.create({}, callback as any); - const proxy = this.routerProxy.createExceptionLayerProxy(callback, exceptionHandler); - express.use(proxy); - } -} \ No newline at end of file + public setupExceptionHandler(express: Application) { + const callback = (err, req, res, next) => { + throw err; + }; + const exceptionHandler = this.routerExceptionsFilter.create( + {}, + callback as any + ); + const proxy = this.routerProxy.createExceptionLayerProxy( + callback, + exceptionHandler + ); + express.use(proxy); + } +} diff --git a/src/core/scanner.ts b/src/core/scanner.ts index fd2c77615c2..c3726e72e71 100644 --- a/src/core/scanner.ts +++ b/src/core/scanner.ts @@ -2,152 +2,211 @@ import 'reflect-metadata'; import { NestContainer } from './injector/container'; import { Controller } from '@nestjs/common/interfaces/controllers/controller.interface'; import { Injectable } from '@nestjs/common/interfaces/injectable.interface'; -import { metadata, GATEWAY_MIDDLEWARES, EXCEPTION_FILTERS_METADATA, GUARDS_METADATA, INTERCEPTORS_METADATA } from '@nestjs/common/constants'; +import { + metadata, + GATEWAY_MIDDLEWARES, + EXCEPTION_FILTERS_METADATA, + GUARDS_METADATA, + INTERCEPTORS_METADATA +} from '@nestjs/common/constants'; import { NestModuleMetatype } from '@nestjs/common/interfaces/modules/module-metatype.interface'; import { Metatype } from '@nestjs/common/interfaces/metatype.interface'; import { MetadataScanner } from '../core/metadata-scanner'; import { DynamicModule } from '@nestjs/common'; export class DependenciesScanner { - constructor( - private readonly container: NestContainer, - private readonly metadataScanner: MetadataScanner) {} - - public scan(module: NestModuleMetatype) { - this.scanForModules(module); - this.scanModulesForDependencies(); - this.container.bindGlobalScope(); - } - - public scanForModules(module: NestModuleMetatype | DynamicModule, scope: NestModuleMetatype[] = []) { - this.storeModule(module, scope); - - const importedModules = this.reflectMetadata(module, metadata.MODULES); - importedModules.map((innerModule) => { - this.scanForModules(innerModule, [].concat(scope, module)); - }); - } - - public storeModule(module: any, scope: NestModuleMetatype[]) { - if (module && module.forwardRef) { - return this.container.addModule(module.forwardRef(), scope); - } - this.container.addModule(module, scope); - } - - public scanModulesForDependencies() { - const modules = this.container.getModules(); - - modules.forEach(({ metatype }, token) => { - this.reflectRelatedModules(metatype, token); - this.reflectComponents(metatype, token); - this.reflectControllers(metatype, token); - this.reflectExports(metatype, token); - }); - } - - public reflectRelatedModules(module: NestModuleMetatype, token: string) { - const modules = [ - ...this.reflectMetadata(module, metadata.MODULES), - ...this.container.getDynamicMetadataByToken(token, metadata.MODULES as 'modules'), - ]; - modules.map((related) => this.storeRelatedModule(related, token)); - } - - public reflectComponents(module: NestModuleMetatype, token: string) { - const components = [ - ...this.reflectMetadata(module, metadata.COMPONENTS), - ...this.container.getDynamicMetadataByToken(token, metadata.COMPONENTS as 'components'), - ]; - components.map((component) => { - this.storeComponent(component, token); - this.reflectComponentMetadata(component, token); - this.reflectDynamicMetadata(component, token); - }); - } - - public reflectComponentMetadata(component: Metatype, token: string) { - this.reflectGatewaysMiddlewares(component, token); - } - - public reflectControllers(module: NestModuleMetatype, token: string) { - const routes = [ - ...this.reflectMetadata(module, metadata.CONTROLLERS), - ...this.container.getDynamicMetadataByToken(token, metadata.CONTROLLERS as 'controllers'), - ]; - routes.map((route) => { - this.storeRoute(route, token); - this.reflectDynamicMetadata(route, token); - }); - } - - public reflectDynamicMetadata(obj: Metatype, token: string) { - if (!obj.prototype) { return; } - - this.reflectGuards(obj, token); - this.reflectInterceptors(obj, token); - } - - public reflectExports(module: NestModuleMetatype, token: string) { - const exports = [ - ...this.reflectMetadata(module, metadata.EXPORTS), - ...this.container.getDynamicMetadataByToken(token, metadata.EXPORTS as 'exports'), - ]; - exports.map((exportedComponent) => this.storeExportedComponent(exportedComponent, token)); - } - - public reflectGatewaysMiddlewares(component: Metatype, token: string) { - const middlewares = this.reflectMetadata(component, GATEWAY_MIDDLEWARES); - middlewares.map((middleware) => this.storeComponent(middleware, token)); - } - - public reflectGuards(component: Metatype, token: string) { - const controllerGuards = this.reflectMetadata(component, GUARDS_METADATA); - const methodsGuards = this.metadataScanner.scanFromPrototype( - null, component.prototype, this.reflectKeyMetadata.bind(this, component, GUARDS_METADATA), - ); - const flattenMethodsGuards = methodsGuards.reduce((a: any[], b) => a.concat(b), []); - [...controllerGuards, ...flattenMethodsGuards].map((guard) => this.storeInjectable(guard, token)); - } - - public reflectInterceptors(component: Metatype, token: string) { - const controllerInterceptors = this.reflectMetadata(component, INTERCEPTORS_METADATA); - const methodsInterceptors = this.metadataScanner.scanFromPrototype( - null, component.prototype, this.reflectKeyMetadata.bind(this, component, INTERCEPTORS_METADATA), - ); - const flattenMethodsInterceptors = methodsInterceptors.reduce((a: any[], b) => a.concat(b), []); - [...controllerInterceptors, ...flattenMethodsInterceptors].map((guard) => this.storeInjectable(guard, token)); - } - - public reflectKeyMetadata(component: Metatype, key: string, method: string) { - const descriptor = Reflect.getOwnPropertyDescriptor(component.prototype, method); - return descriptor ? Reflect.getMetadata(key, descriptor.value) : undefined; - } - - public storeRelatedModule(related: any, token: string) { - if (related.forwardRef) { - return this.container.addRelatedModule(related.forwardRef(), token); - } - this.container.addRelatedModule(related, token); - } - - public storeComponent(component: Metatype, token: string) { - this.container.addComponent(component, token); - } - - public storeInjectable(component: Metatype, token: string) { - this.container.addInjectable(component, token); - } - - public storeExportedComponent(exportedComponent: Metatype, token: string) { - this.container.addExportedComponent(exportedComponent, token); - } - - public storeRoute(route: Metatype, token: string) { - this.container.addController(route, token); - } - - public reflectMetadata(metatype, metadata: string) { - return Reflect.getMetadata(metadata, metatype) || []; - } -} \ No newline at end of file + constructor( + private readonly container: NestContainer, + private readonly metadataScanner: MetadataScanner + ) {} + + public scan(module: NestModuleMetatype) { + this.scanForModules(module); + this.scanModulesForDependencies(); + this.container.bindGlobalScope(); + } + + public scanForModules( + module: NestModuleMetatype | DynamicModule, + scope: NestModuleMetatype[] = [] + ) { + this.storeModule(module, scope); + + const importedModules = this.reflectMetadata(module, metadata.MODULES); + importedModules.map(innerModule => { + this.scanForModules(innerModule, [].concat(scope, module)); + }); + } + + public storeModule(module: any, scope: NestModuleMetatype[]) { + if (module && module.forwardRef) { + return this.container.addModule(module.forwardRef(), scope); + } + this.container.addModule(module, scope); + } + + public scanModulesForDependencies() { + const modules = this.container.getModules(); + + modules.forEach(({ metatype }, token) => { + this.reflectRelatedModules(metatype, token); + this.reflectComponents(metatype, token); + this.reflectControllers(metatype, token); + this.reflectExports(metatype, token); + }); + } + + public reflectRelatedModules(module: NestModuleMetatype, token: string) { + const modules = [ + ...this.reflectMetadata(module, metadata.MODULES), + ...this.container.getDynamicMetadataByToken( + token, + metadata.MODULES as 'modules' + ) + ]; + modules.map(related => this.storeRelatedModule(related, token)); + } + + public reflectComponents(module: NestModuleMetatype, token: string) { + const components = [ + ...this.reflectMetadata(module, metadata.COMPONENTS), + ...this.container.getDynamicMetadataByToken( + token, + metadata.COMPONENTS as 'components' + ) + ]; + components.map(component => { + this.storeComponent(component, token); + this.reflectComponentMetadata(component, token); + this.reflectDynamicMetadata(component, token); + }); + } + + public reflectComponentMetadata( + component: Metatype, + token: string + ) { + this.reflectGatewaysMiddlewares(component, token); + } + + public reflectControllers(module: NestModuleMetatype, token: string) { + const routes = [ + ...this.reflectMetadata(module, metadata.CONTROLLERS), + ...this.container.getDynamicMetadataByToken( + token, + metadata.CONTROLLERS as 'controllers' + ) + ]; + routes.map(route => { + this.storeRoute(route, token); + this.reflectDynamicMetadata(route, token); + }); + } + + public reflectDynamicMetadata(obj: Metatype, token: string) { + if (!obj.prototype) { + return; + } + + this.reflectGuards(obj, token); + this.reflectInterceptors(obj, token); + } + + public reflectExports(module: NestModuleMetatype, token: string) { + const exports = [ + ...this.reflectMetadata(module, metadata.EXPORTS), + ...this.container.getDynamicMetadataByToken( + token, + metadata.EXPORTS as 'exports' + ) + ]; + exports.map(exportedComponent => + this.storeExportedComponent(exportedComponent, token) + ); + } + + public reflectGatewaysMiddlewares( + component: Metatype, + token: string + ) { + const middlewares = this.reflectMetadata(component, GATEWAY_MIDDLEWARES); + middlewares.map(middleware => this.storeComponent(middleware, token)); + } + + public reflectGuards(component: Metatype, token: string) { + const controllerGuards = this.reflectMetadata(component, GUARDS_METADATA); + const methodsGuards = this.metadataScanner.scanFromPrototype( + null, + component.prototype, + this.reflectKeyMetadata.bind(this, component, GUARDS_METADATA) + ); + const flattenMethodsGuards = methodsGuards.reduce( + (a: any[], b) => a.concat(b), + [] + ); + [...controllerGuards, ...flattenMethodsGuards].map(guard => + this.storeInjectable(guard, token) + ); + } + + public reflectInterceptors(component: Metatype, token: string) { + const controllerInterceptors = this.reflectMetadata( + component, + INTERCEPTORS_METADATA + ); + const methodsInterceptors = this.metadataScanner.scanFromPrototype( + null, + component.prototype, + this.reflectKeyMetadata.bind(this, component, INTERCEPTORS_METADATA) + ); + const flattenMethodsInterceptors = methodsInterceptors.reduce( + (a: any[], b) => a.concat(b), + [] + ); + [...controllerInterceptors, ...flattenMethodsInterceptors].map(guard => + this.storeInjectable(guard, token) + ); + } + + public reflectKeyMetadata( + component: Metatype, + key: string, + method: string + ) { + const descriptor = Reflect.getOwnPropertyDescriptor( + component.prototype, + method + ); + return descriptor ? Reflect.getMetadata(key, descriptor.value) : undefined; + } + + public storeRelatedModule(related: any, token: string) { + if (related.forwardRef) { + return this.container.addRelatedModule(related.forwardRef(), token); + } + this.container.addRelatedModule(related, token); + } + + public storeComponent(component: Metatype, token: string) { + this.container.addComponent(component, token); + } + + public storeInjectable(component: Metatype, token: string) { + this.container.addInjectable(component, token); + } + + public storeExportedComponent( + exportedComponent: Metatype, + token: string + ) { + this.container.addExportedComponent(exportedComponent, token); + } + + public storeRoute(route: Metatype, token: string) { + this.container.addController(route, token); + } + + public reflectMetadata(metatype, metadata: string) { + return Reflect.getMetadata(metadata, metatype) || []; + } +} diff --git a/src/core/services/reflector.service.ts b/src/core/services/reflector.service.ts index 032293b61da..cc80d80476f 100644 --- a/src/core/services/reflector.service.ts +++ b/src/core/services/reflector.service.ts @@ -2,4 +2,4 @@ export class Reflector { public get(metadataKey, target): T { return Reflect.getMetadata(metadataKey, target) as T; } -} \ No newline at end of file +} diff --git a/src/core/test/application-config.spec.ts b/src/core/test/application-config.spec.ts index 908ae3145eb..d42f15f660b 100644 --- a/src/core/test/application-config.spec.ts +++ b/src/core/test/application-config.spec.ts @@ -29,7 +29,7 @@ describe('ApplicationConfig', () => { describe('Pipes', () => { it('should set global pipes', () => { const pipes = ['test', 'test2']; - appConfig.useGlobalPipes(...pipes as any); + appConfig.useGlobalPipes(...(pipes as any)); expect(appConfig.getGlobalPipes()).to.be.eql(pipes); }); @@ -37,7 +37,7 @@ describe('ApplicationConfig', () => { describe('Filters', () => { it('should set global filters', () => { const filters = ['test', 'test2']; - appConfig.useGlobalFilters(...filters as any); + appConfig.useGlobalFilters(...(filters as any)); expect(appConfig.getGlobalFilters()).to.be.eql(filters); }); @@ -45,7 +45,7 @@ describe('ApplicationConfig', () => { describe('Guards', () => { it('should set global guards', () => { const guards = ['test', 'test2']; - appConfig.useGlobalGuards(...guards as any); + appConfig.useGlobalGuards(...(guards as any)); expect(appConfig.getGlobalGuards()).to.be.eql(guards); }); @@ -53,9 +53,9 @@ describe('ApplicationConfig', () => { describe('Interceptors', () => { it('should set global interceptors', () => { const interceptors = ['test', 'test2']; - appConfig.useGlobalInterceptors(...interceptors as any); + appConfig.useGlobalInterceptors(...(interceptors as any)); expect(appConfig.getGlobalInterceptors()).to.be.eql(interceptors); }); }); -}); \ No newline at end of file +}); diff --git a/src/core/test/errors/test/exception-handler.spec.ts b/src/core/test/errors/test/exception-handler.spec.ts index e08de2d355a..c593042f13c 100644 --- a/src/core/test/errors/test/exception-handler.spec.ts +++ b/src/core/test/errors/test/exception-handler.spec.ts @@ -5,29 +5,30 @@ import { RuntimeException } from '../../../errors/exceptions/runtime.exception'; import { InvalidMiddlewareException } from '../../../errors/exceptions/invalid-middleware.exception'; describe('ExceptionHandler', () => { - let instance: ExceptionHandler; + let instance: ExceptionHandler; + beforeEach(() => { + instance = new ExceptionHandler(); + }); + describe('handle', () => { + let logger; + let errorSpy: sinon.SinonSpy; beforeEach(() => { - instance = new ExceptionHandler(); + logger = { + error: () => {} + }; + (ExceptionHandler as any).logger = logger; + errorSpy = sinon.spy(logger, 'error'); }); - describe('handle', () => { - let logger; - let errorSpy: sinon.SinonSpy; - beforeEach(() => { - logger = { - error: () => {}, - }; - (ExceptionHandler as any).logger = logger; - errorSpy = sinon.spy(logger, 'error'); - }); - it('when exception is instanceof RuntimeException', () => { - const exception = new RuntimeException('msg'); - instance.handle(exception); - expect(errorSpy.calledWith(exception.message, exception.stack)).to.be.true; - }); - it('when exception is not instanceof RuntimeException', () => { - const exception = new InvalidMiddlewareException('msg'); - instance.handle(exception); - expect(errorSpy.calledWith(exception.what(), exception.stack)).to.be.true; - }); + it('when exception is instanceof RuntimeException', () => { + const exception = new RuntimeException('msg'); + instance.handle(exception); + expect(errorSpy.calledWith(exception.message, exception.stack)).to.be + .true; }); -}); \ No newline at end of file + it('when exception is not instanceof RuntimeException', () => { + const exception = new InvalidMiddlewareException('msg'); + instance.handle(exception); + expect(errorSpy.calledWith(exception.what(), exception.stack)).to.be.true; + }); + }); +}); diff --git a/src/core/test/errors/test/exceptions-zone.spec.ts b/src/core/test/errors/test/exceptions-zone.spec.ts index 71d26f0804b..9111a044d67 100644 --- a/src/core/test/errors/test/exceptions-zone.spec.ts +++ b/src/core/test/errors/test/exceptions-zone.spec.ts @@ -4,57 +4,60 @@ import { ExceptionsZone } from '../../../errors/exceptions-zone'; import { UNHANDLED_RUNTIME_EXCEPTION } from '../../../errors/messages'; describe('ExceptionsZone', () => { - describe('run', () => { - let callback: sinon.SinonSpy; - beforeEach(() => { - callback = sinon.spy(); - }); - it('should call callback', () => { - ExceptionsZone.run(callback as any); - expect(callback.called).to.be.true; - }); - describe('when callback throws exception', () => { - const exceptionHandler = { - handle: () => {}, - }; - let handleSpy: sinon.SinonSpy; - beforeEach(() => { - (ExceptionsZone as any).exceptionHandler = exceptionHandler; - handleSpy = sinon.spy(exceptionHandler, 'handle'); - }); - it('should call "handle" method of exceptionHandler and throws UNHANDLED_RUNTIME_EXCEPTION', () => { - const throwsCallback = () => { - throw 3; - }; - expect(() => ExceptionsZone.run(throwsCallback)).to.throws(UNHANDLED_RUNTIME_EXCEPTION); - expect(handleSpy.called).to.be.true; - }); - }); + describe('run', () => { + let callback: sinon.SinonSpy; + beforeEach(() => { + callback = sinon.spy(); }); - describe('asyncRun', () => { - let callback: sinon.SinonSpy; - beforeEach(() => { - callback = sinon.spy(); - }); - it('should call callback', async () => { - await ExceptionsZone.asyncRun(callback as any); - expect(callback.called).to.be.true; - }); - describe('when callback throws exception', () => { - const exceptionHandler = { - handle: () => {}, - }; - let handleSpy: sinon.SinonSpy; - beforeEach(() => { - (ExceptionsZone as any).exceptionHandler = exceptionHandler; - handleSpy = sinon.spy(exceptionHandler, 'handle'); - }); - it('should call "handle" method of exceptionHandler and throws UNHANDLED_RUNTIME_EXCEPTION', async () => { - const throwsCallback = () => { - throw 3; - }; - expect(ExceptionsZone.asyncRun(throwsCallback)).to.eventually.be.rejected; - }); - }); + it('should call callback', () => { + ExceptionsZone.run(callback as any); + expect(callback.called).to.be.true; }); -}); \ No newline at end of file + describe('when callback throws exception', () => { + const exceptionHandler = { + handle: () => {} + }; + let handleSpy: sinon.SinonSpy; + beforeEach(() => { + (ExceptionsZone as any).exceptionHandler = exceptionHandler; + handleSpy = sinon.spy(exceptionHandler, 'handle'); + }); + it('should call "handle" method of exceptionHandler and throws UNHANDLED_RUNTIME_EXCEPTION', () => { + const throwsCallback = () => { + throw 3; + }; + expect(() => ExceptionsZone.run(throwsCallback)).to.throws( + UNHANDLED_RUNTIME_EXCEPTION + ); + expect(handleSpy.called).to.be.true; + }); + }); + }); + describe('asyncRun', () => { + let callback: sinon.SinonSpy; + beforeEach(() => { + callback = sinon.spy(); + }); + it('should call callback', async () => { + await ExceptionsZone.asyncRun(callback as any); + expect(callback.called).to.be.true; + }); + describe('when callback throws exception', () => { + const exceptionHandler = { + handle: () => {} + }; + let handleSpy: sinon.SinonSpy; + beforeEach(() => { + (ExceptionsZone as any).exceptionHandler = exceptionHandler; + handleSpy = sinon.spy(exceptionHandler, 'handle'); + }); + it('should call "handle" method of exceptionHandler and throws UNHANDLED_RUNTIME_EXCEPTION', async () => { + const throwsCallback = () => { + throw 3; + }; + expect(ExceptionsZone.asyncRun(throwsCallback)).to.eventually.be + .rejected; + }); + }); + }); +}); diff --git a/src/core/test/exceptions/exceptions-handler.spec.ts b/src/core/test/exceptions/exceptions-handler.spec.ts index e1ab0f8ac00..92c8004b60c 100644 --- a/src/core/test/exceptions/exceptions-handler.spec.ts +++ b/src/core/test/exceptions/exceptions-handler.spec.ts @@ -7,120 +7,125 @@ import { NestEnvironment } from '../../../common/enums/nest-environment.enum'; import { InvalidExceptionFilterException } from '../../errors/exceptions/invalid-exception-filter.exception'; describe('ExceptionsHandler', () => { - let handler: ExceptionsHandler; - let statusStub: sinon.SinonStub; - let jsonStub: sinon.SinonStub; - let response; + let handler: ExceptionsHandler; + let statusStub: sinon.SinonStub; + let jsonStub: sinon.SinonStub; + let response; - before(() => Logger.setMode(NestEnvironment.TEST)); + before(() => Logger.setMode(NestEnvironment.TEST)); - beforeEach(() => { - handler = new ExceptionsHandler(); - statusStub = sinon.stub(); - jsonStub = sinon.stub(); + beforeEach(() => { + handler = new ExceptionsHandler(); + statusStub = sinon.stub(); + jsonStub = sinon.stub(); - response = { - status: statusStub, - json: jsonStub, - }; - response.status.returns(response); - response.json.returns(response); - }); + response = { + status: statusStub, + json: jsonStub + }; + response.status.returns(response); + response.json.returns(response); + }); - describe('next', () => { - it('should method send expected response status code and message when exception is unknown', () => { - handler.next(new Error(), response); + describe('next', () => { + it('should method send expected response status code and message when exception is unknown', () => { + handler.next(new Error(), response); - expect(statusStub.calledWith(500)).to.be.true; - expect(jsonStub.calledWith({ statusCode: 500, message: 'Internal server error' })).to.be.true; - }); - describe('when exception is instance of HttpException', () => { - it('should method send expected response status code and json object', () => { - const status = 401; - const message = { - custom: 'Unauthorized', - }; - handler.next(new HttpException(message, status), response); + expect(statusStub.calledWith(500)).to.be.true; + expect( + jsonStub.calledWith({ + statusCode: 500, + message: 'Internal server error' + }) + ).to.be.true; + }); + describe('when exception is instance of HttpException', () => { + it('should method send expected response status code and json object', () => { + const status = 401; + const message = { + custom: 'Unauthorized' + }; + handler.next(new HttpException(message, status), response); + + expect(statusStub.calledWith(status)).to.be.true; + expect(jsonStub.calledWith(message)).to.be.true; + }); + it('should method send expected response status code and transform message to json', () => { + const status = 401; + const message = 'Unauthorized'; - expect(statusStub.calledWith(status)).to.be.true; - expect(jsonStub.calledWith(message)).to.be.true; - }); - it('should method send expected response status code and transform message to json', () => { - const status = 401; - const message = 'Unauthorized'; + handler.next(new HttpException(message, status), response); - handler.next(new HttpException(message, status), response); + expect(statusStub.calledWith(status)).to.be.true; + expect(jsonStub.calledWith({ message, statusCode: status })).to.be.true; + }); + }); + describe('when "invokeCustomFilters" returns true', () => { + beforeEach(() => { + sinon.stub(handler, 'invokeCustomFilters').returns(true); + }); + it('should not call status and json stubs', () => { + expect(statusStub.notCalled).to.be.true; + expect(jsonStub.notCalled).to.be.true; + }); + }); + }); + describe('setCustomFilters', () => { + const filters = ['test', 'test2']; + it('should set custom filters', () => { + handler.setCustomFilters(filters as any); + expect((handler as any).filters).to.be.eql(filters); + }); + it('should throws exception when passed argument is not an array', () => { + expect(() => handler.setCustomFilters(null)).to.throws( + InvalidExceptionFilterException + ); + }); + }); + describe('invokeCustomFilters', () => { + describe('when filters array is empty', () => { + it('should returns false', () => { + expect(handler.invokeCustomFilters(null, null)).to.be.false; + }); + }); + describe('when filters array is not empty', () => { + let filters, funcSpy; + class TestException {} - expect(statusStub.calledWith(status)).to.be.true; - expect(jsonStub.calledWith({ message, statusCode: status })).to.be.true; - }); + beforeEach(() => { + funcSpy = sinon.spy(); + }); + describe('when filter exists in filters array', () => { + beforeEach(() => { + filters = [{ exceptionMetatypes: [TestException], func: funcSpy }]; + (handler as any).filters = filters; }); - describe('when "invokeCustomFilters" returns true', () => { - beforeEach(() => { - sinon.stub(handler, 'invokeCustomFilters').returns(true); - }); - it('should not call status and json stubs', () => { - expect(statusStub.notCalled).to.be.true; - expect(jsonStub.notCalled).to.be.true; - }); + it('should call funcSpy', () => { + handler.invokeCustomFilters(new TestException(), null); + expect(funcSpy.notCalled).to.be.false; }); - }); - describe('setCustomFilters', () => { - const filters = [ 'test', 'test2' ]; - it('should set custom filters', () => { - handler.setCustomFilters(filters as any); - expect((handler as any).filters).to.be.eql(filters); + it('should call funcSpy with exception and response passed as an arguments', () => { + const exception = new TestException(); + const res = { foo: 'bar' }; + + handler.invokeCustomFilters(exception, res); + expect(funcSpy.calledWith(exception, res)).to.be.true; }); - it('should throws exception when passed argument is not an array', () => { - expect( - () => handler.setCustomFilters(null), - ).to.throws(InvalidExceptionFilterException); + it('should returns true', () => { + expect(handler.invokeCustomFilters(new TestException(), null)).to.be + .true; }); - }); - describe('invokeCustomFilters', () => { - describe('when filters array is empty', () => { - it('should returns false', () => { - expect(handler.invokeCustomFilters(null, null)).to.be.false; - }); + }); + describe('when filter does not exists in filters array', () => { + it('should not call funcSpy', () => { + handler.invokeCustomFilters(new TestException(), null); + expect(funcSpy.notCalled).to.be.true; }); - describe('when filters array is not empty', () => { - let filters, funcSpy; - class TestException {} - - beforeEach(() => { - funcSpy = sinon.spy(); - }); - describe('when filter exists in filters array', () => { - beforeEach(() => { - filters = [ - { exceptionMetatypes: [ TestException ], func: funcSpy }, - ]; - (handler as any).filters = filters; - }); - it('should call funcSpy', () => { - handler.invokeCustomFilters(new TestException(), null); - expect(funcSpy.notCalled).to.be.false; - }); - it('should call funcSpy with exception and response passed as an arguments', () => { - const exception = new TestException(); - const res = { foo: 'bar' }; - - handler.invokeCustomFilters(exception, res); - expect(funcSpy.calledWith(exception, res)).to.be.true; - }); - it('should returns true', () => { - expect(handler.invokeCustomFilters(new TestException(), null)).to.be.true; - }); - }); - describe('when filter does not exists in filters array', () => { - it('should not call funcSpy', () => { - handler.invokeCustomFilters(new TestException(), null); - expect(funcSpy.notCalled).to.be.true; - }); - it('should returns false', () => { - expect(handler.invokeCustomFilters(new TestException(), null)).to.be.false; - }); - }); + it('should returns false', () => { + expect(handler.invokeCustomFilters(new TestException(), null)).to.be + .false; }); + }); }); -}); \ No newline at end of file + }); +}); diff --git a/src/core/test/guards/guards-consumer.spec.ts b/src/core/test/guards/guards-consumer.spec.ts index 5f732b49bb1..10421754e65 100644 --- a/src/core/test/guards/guards-consumer.spec.ts +++ b/src/core/test/guards/guards-consumer.spec.ts @@ -5,47 +5,61 @@ import { Observable } from 'rxjs/Observable'; import 'rxjs/add/observable/of'; describe('GuardsConsumer', () => { - let consumer: GuardsConsumer; - let guards: any[]; - beforeEach(() => { - consumer = new GuardsConsumer(); - guards = [{ canActivate: () => true }, { canActivate: () => true }]; + let consumer: GuardsConsumer; + let guards: any[]; + beforeEach(() => { + consumer = new GuardsConsumer(); + guards = [{ canActivate: () => true }, { canActivate: () => true }]; + }); + describe('tryActivate', () => { + describe('when guards array is empty', () => { + it('should return true', async () => { + const canActivate = await consumer.tryActivate( + [], + {}, + { constructor: null }, + null + ); + expect(canActivate).to.be.true; + }); }); - describe('tryActivate', () => { - describe('when guards array is empty', () => { - it('should return true', async () => { - const canActivate = await consumer.tryActivate([], {}, { constructor: null }, null); - expect(canActivate).to.be.true; - }); + describe('when guards array is not empty', () => { + describe('when at least on guard returns false', () => { + it('should return false', async () => { + const canActivate = await consumer.tryActivate( + [...guards, { canActivate: () => false }], + {}, + { constructor: null }, + null + ); + expect(canActivate).to.be.false; }); - describe('when guards array is not empty', () => { - describe('when at least on guard returns false', () => { - it('should return false', async () => { - const canActivate = await consumer.tryActivate([ - ...guards, - { canActivate: () => false }, - ], {}, { constructor: null }, null); - expect(canActivate).to.be.false; - }); - }); - describe('when each guard returns true', () => { - it('should return true', async () => { - const canActivate = await consumer.tryActivate(guards, {}, { constructor: null }, null); - expect(canActivate).to.be.true; - }); - }); + }); + describe('when each guard returns true', () => { + it('should return true', async () => { + const canActivate = await consumer.tryActivate( + guards, + {}, + { constructor: null }, + null + ); + expect(canActivate).to.be.true; }); + }); }); - describe('pickResult', () => { - describe('when result is Observable', () => { - it('should returns promise', () => { - expect(consumer.pickResult(Observable.of(true))).to.eventually.instanceOf(Promise); - }); - }); - describe('when result is Promise', () => { - it('should await promise', async () => { - expect(await consumer.pickResult(Promise.resolve(true))).to.be.true; - }); - }); + }); + describe('pickResult', () => { + describe('when result is Observable', () => { + it('should returns promise', () => { + expect( + consumer.pickResult(Observable.of(true)) + ).to.eventually.instanceOf(Promise); + }); + }); + describe('when result is Promise', () => { + it('should await promise', async () => { + expect(await consumer.pickResult(Promise.resolve(true))).to.be.true; + }); }); -}); \ No newline at end of file + }); +}); diff --git a/src/core/test/guards/guards-context-creator.spec.ts b/src/core/test/guards/guards-context-creator.spec.ts index c755ebac81f..32d0ce5e773 100644 --- a/src/core/test/guards/guards-context-creator.spec.ts +++ b/src/core/test/guards/guards-context-creator.spec.ts @@ -4,58 +4,55 @@ import { GuardsContextCreator } from '../../guards/guards-context-creator'; import { Observable } from 'rxjs/Observable'; describe('GuardsContextCreator', () => { - let guardsContextCreator: GuardsContextCreator; - let guards: any[]; - let container; - let getSpy; + let guardsContextCreator: GuardsContextCreator; + let guards: any[]; + let container; + let getSpy; - beforeEach(() => { - guards = [ - { - name: 'test', - instance: { - canActivate: () => true, - }, - }, - { - name: 'test2', - instance: { - canActivate: () => true, - }, - }, - {}, - undefined, - ]; - getSpy = sinon.stub().returns({ - injectables: new Map([ - ['test', guards[0]], - ['test2', guards[1]], - ]), - }); - container = { - getModules: () => ({ - get: getSpy, - }), - }; - guardsContextCreator = new GuardsContextCreator(container as any); + beforeEach(() => { + guards = [ + { + name: 'test', + instance: { + canActivate: () => true + } + }, + { + name: 'test2', + instance: { + canActivate: () => true + } + }, + {}, + undefined + ]; + getSpy = sinon.stub().returns({ + injectables: new Map([['test', guards[0]], ['test2', guards[1]]]) }); - describe('createConcreteContext', () => { - describe('when `moduleContext` is nil', () => { - it('should returns empty array', () => { - const result = guardsContextCreator.createConcreteContext(guards); - expect(result).to.be.empty; - }); - }); - describe('when `moduleContext` is defined', () => { - beforeEach(() => { - // tslint:disable-next-line:no-string-literal - guardsContextCreator['moduleContext'] = 'test'; - }); - it('should filter metatypes', () => { - expect( - guardsContextCreator.createConcreteContext(guards), - ).to.have.length(2); - }); - }); + container = { + getModules: () => ({ + get: getSpy + }) + }; + guardsContextCreator = new GuardsContextCreator(container as any); + }); + describe('createConcreteContext', () => { + describe('when `moduleContext` is nil', () => { + it('should returns empty array', () => { + const result = guardsContextCreator.createConcreteContext(guards); + expect(result).to.be.empty; + }); }); -}); \ No newline at end of file + describe('when `moduleContext` is defined', () => { + beforeEach(() => { + // tslint:disable-next-line:no-string-literal + guardsContextCreator['moduleContext'] = 'test'; + }); + it('should filter metatypes', () => { + expect( + guardsContextCreator.createConcreteContext(guards) + ).to.have.length(2); + }); + }); + }); +}); diff --git a/src/core/test/helpers/external-context-creator.spec.ts b/src/core/test/helpers/external-context-creator.spec.ts index 5b366bed10d..4165a0e9b9a 100644 --- a/src/core/test/helpers/external-context-creator.spec.ts +++ b/src/core/test/helpers/external-context-creator.spec.ts @@ -9,127 +9,127 @@ import { InterceptorsConsumer } from '../../interceptors/interceptors-consumer'; import { ExternalContextCreator } from '../../helpers/external-context-creator'; describe('ExternalContextCreator', () => { - let contextCreator: ExternalContextCreator; - let callback; - let applySpy: sinon.SinonSpy; - let bindSpy: sinon.SinonSpy; - let guardsConsumer: GuardsConsumer; + let contextCreator: ExternalContextCreator; + let callback; + let applySpy: sinon.SinonSpy; + let bindSpy: sinon.SinonSpy; + let guardsConsumer: GuardsConsumer; - beforeEach(() => { - callback = { - bind: () => ({}), - apply: () => ({}), - }; - bindSpy = sinon.spy(callback, 'bind'); - applySpy = sinon.spy(callback, 'apply'); + beforeEach(() => { + callback = { + bind: () => ({}), + apply: () => ({}) + }; + bindSpy = sinon.spy(callback, 'bind'); + applySpy = sinon.spy(callback, 'apply'); - guardsConsumer = new GuardsConsumer(); - contextCreator = new ExternalContextCreator( - new GuardsContextCreator(new NestContainer()), - guardsConsumer, - new InterceptorsContextCreator(new NestContainer()), - new InterceptorsConsumer(), - new ModulesContainer(), - ); - }); - describe('create', () => { - it('should call "findContextModuleName" with expected argument', done => { - const findContextModuleNameSpy = sinon.spy( - contextCreator, - 'findContextModuleName', - ); - contextCreator.create({ foo: 'bar' }, callback as any, ''); - expect(findContextModuleNameSpy.called).to.be.true; - done(); - }); - describe('returns proxy function', () => { - let proxyContext; - let instance; + guardsConsumer = new GuardsConsumer(); + contextCreator = new ExternalContextCreator( + new GuardsContextCreator(new NestContainer()), + guardsConsumer, + new InterceptorsContextCreator(new NestContainer()), + new InterceptorsConsumer(), + new ModulesContainer() + ); + }); + describe('create', () => { + it('should call "findContextModuleName" with expected argument', done => { + const findContextModuleNameSpy = sinon.spy( + contextCreator, + 'findContextModuleName' + ); + contextCreator.create({ foo: 'bar' }, callback as any, ''); + expect(findContextModuleNameSpy.called).to.be.true; + done(); + }); + describe('returns proxy function', () => { + let proxyContext; + let instance; - beforeEach(() => { - instance = { foo: 'bar' }; - proxyContext = contextCreator.create(instance, callback as any, ''); - }); - it('should be a function', () => { - expect(proxyContext).to.be.a('function'); - }); - describe('when proxy function called', () => { - describe('when can not activate', () => { - it('should throw exception when "tryActivate" returns false', () => { - sinon.stub(guardsConsumer, 'tryActivate', () => false); - expect(proxyContext(1, 2, 3)).to.eventually.throw(); - }); - }); - describe('when can activate', () => { - it('should apply context and args', async () => { - const args = [1, 2, 3]; - sinon.stub(guardsConsumer, 'tryActivate', () => true); + beforeEach(() => { + instance = { foo: 'bar' }; + proxyContext = contextCreator.create(instance, callback as any, ''); + }); + it('should be a function', () => { + expect(proxyContext).to.be.a('function'); + }); + describe('when proxy function called', () => { + describe('when can not activate', () => { + it('should throw exception when "tryActivate" returns false', () => { + sinon.stub(guardsConsumer, 'tryActivate', () => false); + expect(proxyContext(1, 2, 3)).to.eventually.throw(); + }); + }); + describe('when can activate', () => { + it('should apply context and args', async () => { + const args = [1, 2, 3]; + sinon.stub(guardsConsumer, 'tryActivate', () => true); - await proxyContext(...args); - expect(applySpy.calledWith(instance, args)).to.be.true; - }); - }); - }); - }); - }); - describe('findContextModuleName', () => { - describe('when constructor name is undefined', () => { - it('should return empty string', () => { - expect(contextCreator.findContextModuleName({} as any)).to.be.eql(''); - }); - }); - describe('when component exists', () => { - it('should return module key', () => { - const modules = new Map(); - const componentKey = 'test'; - const moduleKey = 'key'; + await proxyContext(...args); + expect(applySpy.calledWith(instance, args)).to.be.true; + }); + }); + }); + }); + }); + describe('findContextModuleName', () => { + describe('when constructor name is undefined', () => { + it('should return empty string', () => { + expect(contextCreator.findContextModuleName({} as any)).to.be.eql(''); + }); + }); + describe('when component exists', () => { + it('should return module key', () => { + const modules = new Map(); + const componentKey = 'test'; + const moduleKey = 'key'; - modules.set(moduleKey, {}); - (contextCreator as any).modulesContainer = modules; - sinon.stub(contextCreator, 'findComponentByClassName', () => true); + modules.set(moduleKey, {}); + (contextCreator as any).modulesContainer = modules; + sinon.stub(contextCreator, 'findComponentByClassName', () => true); - expect( - contextCreator.findContextModuleName({ name: componentKey } as any), - ).to.be.eql(moduleKey); - }); - }); - describe('when component does not exists', () => { - it('should return empty string', () => { - sinon.stub(contextCreator, 'findComponentByClassName', () => false); - expect(contextCreator.findContextModuleName({} as any)).to.be.eql(''); - }); - }); - }); - describe('findComponentByClassName', () => { - describe('when component exists', () => { - it('should return true', () => { - const components = new Map(); - const key = 'test'; - components.set(key, key); + expect( + contextCreator.findContextModuleName({ name: componentKey } as any) + ).to.be.eql(moduleKey); + }); + }); + describe('when component does not exists', () => { + it('should return empty string', () => { + sinon.stub(contextCreator, 'findComponentByClassName', () => false); + expect(contextCreator.findContextModuleName({} as any)).to.be.eql(''); + }); + }); + }); + describe('findComponentByClassName', () => { + describe('when component exists', () => { + it('should return true', () => { + const components = new Map(); + const key = 'test'; + components.set(key, key); - expect( - contextCreator.findComponentByClassName( - { - components, - } as any, - key, - ), - ).to.be.true; - }); - }); - describe('when component does not exists', () => { - it('should return false', () => { - const components = new Map(); - const key = 'test'; - expect( - contextCreator.findComponentByClassName( - { - components, - } as any, - key, - ), - ).to.be.false; - }); - }); - }); + expect( + contextCreator.findComponentByClassName( + { + components + } as any, + key + ) + ).to.be.true; + }); + }); + describe('when component does not exists', () => { + it('should return false', () => { + const components = new Map(); + const key = 'test'; + expect( + contextCreator.findComponentByClassName( + { + components + } as any, + key + ) + ).to.be.false; + }); + }); + }); }); diff --git a/src/core/test/helpers/router-method-factory.spec.ts b/src/core/test/helpers/router-method-factory.spec.ts index 9272e9292d0..93e7022641c 100644 --- a/src/core/test/helpers/router-method-factory.spec.ts +++ b/src/core/test/helpers/router-method-factory.spec.ts @@ -3,29 +3,29 @@ import { RouterMethodFactory } from '../../helpers/router-method-factory'; import { RequestMethod } from '../../../common/enums/request-method.enum'; describe('RouterMethodFactory', () => { - let factory: RouterMethodFactory; - const target = { - get: () => {}, - post: () => {}, - all: () => {}, - delete: () => {}, - put: () => {}, - patch: () => {}, - options: () => {}, - head: () => {}, - }; - beforeEach(() => { - factory = new RouterMethodFactory(); - }); + let factory: RouterMethodFactory; + const target = { + get: () => {}, + post: () => {}, + all: () => {}, + delete: () => {}, + put: () => {}, + patch: () => {}, + options: () => {}, + head: () => {} + }; + beforeEach(() => { + factory = new RouterMethodFactory(); + }); - it('should return proper method', () => { - expect(factory.get(target, RequestMethod.DELETE)).to.equal(target.delete); - expect(factory.get(target, RequestMethod.POST)).to.equal(target.post); - expect(factory.get(target, RequestMethod.ALL)).to.equal(target.all); - expect(factory.get(target, RequestMethod.PUT)).to.equal(target.put); - expect(factory.get(target, RequestMethod.GET)).to.equal(target.get); - expect(factory.get(target, RequestMethod.PATCH)).to.equal(target.patch); - expect(factory.get(target, RequestMethod.OPTIONS)).to.equal(target.options); - expect(factory.get(target, RequestMethod.HEAD)).to.equal(target.head); - }); -}); \ No newline at end of file + it('should return proper method', () => { + expect(factory.get(target, RequestMethod.DELETE)).to.equal(target.delete); + expect(factory.get(target, RequestMethod.POST)).to.equal(target.post); + expect(factory.get(target, RequestMethod.ALL)).to.equal(target.all); + expect(factory.get(target, RequestMethod.PUT)).to.equal(target.put); + expect(factory.get(target, RequestMethod.GET)).to.equal(target.get); + expect(factory.get(target, RequestMethod.PATCH)).to.equal(target.patch); + expect(factory.get(target, RequestMethod.OPTIONS)).to.equal(target.options); + expect(factory.get(target, RequestMethod.HEAD)).to.equal(target.head); + }); +}); diff --git a/src/core/test/injector/container.spec.ts b/src/core/test/injector/container.spec.ts index 3ec9110dad5..1fedd9efe33 100644 --- a/src/core/test/injector/container.spec.ts +++ b/src/core/test/injector/container.spec.ts @@ -6,180 +6,180 @@ import { UnknownModuleException } from '../../errors/exceptions/unknown-module.e import { Global } from '../../../common/index'; describe('NestContainer', () => { - let container: NestContainer; - - @Module({}) - class TestModule {} - - @Global() - @Module({}) - class GlobalTestModule {} - - beforeEach(() => { - container = new NestContainer(); - }); - - it('should "addComponent" throw "UnknownModuleException" when module is not stored in collection', () => { - expect(() => container.addComponent(null, 'TestModule')).throw( - UnknownModuleException, - ); - }); - - it('should "addController" throw "UnknownModuleException" when module is not stored in collection', () => { - expect(() => container.addController(null, 'TestModule')).throw( - UnknownModuleException, - ); - }); - - it('should "addExportedComponent" throw "UnknownModuleException" when module is not stored in collection', () => { - expect(() => container.addExportedComponent(null, 'TestModule')).throw( - UnknownModuleException, - ); - }); - - it('should "addInjectable" throw "UnknownModuleException" when module is not stored in collection', () => { - expect(() => container.addInjectable(null, 'TestModule')).throw( - UnknownModuleException, - ); - }); - - describe('clear', () => { - it('should call `clear` on modules collection', () => { - const clearSpy = sinon.spy((container as any).modules, 'clear'); - container.clear(); - expect(clearSpy.called).to.be.true; - }); - }); - - describe('addModule', () => { - it('should not add module if already exists in collection', () => { - const modules = new Map(); - const setSpy = sinon.spy(modules, 'set'); - (container as any).modules = modules; - - container.addModule(TestModule as any, []); - container.addModule(TestModule as any, []); - - expect(setSpy.calledOnce).to.be.true; - }); - - it('should throws an exception when metatype is not defined', () => { - expect(() => container.addModule(undefined, [])).to.throws(); - }); - - it('should add global module when module is global', () => { - const addGlobalModuleSpy = sinon.spy(container, 'addGlobalModule'); - container.addModule(GlobalTestModule as any, []); - expect(addGlobalModuleSpy.calledOnce).to.be.true; - }); - }); - describe('isGlobalModule', () => { - describe('when module is not global scoped', () => { - it('should return false', () => { - expect(container.isGlobalModule(TestModule as any)).to.be.false; - }); - }); - describe('when module is not global scoped', () => { - it('should return true', () => { - expect(container.isGlobalModule(GlobalTestModule as any)).to.be.true; - }); - }); - }); - - describe('bindGlobalsToRelatedModules', () => { - it('should call "bindGlobalModuleToModule" for every global module', () => { - const global1 = { test: 1 }; - const global2 = { test: 2 }; - - container.addGlobalModule(global1 as any); - container.addGlobalModule(global2 as any); - - const bindGlobalModuleToModuleSpy = sinon.spy( - container, - 'bindGlobalModuleToModule', - ); - container.bindGlobalsToRelatedModules({ - addRelatedModule: sinon.spy(), - } as any); - expect(bindGlobalModuleToModuleSpy.calledTwice).to.be.true; - }); - }); - - describe('bindGlobalModuleToModule', () => { - describe('when "module" is not "globalModule"', () => { - it('should call "addRelatedModule"', () => { - const module = { addRelatedModule: sinon.spy() }; - container.bindGlobalModuleToModule(module as any, null); - expect(module.addRelatedModule.calledOnce).to.be.true; - }); - }); - describe('when "module" is "globalModule"', () => { - it('should not call "addRelatedModule"', () => { - const module = { addRelatedModule: sinon.spy() }; - container.bindGlobalModuleToModule(module as any, module as any); - expect(module.addRelatedModule.calledOnce).to.be.false; - }); - }); - }); - - describe('extractMetadata', () => { - describe('when module is a dynamic module', () => { - it('should return object with "type" and "dynamicMetadata" property', () => { - const obj = { module: 'test', components: [] }; - const { module, ...dynamicMetadata } = obj; - expect(container.extractMetadata(obj as any)).to.be.deep.equal({ - type: module, - dynamicMetadata, - }); - }); - }); - describe('when module is a not dynamic module', () => { - it('should return object with "type" property', () => { - const type = 'test'; - expect(container.extractMetadata(type as any)).to.be.deep.equal({ - type, - }); - }); - }); - }); - - describe('isDynamicModule', () => { - describe('when module is a dynamic module', () => { - it('should return true', () => { - expect(container.isDynamicModule({ module: true } as any)).to.be.true; - }); - }); - describe('when module is a dynamic module', () => { - it('should return undefined', () => { - expect(container.isDynamicModule({ x: true } as any)).to.be.undefined; - }); - }); - }); - - describe('addDynamicMetadata', () => { - let token: string; - let collection: Map; - - beforeEach(() => { - token = 'token'; - collection = new Map(); - (container as any).dynamicModulesMetadata = collection; - }); - describe('when dynamic metadata exists', () => { - it('should add to the dynamic metadata collection', () => { - const addSpy = sinon.spy(collection, 'set'); - const dynamicMetadata = { module: null }; - - container.addDynamicMetadata(token, dynamicMetadata); - expect(addSpy.calledWith(token, dynamicMetadata)).to.be.true; - }); - }); - describe('when dynamic metadata does not exists', () => { - it('should not add to the dynamic metadata collection', () => { - const addSpy = sinon.spy(collection, 'set'); - container.addDynamicMetadata(token, null); - expect(addSpy.called).to.be.false; - }); - }); - }); + let container: NestContainer; + + @Module({}) + class TestModule {} + + @Global() + @Module({}) + class GlobalTestModule {} + + beforeEach(() => { + container = new NestContainer(); + }); + + it('should "addComponent" throw "UnknownModuleException" when module is not stored in collection', () => { + expect(() => container.addComponent(null, 'TestModule')).throw( + UnknownModuleException + ); + }); + + it('should "addController" throw "UnknownModuleException" when module is not stored in collection', () => { + expect(() => container.addController(null, 'TestModule')).throw( + UnknownModuleException + ); + }); + + it('should "addExportedComponent" throw "UnknownModuleException" when module is not stored in collection', () => { + expect(() => container.addExportedComponent(null, 'TestModule')).throw( + UnknownModuleException + ); + }); + + it('should "addInjectable" throw "UnknownModuleException" when module is not stored in collection', () => { + expect(() => container.addInjectable(null, 'TestModule')).throw( + UnknownModuleException + ); + }); + + describe('clear', () => { + it('should call `clear` on modules collection', () => { + const clearSpy = sinon.spy((container as any).modules, 'clear'); + container.clear(); + expect(clearSpy.called).to.be.true; + }); + }); + + describe('addModule', () => { + it('should not add module if already exists in collection', () => { + const modules = new Map(); + const setSpy = sinon.spy(modules, 'set'); + (container as any).modules = modules; + + container.addModule(TestModule as any, []); + container.addModule(TestModule as any, []); + + expect(setSpy.calledOnce).to.be.true; + }); + + it('should throws an exception when metatype is not defined', () => { + expect(() => container.addModule(undefined, [])).to.throws(); + }); + + it('should add global module when module is global', () => { + const addGlobalModuleSpy = sinon.spy(container, 'addGlobalModule'); + container.addModule(GlobalTestModule as any, []); + expect(addGlobalModuleSpy.calledOnce).to.be.true; + }); + }); + describe('isGlobalModule', () => { + describe('when module is not global scoped', () => { + it('should return false', () => { + expect(container.isGlobalModule(TestModule as any)).to.be.false; + }); + }); + describe('when module is not global scoped', () => { + it('should return true', () => { + expect(container.isGlobalModule(GlobalTestModule as any)).to.be.true; + }); + }); + }); + + describe('bindGlobalsToRelatedModules', () => { + it('should call "bindGlobalModuleToModule" for every global module', () => { + const global1 = { test: 1 }; + const global2 = { test: 2 }; + + container.addGlobalModule(global1 as any); + container.addGlobalModule(global2 as any); + + const bindGlobalModuleToModuleSpy = sinon.spy( + container, + 'bindGlobalModuleToModule' + ); + container.bindGlobalsToRelatedModules({ + addRelatedModule: sinon.spy() + } as any); + expect(bindGlobalModuleToModuleSpy.calledTwice).to.be.true; + }); + }); + + describe('bindGlobalModuleToModule', () => { + describe('when "module" is not "globalModule"', () => { + it('should call "addRelatedModule"', () => { + const module = { addRelatedModule: sinon.spy() }; + container.bindGlobalModuleToModule(module as any, null); + expect(module.addRelatedModule.calledOnce).to.be.true; + }); + }); + describe('when "module" is "globalModule"', () => { + it('should not call "addRelatedModule"', () => { + const module = { addRelatedModule: sinon.spy() }; + container.bindGlobalModuleToModule(module as any, module as any); + expect(module.addRelatedModule.calledOnce).to.be.false; + }); + }); + }); + + describe('extractMetadata', () => { + describe('when module is a dynamic module', () => { + it('should return object with "type" and "dynamicMetadata" property', () => { + const obj = { module: 'test', components: [] }; + const { module, ...dynamicMetadata } = obj; + expect(container.extractMetadata(obj as any)).to.be.deep.equal({ + type: module, + dynamicMetadata + }); + }); + }); + describe('when module is a not dynamic module', () => { + it('should return object with "type" property', () => { + const type = 'test'; + expect(container.extractMetadata(type as any)).to.be.deep.equal({ + type + }); + }); + }); + }); + + describe('isDynamicModule', () => { + describe('when module is a dynamic module', () => { + it('should return true', () => { + expect(container.isDynamicModule({ module: true } as any)).to.be.true; + }); + }); + describe('when module is a dynamic module', () => { + it('should return undefined', () => { + expect(container.isDynamicModule({ x: true } as any)).to.be.undefined; + }); + }); + }); + + describe('addDynamicMetadata', () => { + let token: string; + let collection: Map; + + beforeEach(() => { + token = 'token'; + collection = new Map(); + (container as any).dynamicModulesMetadata = collection; + }); + describe('when dynamic metadata exists', () => { + it('should add to the dynamic metadata collection', () => { + const addSpy = sinon.spy(collection, 'set'); + const dynamicMetadata = { module: null }; + + container.addDynamicMetadata(token, dynamicMetadata); + expect(addSpy.calledWith(token, dynamicMetadata)).to.be.true; + }); + }); + describe('when dynamic metadata does not exists', () => { + it('should not add to the dynamic metadata collection', () => { + const addSpy = sinon.spy(collection, 'set'); + container.addDynamicMetadata(token, null); + expect(addSpy.called).to.be.false; + }); + }); + }); }); diff --git a/src/core/test/injector/injector.spec.ts b/src/core/test/injector/injector.spec.ts index 0465535cc84..7e31fb903da 100644 --- a/src/core/test/injector/injector.spec.ts +++ b/src/core/test/injector/injector.spec.ts @@ -12,511 +12,680 @@ import { UndefinedDependencyException } from '../../errors/exceptions/undefined- chai.use(chaiAsPromised); describe('Injector', () => { - let injector: Injector; + let injector: Injector; - beforeEach(() => { - injector = new Injector(); - }); - - describe('loadInstance', () => { - - @Component() - class DependencyOne {} - - @Component() - class DependencyTwo {} - - @Component() - class MainTest { - constructor( - public depOne: DependencyOne, - public depTwo: DependencyTwo) {} - } - - let moduleDeps: Module; - let mainTest, depOne, depTwo; - - beforeEach(() => { - moduleDeps = new Module(DependencyTwo as any, [], new NestContainer()); - mainTest = { - name: 'MainTest', - metatype: MainTest, - instance: Object.create(MainTest.prototype), - isResolved: false, - }; - depOne = { - name: 'DependencyOne', - metatype: DependencyOne, - instance: Object.create(DependencyOne.prototype), - isResolved: false, - }; - depTwo = { - name: 'DependencyTwo', - metatype: DependencyTwo, - instance: Object.create(DependencyOne.prototype), - isResolved: false, - }; - moduleDeps.components.set('MainTest', mainTest); - moduleDeps.components.set('DependencyOne', depOne); - moduleDeps.components.set('DependencyTwo', depTwo); - moduleDeps.components.set('MainTestResolved', { ...mainTest, isResolved: true }); - }); + beforeEach(() => { + injector = new Injector(); + }); - it('should create an instance of component with proper dependencies', async () => { - await injector.loadInstance(mainTest, moduleDeps.components, moduleDeps); - const { instance } = moduleDeps.components.get('MainTest') as InstanceWrapper; + describe('loadInstance', () => { + @Component() + class DependencyOne {} - expect(instance.depOne).instanceof(DependencyOne); - expect(instance.depTwo).instanceof(DependencyOne); - expect(instance).instanceof(MainTest); - }); + @Component() + class DependencyTwo {} - it('should set "isResolved" property to true after instance initialization', async () => { - await injector.loadInstance(mainTest, moduleDeps.components, moduleDeps); - const { isResolved } = moduleDeps.components.get('MainTest') as InstanceWrapper; - expect(isResolved).to.be.true; - }); + @Component() + class MainTest { + constructor(public depOne: DependencyOne, public depTwo: DependencyTwo) {} + } - it('should throw RuntimeException when type is not stored in collection', () => { - return expect( - injector.loadInstance({} as any, moduleDeps.components, moduleDeps), - ).to.eventually.be.rejected; - }); - - it('should await done$ when "isPending"', async () => { - const value = 'test'; - const result = await injector.loadInstance({ - name: 'MainTest', - metatype: MainTest, - instance: Object.create(MainTest.prototype), - isResolved: false, - isPending: true, - done$: Promise.resolve(value) as any, - }, moduleDeps.components, moduleDeps); - expect(result).to.be.eql(value); - }); + let moduleDeps: Module; + let mainTest, depOne, depTwo; - it('should return null when metatype is resolved', async () => { - const value = 'test'; - const result = await injector.loadInstance({ - name: 'MainTestResolved', - metatype: MainTest, - instance: Object.create(MainTest.prototype), - isResolved: true, - }, moduleDeps.components, moduleDeps); - expect(result).to.be.null; - }); + beforeEach(() => { + moduleDeps = new Module(DependencyTwo as any, [], new NestContainer()); + mainTest = { + name: 'MainTest', + metatype: MainTest, + instance: Object.create(MainTest.prototype), + isResolved: false + }; + depOne = { + name: 'DependencyOne', + metatype: DependencyOne, + instance: Object.create(DependencyOne.prototype), + isResolved: false + }; + depTwo = { + name: 'DependencyTwo', + metatype: DependencyTwo, + instance: Object.create(DependencyOne.prototype), + isResolved: false + }; + moduleDeps.components.set('MainTest', mainTest); + moduleDeps.components.set('DependencyOne', depOne); + moduleDeps.components.set('DependencyTwo', depTwo); + moduleDeps.components.set('MainTestResolved', { + ...mainTest, + isResolved: true + }); }); - describe('loadPrototypeOfInstance', () => { - - @Component() - class Test {} - - let moduleDeps: Module; - let test; - - beforeEach(() => { - moduleDeps = new Module(Test as any, [], new NestContainer()); - test = { - name: 'Test', - metatype: Test, - instance: Object.create(Test.prototype), - isResolved: false, - }; - moduleDeps.components.set('Test', test); - }); + it('should create an instance of component with proper dependencies', async () => { + await injector.loadInstance(mainTest, moduleDeps.components, moduleDeps); + const { instance } = moduleDeps.components.get( + 'MainTest' + ) as InstanceWrapper; - it('should create prototype of instance', () => { - const expectedResult = { - instance: Object.create(Test.prototype), - isResolved: false, - metatype: Test, - name: 'Test', - }; - injector.loadPrototypeOfInstance(test, moduleDeps.components); - expect(moduleDeps.components.get('Test')).to.deep.equal(expectedResult); - }); - - it('should return null when collection is nil', () => { - const result = injector.loadPrototypeOfInstance(test, null); - expect(result).to.be.null; - }); + expect(instance.depOne).instanceof(DependencyOne); + expect(instance.depTwo).instanceof(DependencyOne); + expect(instance).instanceof(MainTest); + }); - it('should return null when target isResolved', () => { - const collection = { - get: () => ({ isResolved: true }), - }; - const result = injector.loadPrototypeOfInstance(test, collection as any); - expect(result).to.be.null; - }); + it('should set "isResolved" property to true after instance initialization', async () => { + await injector.loadInstance(mainTest, moduleDeps.components, moduleDeps); + const { isResolved } = moduleDeps.components.get( + 'MainTest' + ) as InstanceWrapper; + expect(isResolved).to.be.true; + }); - it('should return null when "inject" is not nil', () => { - const collection = { - get: () => ({ inject: [] }), - }; - const result = injector.loadPrototypeOfInstance(test, collection as any); - expect(result).to.be.null; - }); + it('should throw RuntimeException when type is not stored in collection', () => { + return expect( + injector.loadInstance({} as any, moduleDeps.components, moduleDeps) + ).to.eventually.be.rejected; }); - describe('resolveSingleParam', () => { - it('should throw "RuntimeException" when param is undefined', async () => { - return expect( - injector.resolveSingleParam(null, undefined, { index: 0, length: 5 }, null, []), - ).to.eventually.be.rejected; - }); + it('should await done$ when "isPending"', async () => { + const value = 'test'; + const result = await injector.loadInstance( + { + name: 'MainTest', + metatype: MainTest, + instance: Object.create(MainTest.prototype), + isResolved: false, + isPending: true, + done$: Promise.resolve(value) as any + }, + moduleDeps.components, + moduleDeps + ); + expect(result).to.be.eql(value); }); - describe('loadInstanceOfMiddleware', () => { - let resolveConstructorParams: sinon.SinonSpy; + it('should return null when metatype is resolved', async () => { + const value = 'test'; + const result = await injector.loadInstance( + { + name: 'MainTestResolved', + metatype: MainTest, + instance: Object.create(MainTest.prototype), + isResolved: true + }, + moduleDeps.components, + moduleDeps + ); + expect(result).to.be.null; + }); + }); - beforeEach(() => { - resolveConstructorParams = sinon.spy(); - injector.resolveConstructorParams = resolveConstructorParams; - }); + describe('loadPrototypeOfInstance', () => { + @Component() + class Test {} - it('should call "resolveConstructorParams" when instance is not resolved', () => { - const collection = { - get: (...args) => ({ - instance: null, - }), - set: (...args) => {}, - }; + let moduleDeps: Module; + let test; - injector.loadInstanceOfMiddleware({ metatype: { name: '' }} as any, collection as any, null); - expect(resolveConstructorParams.called).to.be.true; - }); + beforeEach(() => { + moduleDeps = new Module(Test as any, [], new NestContainer()); + test = { + name: 'Test', + metatype: Test, + instance: Object.create(Test.prototype), + isResolved: false + }; + moduleDeps.components.set('Test', test); + }); - it('should not call "resolveConstructorParams" when instance is not resolved', () => { - const collection = { - get: (...args) => ({ - instance: {}, - }), - set: (...args) => {}, - }; + it('should create prototype of instance', () => { + const expectedResult = { + instance: Object.create(Test.prototype), + isResolved: false, + metatype: Test, + name: 'Test' + }; + injector.loadPrototypeOfInstance(test, moduleDeps.components); + expect(moduleDeps.components.get('Test')).to.deep.equal(expectedResult); + }); - injector.loadInstanceOfMiddleware({ metatype: { name: '' }} as any, collection as any, null); - expect(resolveConstructorParams.called).to.be.false; - }); + it('should return null when collection is nil', () => { + const result = injector.loadPrototypeOfInstance(test, null); + expect(result).to.be.null; }); - describe('loadInstanceOfRoute', () => { - let loadInstance: sinon.SinonSpy; + it('should return null when target isResolved', () => { + const collection = { + get: () => ({ isResolved: true }) + }; + const result = injector.loadPrototypeOfInstance(test, collection as any); + expect(result).to.be.null; + }); - beforeEach(() => { - loadInstance = sinon.spy(); - injector.loadInstance = loadInstance; - }); + it('should return null when "inject" is not nil', () => { + const collection = { + get: () => ({ inject: [] }) + }; + const result = injector.loadPrototypeOfInstance(test, collection as any); + expect(result).to.be.null; + }); + }); + + describe('resolveSingleParam', () => { + it('should throw "RuntimeException" when param is undefined', async () => { + return expect( + injector.resolveSingleParam( + null, + undefined, + { index: 0, length: 5 }, + null, + [] + ) + ).to.eventually.be.rejected; + }); + }); - it('should call "loadInstance" with expected arguments', async () => { - const module = { routes: [] }; - const wrapper = { test: 'test' }; + describe('loadInstanceOfMiddleware', () => { + let resolveConstructorParams: sinon.SinonSpy; - await injector.loadInstanceOfRoute(wrapper as any, module as any); - expect(loadInstance.calledWith(wrapper, module.routes, module)).to.be.true; - }); + beforeEach(() => { + resolveConstructorParams = sinon.spy(); + injector.resolveConstructorParams = resolveConstructorParams; }); - describe('loadInstanceOfInjectable', () => { - let loadInstance: sinon.SinonSpy; + it('should call "resolveConstructorParams" when instance is not resolved', () => { + const collection = { + get: (...args) => ({ + instance: null + }), + set: (...args) => {} + }; + + injector.loadInstanceOfMiddleware( + { metatype: { name: '' } } as any, + collection as any, + null + ); + expect(resolveConstructorParams.called).to.be.true; + }); - beforeEach(() => { - loadInstance = sinon.spy(); - injector.loadInstance = loadInstance; - }); + it('should not call "resolveConstructorParams" when instance is not resolved', () => { + const collection = { + get: (...args) => ({ + instance: {} + }), + set: (...args) => {} + }; + + injector.loadInstanceOfMiddleware( + { metatype: { name: '' } } as any, + collection as any, + null + ); + expect(resolveConstructorParams.called).to.be.false; + }); + }); - it('should call "loadInstance" with expected arguments', async () => { - const module = { injectables: [] }; - const wrapper = { test: 'test' }; + describe('loadInstanceOfRoute', () => { + let loadInstance: sinon.SinonSpy; - await injector.loadInstanceOfInjectable(wrapper as any, module as any); - expect(loadInstance.calledWith(wrapper, module.injectables, module)).to.be.true; - }); + beforeEach(() => { + loadInstance = sinon.spy(); + injector.loadInstance = loadInstance; }); - describe('resolveFactoryInstance', () => { - it('should resolve deffered value', async () => { - const wrapper = { test: 'test' }; - const result = await injector.resolveFactoryInstance(Promise.resolve(wrapper)); - expect(result).to.be.eql(wrapper); - }); - it('should return exact same value', async () => { - const wrapper = { test: 'test' }; - const result = await injector.resolveFactoryInstance(wrapper); - expect(result).to.be.eql(wrapper); - }); + it('should call "loadInstance" with expected arguments', async () => { + const module = { routes: [] }; + const wrapper = { test: 'test' }; + + await injector.loadInstanceOfRoute(wrapper as any, module as any); + expect(loadInstance.calledWith(wrapper, module.routes, module)).to.be + .true; }); + }); - describe('scanForComponent', () => { - let scanForComponentInRelatedModules: sinon.SinonStub; - const metatype = { name: 'test', metatype: { name: 'test' }}; + describe('loadInstanceOfInjectable', () => { + let loadInstance: sinon.SinonSpy; - beforeEach(() => { - scanForComponentInRelatedModules = sinon.stub(); - (injector as any).scanForComponentInRelatedModules = scanForComponentInRelatedModules; - }); + beforeEach(() => { + loadInstance = sinon.spy(); + injector.loadInstance = loadInstance; + }); - it('should return object from collection if exists', async () => { - const instance = { test: 3 }; - const collection = { - has: () => true, - get: () => instance, - }; - const result = await injector.scanForComponent(collection as any, null, { name: metatype.name, index: 0, length: 10 }, metatype); - expect(result).to.be.equal(instance); - }); + it('should call "loadInstance" with expected arguments', async () => { + const module = { injectables: [] }; + const wrapper = { test: 'test' }; - it('should call "scanForComponentInRelatedModules" when object is not in collection', async () => { - scanForComponentInRelatedModules.returns({}); - const collection = { - has: () => false, - }; - await injector.scanForComponent(collection as any, null, { name: metatype.name, index: 0, length: 10 }, metatype); - expect(scanForComponentInRelatedModules.called).to.be.true; - }); + await injector.loadInstanceOfInjectable(wrapper as any, module as any); + expect(loadInstance.calledWith(wrapper, module.injectables, module)).to.be + .true; + }); + }); + + describe('resolveFactoryInstance', () => { + it('should resolve deffered value', async () => { + const wrapper = { test: 'test' }; + const result = await injector.resolveFactoryInstance( + Promise.resolve(wrapper) + ); + expect(result).to.be.eql(wrapper); + }); + it('should return exact same value', async () => { + const wrapper = { test: 'test' }; + const result = await injector.resolveFactoryInstance(wrapper); + expect(result).to.be.eql(wrapper); + }); + }); - it('should throw "UnknownDependenciesException" when instanceWrapper is null and "exports" collection does not contain token', () => { - scanForComponentInRelatedModules.returns(null); - const collection = { - has: () => false, - }; - const module = { exports: collection }; - expect( - injector.scanForComponent(collection as any, module as any, { name: metatype.name, index: 0, length: 10 }, { metatype }), - ).to.eventually.be.rejected; - }); - - it('should not throw "UnknownDependenciesException" instanceWrapper is not null', () => { - scanForComponentInRelatedModules.returns({}); - const collection = { - has: () => false, - }; - const module = { exports: collection }; - expect( - injector.scanForComponent(collection as any, module as any, { name: metatype.name, index: 0, length: 10 }, metatype), - ).to.eventually.be.not.rejected; - }); + describe('scanForComponent', () => { + let scanForComponentInRelatedModules: sinon.SinonStub; + const metatype = { name: 'test', metatype: { name: 'test' } }; + beforeEach(() => { + scanForComponentInRelatedModules = sinon.stub(); + (injector as any).scanForComponentInRelatedModules = scanForComponentInRelatedModules; }); - describe('scanForComponentInRelatedModules', () => { - let loadInstanceOfComponent: sinon.SinonSpy; - const metatype = { name: 'test' }; - const module = { - relatedModules: new Map(), - }; - - beforeEach(() => { - loadInstanceOfComponent = sinon.spy(); - (injector as any).loadInstanceOfComponent = loadInstanceOfComponent; - }); + it('should return object from collection if exists', async () => { + const instance = { test: 3 }; + const collection = { + has: () => true, + get: () => instance + }; + const result = await injector.scanForComponent( + collection as any, + null, + { name: metatype.name, index: 0, length: 10 }, + metatype + ); + expect(result).to.be.equal(instance); + }); - it('should return null when there is no related modules', async () => { - const result = await injector.scanForComponentInRelatedModules(module as any, null, []); - expect(result).to.be.eq(null); - }); + it('should call "scanForComponentInRelatedModules" when object is not in collection', async () => { + scanForComponentInRelatedModules.returns({}); + const collection = { + has: () => false + }; + await injector.scanForComponent( + collection as any, + null, + { name: metatype.name, index: 0, length: 10 }, + metatype + ); + expect(scanForComponentInRelatedModules.called).to.be.true; + }); - it('should return null when related modules do not have appropriate component', () => { - let module = { - relatedModules: new Map([['key', { - components: { - has: () => false, - }, - exports: { - has: () => true, - }, - }]] as any), - }; - expect( - injector.scanForComponentInRelatedModules(module as any, metatype as any, []), - ).to.be.eventually.eq(null); - - module = { - relatedModules: new Map([['key', { - components: { - has: () => true, - }, - exports: { - has: () => false, - }, - }]] as any), - }; - expect( - injector.scanForComponentInRelatedModules(module as any, metatype as any, []), - ).to.eventually.be.eq(null); - }); + it('should throw "UnknownDependenciesException" when instanceWrapper is null and "exports" collection does not contain token', () => { + scanForComponentInRelatedModules.returns(null); + const collection = { + has: () => false + }; + const module = { exports: collection }; + expect( + injector.scanForComponent( + collection as any, + module as any, + { name: metatype.name, index: 0, length: 10 }, + { metatype } + ) + ).to.eventually.be.rejected; + }); - it('should call "loadInstanceOfComponent" when component is not resolved', async () => { - let module = { - relatedModules: new Map([['key', { - components: { - has: () => true, - get: () => ({ - isResolved: false, - }), - }, - exports: { - has: () => true, - }, - relatedModules: new Map(), - }]] as any), - }; - await injector.scanForComponentInRelatedModules(module as any, metatype as any, []); - expect(loadInstanceOfComponent.called).to.be.true; - }); + it('should not throw "UnknownDependenciesException" instanceWrapper is not null', () => { + scanForComponentInRelatedModules.returns({}); + const collection = { + has: () => false + }; + const module = { exports: collection }; + expect( + injector.scanForComponent( + collection as any, + module as any, + { name: metatype.name, index: 0, length: 10 }, + metatype + ) + ).to.eventually.be.not.rejected; + }); + }); - it('should not call "loadInstanceOfComponent" when component is resolved', async () => { - let module = { - relatedModules: new Map([['key', { - components: { - has: () => true, - get: () => ({ - isResolved: true, - }), - }, - exports: { - has: () => true, - }, - relatedModules: new Map(), - }]] as any), - }; - await injector.scanForComponentInRelatedModules(module as any, metatype as any, []); - expect(loadInstanceOfComponent.called).to.be.false; - }); + describe('scanForComponentInRelatedModules', () => { + let loadInstanceOfComponent: sinon.SinonSpy; + const metatype = { name: 'test' }; + const module = { + relatedModules: new Map() + }; + beforeEach(() => { + loadInstanceOfComponent = sinon.spy(); + (injector as any).loadInstanceOfComponent = loadInstanceOfComponent; }); - describe('scanForComponentInScopes', () => { - it('should returns null when component is not available in any scope', () => { - expect(injector.scanForComponentInScopes([], { name: '', index: 0, length: 10 }, {})).to.eventually.be.null; - }); - it('should returns wrapper when component is available in any scope', () => { - const component = 'test'; - sinon.stub(injector, 'scanForComponentInScope').returns(component); - expect(injector.scanForComponentInScopes([{}] as any, { name: '', index: 0, length: 10 }, {})).to.eventually.be.eql(component); - }); + it('should return null when there is no related modules', async () => { + const result = await injector.scanForComponentInRelatedModules( + module as any, + null, + [] + ); + expect(result).to.be.eq(null); }); - describe('scanForComponentInScope', () => { - it('should returns null when scope throws exception', () => { - sinon.stub(injector, 'scanForComponent').throws('exception'); - expect(injector.scanForComponentInScope({} as any, { name: '', index: 0, length: 10 }, {})).to.eventually.be.null; - }); + it('should return null when related modules do not have appropriate component', () => { + let module = { + relatedModules: new Map([ + [ + 'key', + { + components: { + has: () => false + }, + exports: { + has: () => true + } + } + ] + ] as any) + }; + expect( + injector.scanForComponentInRelatedModules( + module as any, + metatype as any, + [] + ) + ).to.be.eventually.eq(null); + + module = { + relatedModules: new Map([ + [ + 'key', + { + components: { + has: () => true + }, + exports: { + has: () => false + } + } + ] + ] as any) + }; + expect( + injector.scanForComponentInRelatedModules( + module as any, + metatype as any, + [] + ) + ).to.eventually.be.eq(null); + }); - it('should rethrow UndefinedDependencyException', () => { - sinon.stub(injector, 'scanForComponent').throws(new UndefinedDependencyException('type', 0, 10)); - expect(injector.scanForComponentInScope({} as any, { name: 'type', index: 0, length: 10 }, {})).to.eventually.throw(); - }); + it('should call "loadInstanceOfComponent" when component is not resolved', async () => { + let module = { + relatedModules: new Map([ + [ + 'key', + { + components: { + has: () => true, + get: () => ({ + isResolved: false + }) + }, + exports: { + has: () => true + }, + relatedModules: new Map() + } + ] + ] as any) + }; + await injector.scanForComponentInRelatedModules( + module as any, + metatype as any, + [] + ); + expect(loadInstanceOfComponent.called).to.be.true; + }); - describe('when instanceWrapper is not resolved and does not have forward ref', () => { - it('should call loadInstanceOfComponent', async () => { - const loadStub = sinon.stub(injector, 'loadInstanceOfComponent').callsFake(() => null); - sinon.stub(injector, 'scanForComponent').returns({ isResolved: false }); - - await injector.scanForComponentInScope([] as any, { name: 'name', index: 0, length: 10 }, {} as any); - expect(loadStub.called).to.be.true; - }); - it('should not call loadInstanceOfComponent (isResolved)', async () => { - const loadStub = sinon.stub(injector, 'loadInstanceOfComponent').callsFake(() => null); - sinon.stub(injector, 'scanForComponent').returns({ isResolved: true }); - - await injector.scanForComponentInScope([] as any, { name: 'name', index: 0, length: 10 }, {} as any); - expect(loadStub.called).to.be.false; - }); - it('should not call loadInstanceOfComponent (forwardRef)', async () => { - const loadStub = sinon.stub(injector, 'loadInstanceOfComponent').callsFake(() => null); - sinon.stub(injector, 'scanForComponent').returns({ isResolved: false, forwardRef: true }); - - await injector.scanForComponentInScope([] as any, { name: 'name', index: 0, length: 10 }, {} as any); - expect(loadStub.called).to.be.false; - }); - }); + it('should not call "loadInstanceOfComponent" when component is resolved', async () => { + let module = { + relatedModules: new Map([ + [ + 'key', + { + components: { + has: () => true, + get: () => ({ + isResolved: true + }) + }, + exports: { + has: () => true + }, + relatedModules: new Map() + } + ] + ] as any) + }; + await injector.scanForComponentInRelatedModules( + module as any, + metatype as any, + [] + ); + expect(loadInstanceOfComponent.called).to.be.false; + }); + }); + + describe('scanForComponentInScopes', () => { + it('should returns null when component is not available in any scope', () => { + expect( + injector.scanForComponentInScopes( + [], + { name: '', index: 0, length: 10 }, + {} + ) + ).to.eventually.be.null; + }); + it('should returns wrapper when component is available in any scope', () => { + const component = 'test'; + sinon.stub(injector, 'scanForComponentInScope').returns(component); + expect( + injector.scanForComponentInScopes( + [{}] as any, + { name: '', index: 0, length: 10 }, + {} + ) + ).to.eventually.be.eql(component); + }); + }); + + describe('scanForComponentInScope', () => { + it('should returns null when scope throws exception', () => { + sinon.stub(injector, 'scanForComponent').throws('exception'); + expect( + injector.scanForComponentInScope( + {} as any, + { name: '', index: 0, length: 10 }, + {} + ) + ).to.eventually.be.null; }); - describe('resolveParamToken', () => { - let forwardRef; - let wrapper; - let param; + it('should rethrow UndefinedDependencyException', () => { + sinon + .stub(injector, 'scanForComponent') + .throws(new UndefinedDependencyException('type', 0, 10)); + expect( + injector.scanForComponentInScope( + {} as any, + { name: 'type', index: 0, length: 10 }, + {} + ) + ).to.eventually.throw(); + }); - describe('when "forwardRef" property is not nil', () => { - beforeEach(() => { - forwardRef = 'test'; - wrapper = {}; - param = { - forwardRef: () => forwardRef, - }; - }); - it('return forwardRef() result', () => { - expect(injector.resolveParamToken(wrapper, param)).to.be.eql(forwardRef); - }); - it('set wrapper "forwardRef" property to true', () => { - injector.resolveParamToken(wrapper, param); - expect(wrapper.forwardRef).to.be.true; - }); + describe('when instanceWrapper is not resolved and does not have forward ref', () => { + it('should call loadInstanceOfComponent', async () => { + const loadStub = sinon + .stub(injector, 'loadInstanceOfComponent') + .callsFake(() => null); + sinon.stub(injector, 'scanForComponent').returns({ isResolved: false }); + + await injector.scanForComponentInScope( + [] as any, + { name: 'name', index: 0, length: 10 }, + {} as any + ); + expect(loadStub.called).to.be.true; }); - describe('when "forwardRef" property is nil', () => { - beforeEach(() => { - forwardRef = 'test'; - wrapper = {}; - param = {}; - }); - it('set wrapper "forwardRef" property to false', () => { - injector.resolveParamToken(wrapper, param); - expect(wrapper.forwardRef).to.be.undefined; - }); - it('return param', () => { - expect(injector.resolveParamToken(wrapper, param)).to.be.eql(param); - }); + it('should not call loadInstanceOfComponent (isResolved)', async () => { + const loadStub = sinon + .stub(injector, 'loadInstanceOfComponent') + .callsFake(() => null); + sinon.stub(injector, 'scanForComponent').returns({ isResolved: true }); + + await injector.scanForComponentInScope( + [] as any, + { name: 'name', index: 0, length: 10 }, + {} as any + ); + expect(loadStub.called).to.be.false; + }); + it('should not call loadInstanceOfComponent (forwardRef)', async () => { + const loadStub = sinon + .stub(injector, 'loadInstanceOfComponent') + .callsFake(() => null); + sinon + .stub(injector, 'scanForComponent') + .returns({ isResolved: false, forwardRef: true }); + + await injector.scanForComponentInScope( + [] as any, + { name: 'name', index: 0, length: 10 }, + {} as any + ); + expect(loadStub.called).to.be.false; }); }); + }); - describe('resolveComponentInstance', () => { - let module; + describe('resolveParamToken', () => { + let forwardRef; + let wrapper; + let param; + + describe('when "forwardRef" property is not nil', () => { beforeEach(() => { - module = { - components: [], + forwardRef = 'test'; + wrapper = {}; + param = { + forwardRef: () => forwardRef }; }); + it('return forwardRef() result', () => { + expect(injector.resolveParamToken(wrapper, param)).to.be.eql( + forwardRef + ); + }); + it('set wrapper "forwardRef" property to true', () => { + injector.resolveParamToken(wrapper, param); + expect(wrapper.forwardRef).to.be.true; + }); + }); + describe('when "forwardRef" property is nil', () => { + beforeEach(() => { + forwardRef = 'test'; + wrapper = {}; + param = {}; + }); + it('set wrapper "forwardRef" property to false', () => { + injector.resolveParamToken(wrapper, param); + expect(wrapper.forwardRef).to.be.undefined; + }); + it('return param', () => { + expect(injector.resolveParamToken(wrapper, param)).to.be.eql(param); + }); + }); + }); - describe('when instanceWrapper is not resolved and does not have forward ref', () => { - it('should call loadInstanceOfComponent', async () => { - const loadStub = sinon.stub(injector, 'loadInstanceOfComponent').callsFake(() => null); - sinon.stub(injector, 'scanForComponent').returns({ isResolved: false }); - - await injector.resolveComponentInstance(module, '', { index: 0, length: 10 }, {} as any, []); - expect(loadStub.called).to.be.true; - }); - it('should not call loadInstanceOfComponent (isResolved)', async () => { - const loadStub = sinon.stub(injector, 'loadInstanceOfComponent').callsFake(() => null); - sinon.stub(injector, 'scanForComponent').returns({ isResolved: true }); - - await injector.resolveComponentInstance(module, '', { index: 0, length: 10 }, {} as any, []); - expect(loadStub.called).to.be.false; - }); - it('should not call loadInstanceOfComponent (forwardRef)', async () => { - const loadStub = sinon.stub(injector, 'loadInstanceOfComponent').callsFake(() => null); - sinon.stub(injector, 'scanForComponent').returns({ isResolved: false, forwardRef: true }); + describe('resolveComponentInstance', () => { + let module; + beforeEach(() => { + module = { + components: [] + }; + }); - await injector.resolveComponentInstance(module, '', { index: 0, length: 10 }, {} as any, []); - expect(loadStub.called).to.be.false; - }); + describe('when instanceWrapper is not resolved and does not have forward ref', () => { + it('should call loadInstanceOfComponent', async () => { + const loadStub = sinon + .stub(injector, 'loadInstanceOfComponent') + .callsFake(() => null); + sinon.stub(injector, 'scanForComponent').returns({ isResolved: false }); + + await injector.resolveComponentInstance( + module, + '', + { index: 0, length: 10 }, + {} as any, + [] + ); + expect(loadStub.called).to.be.true; + }); + it('should not call loadInstanceOfComponent (isResolved)', async () => { + const loadStub = sinon + .stub(injector, 'loadInstanceOfComponent') + .callsFake(() => null); + sinon.stub(injector, 'scanForComponent').returns({ isResolved: true }); + + await injector.resolveComponentInstance( + module, + '', + { index: 0, length: 10 }, + {} as any, + [] + ); + expect(loadStub.called).to.be.false; }); + it('should not call loadInstanceOfComponent (forwardRef)', async () => { + const loadStub = sinon + .stub(injector, 'loadInstanceOfComponent') + .callsFake(() => null); + sinon + .stub(injector, 'scanForComponent') + .returns({ isResolved: false, forwardRef: true }); + + await injector.resolveComponentInstance( + module, + '', + { index: 0, length: 10 }, + {} as any, + [] + ); + expect(loadStub.called).to.be.false; + }); + }); - describe('when instanceWraper has async property', () => { - it('should await instance', async () => { - const loadStub = sinon.stub(injector, 'loadInstanceOfComponent').callsFake(() => null); - - const instance = Promise.resolve(true); - sinon.stub(injector, 'scanForComponent').returns({ - isResolved: false, - forwardRef: true, - async: true, - instance, - }); - const result = await injector.resolveComponentInstance(module, '', { index: 0, length: 10 }, {} as any, []); - expect(result.instance).to.be.true; - }); + describe('when instanceWraper has async property', () => { + it('should await instance', async () => { + const loadStub = sinon + .stub(injector, 'loadInstanceOfComponent') + .callsFake(() => null); + + const instance = Promise.resolve(true); + sinon.stub(injector, 'scanForComponent').returns({ + isResolved: false, + forwardRef: true, + async: true, + instance + }); + const result = await injector.resolveComponentInstance( + module, + '', + { index: 0, length: 10 }, + {} as any, + [] + ); + expect(result.instance).to.be.true; }); }); - }); \ No newline at end of file + }); +}); diff --git a/src/core/test/injector/instance-loader.spec.ts b/src/core/test/injector/instance-loader.spec.ts index 7c69af0c953..aa14f755a90 100644 --- a/src/core/test/injector/instance-loader.spec.ts +++ b/src/core/test/injector/instance-loader.spec.ts @@ -9,124 +9,150 @@ import { NestEnvironment } from '../../../common/enums/nest-environment.enum'; import { Logger } from '../../../common/services/logger.service'; describe('InstanceLoader', () => { - let loader: InstanceLoader; - let container: NestContainer; - let mockContainer: sinon.SinonMock; - - @Controller('') - class TestRoute {} - - @Component() - class TestComponent {} - - before(() => Logger.setMode(NestEnvironment.TEST)); - - beforeEach(() => { - container = new NestContainer(); - loader = new InstanceLoader(container); - mockContainer = sinon.mock(container); - }); - - it('should call "loadPrototypeOfInstance" for each component and route in each module', async () => { - const injector = new Injector(); - (loader as any).injector = injector; - - const module = { - components: new Map(), - routes: new Map(), - injectables: new Map(), - metatype: { name: 'test' }, - }; - const componentWrapper = { instance: null, metatype: TestComponent }; - const routeWrapper = { instance: null, metatype: TestRoute }; - - module.components.set('TestComponent', componentWrapper); - module.routes.set('TestRoute', routeWrapper); - - const modules = new Map(); - modules.set('Test', module); - mockContainer.expects('getModules').returns(modules); - - const loadComponentPrototypeStub = sinon.stub(injector, 'loadPrototypeOfInstance'); - - sinon.stub(injector, 'loadInstanceOfRoute'); - sinon.stub(injector, 'loadInstanceOfComponent'); - - await loader.createInstancesOfDependencies(); - expect(loadComponentPrototypeStub.calledWith(componentWrapper, module.components)).to.be.true; - expect(loadComponentPrototypeStub.calledWith(routeWrapper, module.components)).to.be.true; - }); - - it('should call "loadInstanceOfComponent" for each component in each module', async () => { - const injector = new Injector(); - (loader as any).injector = injector; - - const module = { - components: new Map(), - routes: new Map(), - injectables: new Map(), - metatype: { name: 'test' }, - }; - const testComp = { instance: null, metatype: TestComponent, name: 'TestComponent' }; - - module.components.set('TestComponent', testComp); - - const modules = new Map(); - modules.set('Test', module); - mockContainer.expects('getModules').returns(modules); - - const loadComponentStub = sinon.stub(injector, 'loadInstanceOfComponent'); - sinon.stub(injector, 'loadInstanceOfRoute'); - - await loader.createInstancesOfDependencies(); - expect(loadComponentStub.calledWith(module.components.get('TestComponent'), module)).to.be.true; - }); - - it('should call "loadInstanceOfRoute" for each route in each module', async () => { - const injector = new Injector(); - (loader as any).injector = injector; - - const module = { - components: new Map(), - routes: new Map(), - injectables: new Map(), - metatype: { name: 'test' }, - }; - const wrapper = { name: 'TestRoute', instance: null, metatype: TestRoute }; - module.routes.set('TestRoute', wrapper); - - const modules = new Map(); - modules.set('Test', module); - mockContainer.expects('getModules').returns(modules); - - sinon.stub(injector, 'loadInstanceOfComponent'); - const loadRoutesStub = sinon.stub(injector, 'loadInstanceOfRoute'); - - await loader.createInstancesOfDependencies(); - expect(loadRoutesStub.calledWith(module.routes.get('TestRoute'), module)).to.be.true; - }); - - it('should call "loadInstanceOfInjectable" for each injectable in each module', async () => { - const injector = new Injector(); - (loader as any).injector = injector; - - const module = { - components: new Map(), - routes: new Map(), - injectables: new Map(), - metatype: { name: 'test' }, - }; - const testComp = { instance: null, metatype: TestComponent, name: 'TestComponent' }; - module.injectables.set('TestComponent', testComp); - - const modules = new Map(); - modules.set('Test', module); - mockContainer.expects('getModules').returns(modules); - - const loadInjectableStub = sinon.stub(injector, 'loadInstanceOfInjectable'); - sinon.stub(injector, 'loadInstanceOfRoute'); - - await loader.createInstancesOfDependencies(); - expect(loadInjectableStub.calledWith(module.injectables.get('TestComponent'), module)).to.be.true; - }); -}); \ No newline at end of file + let loader: InstanceLoader; + let container: NestContainer; + let mockContainer: sinon.SinonMock; + + @Controller('') + class TestRoute {} + + @Component() + class TestComponent {} + + before(() => Logger.setMode(NestEnvironment.TEST)); + + beforeEach(() => { + container = new NestContainer(); + loader = new InstanceLoader(container); + mockContainer = sinon.mock(container); + }); + + it('should call "loadPrototypeOfInstance" for each component and route in each module', async () => { + const injector = new Injector(); + (loader as any).injector = injector; + + const module = { + components: new Map(), + routes: new Map(), + injectables: new Map(), + metatype: { name: 'test' } + }; + const componentWrapper = { instance: null, metatype: TestComponent }; + const routeWrapper = { instance: null, metatype: TestRoute }; + + module.components.set('TestComponent', componentWrapper); + module.routes.set('TestRoute', routeWrapper); + + const modules = new Map(); + modules.set('Test', module); + mockContainer.expects('getModules').returns(modules); + + const loadComponentPrototypeStub = sinon.stub( + injector, + 'loadPrototypeOfInstance' + ); + + sinon.stub(injector, 'loadInstanceOfRoute'); + sinon.stub(injector, 'loadInstanceOfComponent'); + + await loader.createInstancesOfDependencies(); + expect( + loadComponentPrototypeStub.calledWith(componentWrapper, module.components) + ).to.be.true; + expect( + loadComponentPrototypeStub.calledWith(routeWrapper, module.components) + ).to.be.true; + }); + + it('should call "loadInstanceOfComponent" for each component in each module', async () => { + const injector = new Injector(); + (loader as any).injector = injector; + + const module = { + components: new Map(), + routes: new Map(), + injectables: new Map(), + metatype: { name: 'test' } + }; + const testComp = { + instance: null, + metatype: TestComponent, + name: 'TestComponent' + }; + + module.components.set('TestComponent', testComp); + + const modules = new Map(); + modules.set('Test', module); + mockContainer.expects('getModules').returns(modules); + + const loadComponentStub = sinon.stub(injector, 'loadInstanceOfComponent'); + sinon.stub(injector, 'loadInstanceOfRoute'); + + await loader.createInstancesOfDependencies(); + expect( + loadComponentStub.calledWith( + module.components.get('TestComponent'), + module + ) + ).to.be.true; + }); + + it('should call "loadInstanceOfRoute" for each route in each module', async () => { + const injector = new Injector(); + (loader as any).injector = injector; + + const module = { + components: new Map(), + routes: new Map(), + injectables: new Map(), + metatype: { name: 'test' } + }; + const wrapper = { name: 'TestRoute', instance: null, metatype: TestRoute }; + module.routes.set('TestRoute', wrapper); + + const modules = new Map(); + modules.set('Test', module); + mockContainer.expects('getModules').returns(modules); + + sinon.stub(injector, 'loadInstanceOfComponent'); + const loadRoutesStub = sinon.stub(injector, 'loadInstanceOfRoute'); + + await loader.createInstancesOfDependencies(); + expect(loadRoutesStub.calledWith(module.routes.get('TestRoute'), module)).to + .be.true; + }); + + it('should call "loadInstanceOfInjectable" for each injectable in each module', async () => { + const injector = new Injector(); + (loader as any).injector = injector; + + const module = { + components: new Map(), + routes: new Map(), + injectables: new Map(), + metatype: { name: 'test' } + }; + const testComp = { + instance: null, + metatype: TestComponent, + name: 'TestComponent' + }; + module.injectables.set('TestComponent', testComp); + + const modules = new Map(); + modules.set('Test', module); + mockContainer.expects('getModules').returns(modules); + + const loadInjectableStub = sinon.stub(injector, 'loadInstanceOfInjectable'); + sinon.stub(injector, 'loadInstanceOfRoute'); + + await loader.createInstancesOfDependencies(); + expect( + loadInjectableStub.calledWith( + module.injectables.get('TestComponent'), + module + ) + ).to.be.true; + }); +}); diff --git a/src/core/test/injector/module-token-factory.spec.ts b/src/core/test/injector/module-token-factory.spec.ts index a90b75ec44a..12f31da547c 100644 --- a/src/core/test/injector/module-token-factory.spec.ts +++ b/src/core/test/injector/module-token-factory.spec.ts @@ -4,78 +4,84 @@ import { ModuleTokenFactory } from '../../injector/module-token-factory'; import { Shared, SingleScope } from '../../../index'; describe('ModuleTokenFactory', () => { - let factory: ModuleTokenFactory; - beforeEach(() => { - factory = new ModuleTokenFactory(); + let factory: ModuleTokenFactory; + beforeEach(() => { + factory = new ModuleTokenFactory(); + }); + describe('create', () => { + class Module {} + it('should force global scope when it is not set', () => { + const scope = 'global'; + const token = factory.create(Module as any, [Module as any], undefined); + expect(token).to.be.deep.eq( + JSON.stringify({ + module: Module.name, + dynamic: '', + scope + }) + ); + }); + it('should returns expected token', () => { + const token = factory.create( + SingleScope()(Module) as any, + [Module as any], + undefined + ); + expect(token).to.be.deep.eq( + JSON.stringify({ + module: Module.name, + dynamic: '', + scope: [Module.name] + }) + ); }); - describe('create', () => { - class Module {} - it('should force global scope when it is not set', () => { - const scope = 'global'; - const token = factory.create( - Module as any, - [Module as any], - undefined, - ); - expect(token).to.be.deep.eq(JSON.stringify({ - module: Module.name, - dynamic: '', - scope, - })); - }); - it('should returns expected token', () => { - const token = factory.create( - SingleScope()(Module) as any, - [Module as any], - undefined, - ); - expect(token).to.be.deep.eq(JSON.stringify({ - module: Module.name, - dynamic: '', - scope: [Module.name], - })); - }); - it('should include dynamic metadata', () => { - const token = factory.create( - SingleScope()(Module) as any, - [Module as any], - { - components: [{}], - } as any, - ); - expect(token).to.be.deep.eq(JSON.stringify({ - module: Module.name, - dynamic: JSON.stringify({ - components: [{}], - }), - scope: [Module.name], - })); - }); + it('should include dynamic metadata', () => { + const token = factory.create( + SingleScope()(Module) as any, + [Module as any], + { + components: [{}] + } as any + ); + expect(token).to.be.deep.eq( + JSON.stringify({ + module: Module.name, + dynamic: JSON.stringify({ + components: [{}] + }), + scope: [Module.name] + }) + ); }); - describe('getModuleName', () => { - it('should map module metatype to name', () => { - const metatype = () => {}; - expect(factory.getModuleName(metatype as any)).to.be.eql(metatype.name); - }); + }); + describe('getModuleName', () => { + it('should map module metatype to name', () => { + const metatype = () => {}; + expect(factory.getModuleName(metatype as any)).to.be.eql(metatype.name); }); - describe('getDynamicMetadataToken', () => { - describe('when metadata exists', () => { - it('should return stringified metadata', () => { - const metadata = { components: ['', {}]}; - expect(factory.getDynamicMetadataToken(metadata)).to.be.eql(JSON.stringify(metadata)); - }); + }); + describe('getDynamicMetadataToken', () => { + describe('when metadata exists', () => { + it('should return stringified metadata', () => { + const metadata = { components: ['', {}] }; + expect(factory.getDynamicMetadataToken(metadata)).to.be.eql( + JSON.stringify(metadata) + ); }); - describe('when metadata does not exist', () => { - it('should return empty string', () => { - expect(factory.getDynamicMetadataToken(undefined)).to.be.eql(''); - }); + }); + describe('when metadata does not exist', () => { + it('should return empty string', () => { + expect(factory.getDynamicMetadataToken(undefined)).to.be.eql(''); }); + }); }); - describe('getScopeStack', () => { - it('should map metatypes to the array with last metatype', () => { - const metatype1 = () => {}; - const metatype2 = () => {}; - expect(factory.getScopeStack([metatype1 as any, metatype2 as any])).to.be.eql([metatype2.name]); - }); + describe('getScopeStack', () => { + it('should map metatypes to the array with last metatype', () => { + const metatype1 = () => {}; + const metatype2 = () => {}; + expect( + factory.getScopeStack([metatype1 as any, metatype2 as any]) + ).to.be.eql([metatype2.name]); }); -}); \ No newline at end of file + }); +}); diff --git a/src/core/test/injector/module.spec.ts b/src/core/test/injector/module.spec.ts index e85a5426c4e..5522786217c 100644 --- a/src/core/test/injector/module.spec.ts +++ b/src/core/test/injector/module.spec.ts @@ -8,273 +8,294 @@ import { RuntimeException } from '../../errors/exceptions/runtime.exception'; import { NestContainer } from '../../injector/container'; describe('Module', () => { - let module: Module; - - @ModuleDecorator({}) class TestModule {} - @Component() class TestComponent {} - - beforeEach(() => { - module = new Module(TestModule as any, [], new NestContainer()); + let module: Module; + + @ModuleDecorator({}) + class TestModule {} + @Component() + class TestComponent {} + + beforeEach(() => { + module = new Module(TestModule as any, [], new NestContainer()); + }); + + it('should add route', () => { + const collection = new Map(); + const setSpy = sinon.spy(collection, 'set'); + (module as any)._routes = collection; + + class Test {} + module.addRoute(Test); + expect(setSpy.getCall(0).args).to.deep.equal([ + 'Test', + { + name: 'Test', + metatype: Test, + instance: null, + isResolved: false + } + ]); + }); + + it('should add injectable', () => { + const collection = new Map(); + const setSpy = sinon.spy(collection, 'set'); + (module as any)._injectables = collection; + + module.addInjectable(TestComponent); + expect(setSpy.getCall(0).args).to.deep.equal([ + 'TestComponent', + { + name: 'TestComponent', + metatype: TestComponent, + instance: null, + isResolved: false + } + ]); + }); + + describe('when injectable is custom provided', () => { + it('should call `addCustomProvider`', () => { + const addCustomProviderSpy = sinon.spy(module, 'addCustomProvider'); + + module.addInjectable({ provide: 'test' } as any); + expect(addCustomProviderSpy.called).to.be.true; }); + }); - it('should add route', () => { - const collection = new Map(); - const setSpy = sinon.spy(collection, 'set'); - (module as any)._routes = collection; - - class Test {} - module.addRoute(Test); - expect(setSpy.getCall(0).args).to.deep.equal([ 'Test', { - name: 'Test', - metatype: Test, - instance: null, - isResolved: false, - }]); - }); + it('should add component', () => { + const collection = new Map(); + const setSpy = sinon.spy(collection, 'set'); + (module as any)._components = collection; - it('should add injectable', () => { - const collection = new Map(); - const setSpy = sinon.spy(collection, 'set'); - (module as any)._injectables = collection; - - module.addInjectable(TestComponent); - expect(setSpy.getCall(0).args).to.deep.equal([ 'TestComponent', { - name: 'TestComponent', - metatype: TestComponent, - instance: null, - isResolved: false, - }]); - }); + module.addComponent(TestComponent); + expect(setSpy.getCall(0).args).to.deep.equal([ + 'TestComponent', + { + name: 'TestComponent', + metatype: TestComponent, + instance: null, + isResolved: false + } + ]); + }); - describe('when injectable is custom provided', () => { - it('should call `addCustomProvider`', () => { - const addCustomProviderSpy = sinon.spy(module, 'addCustomProvider'); + it('should call "addCustomProvider" when "provide" property exists', () => { + const addCustomProvider = sinon.spy(); + module.addCustomProvider = addCustomProvider; - module.addInjectable({ provide: 'test' } as any); - expect(addCustomProviderSpy.called).to.be.true; - }); - }); + const provider = { provide: 'test', useValue: 'test' }; - it('should add component', () => { - const collection = new Map(); - const setSpy = sinon.spy(collection, 'set'); - (module as any)._components = collection; - - module.addComponent(TestComponent); - expect(setSpy.getCall(0).args).to.deep.equal([ 'TestComponent', { - name: 'TestComponent', - metatype: TestComponent, - instance: null, - isResolved: false, - }]); - }); + module.addComponent(provider as any); + expect((addCustomProvider as sinon.SinonSpy).called).to.be.true; + }); - it('should call "addCustomProvider" when "provide" property exists', () => { - const addCustomProvider = sinon.spy(); - module.addCustomProvider = addCustomProvider; + it('should call "addCustomClass" when "useClass" property exists', () => { + const addCustomClass = sinon.spy(); + module.addCustomClass = addCustomClass; - const provider = { provide: 'test', useValue: 'test' }; + const provider = { provide: 'test', useClass: () => null }; - module.addComponent(provider as any); - expect((addCustomProvider as sinon.SinonSpy).called).to.be.true; - }); + module.addCustomProvider(provider as any, new Map()); + expect((addCustomClass as sinon.SinonSpy).called).to.be.true; + }); - it('should call "addCustomClass" when "useClass" property exists', () => { - const addCustomClass = sinon.spy(); - module.addCustomClass = addCustomClass; + it('should call "addCustomValue" when "useValue" property exists', () => { + const addCustomValue = sinon.spy(); + module.addCustomValue = addCustomValue; - const provider = { provide: 'test', useClass: () => null }; + const provider = { provide: 'test', useValue: () => null }; - module.addCustomProvider(provider as any, new Map()); - expect((addCustomClass as sinon.SinonSpy).called).to.be.true; - }); + module.addCustomProvider(provider as any, new Map()); + expect((addCustomValue as sinon.SinonSpy).called).to.be.true; + }); - it('should call "addCustomValue" when "useValue" property exists', () => { - const addCustomValue = sinon.spy(); - module.addCustomValue = addCustomValue; + it('should call "addCustomFactory" when "useFactory" property exists', () => { + const addCustomFactory = sinon.spy(); + module.addCustomFactory = addCustomFactory; - const provider = { provide: 'test', useValue: () => null }; + const provider = { provide: 'test', useFactory: () => null }; - module.addCustomProvider(provider as any, new Map()); - expect((addCustomValue as sinon.SinonSpy).called).to.be.true; - }); + module.addCustomProvider(provider as any, new Map()); + expect((addCustomFactory as sinon.SinonSpy).called).to.be.true; + }); - it('should call "addCustomFactory" when "useFactory" property exists', () => { - const addCustomFactory = sinon.spy(); - module.addCustomFactory = addCustomFactory; + describe('addCustomClass', () => { + const type = { name: 'TypeTest' }; + const component = { provide: type, useClass: type, name: 'test' }; + let setSpy; + beforeEach(() => { + const collection = new Map(); + setSpy = sinon.spy(collection, 'set'); + (module as any)._components = collection; + }); + it('should store component', () => { + module.addCustomClass(component as any, (module as any)._components); + expect( + setSpy.calledWith(component.name, { + name: component.name, + metatype: type, + instance: null, + isResolved: false + }) + ).to.be.true; + }); + }); - const provider = { provide: 'test', useFactory: () => null }; + describe('addCustomValue', () => { + let setSpy; + const value = () => ({}); + const name = 'test'; + const component = { provide: value, name, useValue: value }; - module.addCustomProvider(provider as any, new Map()); - expect((addCustomFactory as sinon.SinonSpy).called).to.be.true; + beforeEach(() => { + const collection = new Map(); + setSpy = sinon.spy(collection, 'set'); + (module as any)._components = collection; }); - describe('addCustomClass', () => { - const type = { name: 'TypeTest' }; - const component = { provide: type, useClass: type, name: 'test' }; - let setSpy; - beforeEach(() => { - const collection = new Map(); - setSpy = sinon.spy(collection, 'set'); - (module as any)._components = collection; - }); - it('should store component', () => { - module.addCustomClass(component as any, (module as any)._components); - expect(setSpy.calledWith(component.name, { - name: component.name, - metatype: type, - instance: null, - isResolved: false, - })).to.be.true; - }); + it('should store component', () => { + module.addCustomValue(component as any, (module as any)._components); + expect( + setSpy.calledWith(name, { + name, + metatype: null, + instance: value, + isResolved: true, + isNotMetatype: true, + async: false + }) + ).to.be.true; }); + }); - describe('addCustomValue', () => { - let setSpy; - const value = () => ({}); - const name = 'test'; - const component = { provide: value, name, useValue: value }; - - beforeEach(() => { - const collection = new Map(); - setSpy = sinon.spy(collection, 'set'); - (module as any)._components = collection; - }); - - it('should store component', () => { - module.addCustomValue(component as any, (module as any)._components); - expect(setSpy.calledWith(name, { - name, - metatype: null, - instance: value, - isResolved: true, - isNotMetatype: true, - async: false, - })).to.be.true; - }); - }); + describe('addCustomFactory', () => { + const type = { name: 'TypeTest' }; + const inject = [1, 2, 3]; + const component = { provide: type, useFactory: type, name: 'test', inject }; - describe('addCustomFactory', () => { - const type = { name: 'TypeTest' }; - const inject = [1, 2, 3]; - const component = { provide: type, useFactory: type, name: 'test', inject }; - - let setSpy; - beforeEach(() => { - const collection = new Map(); - setSpy = sinon.spy(collection, 'set'); - (module as any)._components = collection; - }); - it('should store component', () => { - module.addCustomFactory(component as any, (module as any)._components); - expect(setSpy.getCall(0).args).to.deep.equal([component.name, { - name: component.name, - metatype: type, - instance: null, - isResolved: false, - inject, - isNotMetatype: true, - }]); - }); + let setSpy; + beforeEach(() => { + const collection = new Map(); + setSpy = sinon.spy(collection, 'set'); + (module as any)._components = collection; }); + it('should store component', () => { + module.addCustomFactory(component as any, (module as any)._components); + expect(setSpy.getCall(0).args).to.deep.equal([ + component.name, + { + name: component.name, + metatype: type, + instance: null, + isResolved: false, + inject, + isNotMetatype: true + } + ]); + }); + }); - describe('when get instance', () => { - describe('when metatype does not exists in components collection', () => { - beforeEach(() => { - sinon.stub((module as any)._components, 'has').returns(false); - }); - it('should throws RuntimeException', () => { - expect(() => module.instance).to.throws(RuntimeException); - }); - }); - describe('when metatype exists in components collection', () => { - it('should returns null', () => { - expect(module.instance).to.be.eql(null); - }); - }); + describe('when get instance', () => { + describe('when metatype does not exists in components collection', () => { + beforeEach(() => { + sinon.stub((module as any)._components, 'has').returns(false); + }); + it('should throws RuntimeException', () => { + expect(() => module.instance).to.throws(RuntimeException); + }); }); + describe('when metatype exists in components collection', () => { + it('should returns null', () => { + expect(module.instance).to.be.eql(null); + }); + }); + }); - describe('when exported component is custom provided', () => { - it('should call `addCustomExportedComponent`', () => { - const addCustomExportedComponentSpy = sinon.spy(module, 'addCustomExportedComponent'); + describe('when exported component is custom provided', () => { + it('should call `addCustomExportedComponent`', () => { + const addCustomExportedComponentSpy = sinon.spy( + module, + 'addCustomExportedComponent' + ); - module.addExportedComponent({ provide: 'test' } as any); - expect(addCustomExportedComponentSpy.called).to.be.true; - }); + module.addExportedComponent({ provide: 'test' } as any); + expect(addCustomExportedComponentSpy.called).to.be.true; }); - - describe('replace', () => { - describe('when component', () => { - it('should call `addComponent`', () => { - const addComponentSpy = sinon.spy(module, 'addComponent'); - module.replace(null, { isComponent: true }); - expect(addComponentSpy.called).to.be.true; - }); - }); - describe('when guard', () => { - it('should call `addInjectable`', () => { - const addInjectableSpy = sinon.spy(module, 'addInjectable'); - module.replace(null, {}); - expect(addInjectableSpy.called).to.be.true; - }); - }); + }); + + describe('replace', () => { + describe('when component', () => { + it('should call `addComponent`', () => { + const addComponentSpy = sinon.spy(module, 'addComponent'); + module.replace(null, { isComponent: true }); + expect(addComponentSpy.called).to.be.true; + }); }); - - describe('relatedModules', () => { - it('should return relatedModules', () => { - const test = ['test']; - (module as any)._relatedModules = test; - expect(module.relatedModules).to.be.eql(test); + describe('when guard', () => { + it('should call `addInjectable`', () => { + const addInjectableSpy = sinon.spy(module, 'addInjectable'); + module.replace(null, {}); + expect(addInjectableSpy.called).to.be.true; }); }); + }); - describe('injectables', () => { - it('should return injectables', () => { - const test = ['test']; - (module as any)._injectables = test; - expect(module.injectables).to.be.eql(test); - }); + describe('relatedModules', () => { + it('should return relatedModules', () => { + const test = ['test']; + (module as any)._relatedModules = test; + expect(module.relatedModules).to.be.eql(test); }); + }); - describe('routes', () => { - it('should return routes', () => { - const test = ['test']; - (module as any)._routes = test; - expect(module.routes).to.be.eql(test); - }); + describe('injectables', () => { + it('should return injectables', () => { + const test = ['test']; + (module as any)._injectables = test; + expect(module.injectables).to.be.eql(test); }); + }); - describe('exports', () => { - it('should return exports', () => { - const test = ['test']; - (module as any)._exports = test; - expect(module.exports).to.be.eql(test); - }); + describe('routes', () => { + it('should return routes', () => { + const test = ['test']; + (module as any)._routes = test; + expect(module.routes).to.be.eql(test); }); + }); - describe('createModuleRefMetatype', () => { - let components: Map; - let moduleRef; + describe('exports', () => { + it('should return exports', () => { + const test = ['test']; + (module as any)._exports = test; + expect(module.exports).to.be.eql(test); + }); + }); - beforeEach(() => { - components = new Map(); + describe('createModuleRefMetatype', () => { + let components: Map; + let moduleRef; - const Class = module.createModuleRefMetatype(components); - moduleRef = new Class(); - }); + beforeEach(() => { + components = new Map(); + + const Class = module.createModuleRefMetatype(components); + moduleRef = new Class(); + }); - it('should return metatype with "get" method', () => { - expect(!!moduleRef.get).to.be.true; + it('should return metatype with "get" method', () => { + expect(!!moduleRef.get).to.be.true; + }); + describe('get', () => { + it('should return component if exists', () => { + const comp = { instance: [] }; + components.set('comp', comp); + expect(moduleRef.get('comp')).to.be.eql(comp.instance); }); - describe('get', () => { - it('should return component if exists', () => { - const comp = { instance: [] }; - components.set('comp', comp); - expect(moduleRef.get('comp')).to.be.eql(comp.instance); - }); - it('should return null if not exists', () => { - expect(moduleRef.get('fail')).to.be.null; - }); + it('should return null if not exists', () => { + expect(moduleRef.get('fail')).to.be.null; }); }); -}); \ No newline at end of file + }); +}); diff --git a/src/core/test/interceptors/interceptors-consumer.spec.ts b/src/core/test/interceptors/interceptors-consumer.spec.ts index 10d4f62dd35..2eaf4e08b10 100644 --- a/src/core/test/interceptors/interceptors-consumer.spec.ts +++ b/src/core/test/interceptors/interceptors-consumer.spec.ts @@ -6,77 +6,94 @@ import 'rxjs/add/observable/of'; import 'rxjs/add/operator/toPromise'; describe('InterceptorsConsumer', () => { - let consumer: InterceptorsConsumer; - let interceptors: any[]; - beforeEach(() => { - consumer = new InterceptorsConsumer(); - interceptors = [{ - intercept: sinon.stub().returns(Observable.of(true)), - }, { - intercept: sinon.stub().returns(Observable.of(true)), - }]; + let consumer: InterceptorsConsumer; + let interceptors: any[]; + beforeEach(() => { + consumer = new InterceptorsConsumer(); + interceptors = [ + { + intercept: sinon.stub().returns(Observable.of(true)) + }, + { + intercept: sinon.stub().returns(Observable.of(true)) + } + ]; + }); + describe('intercept', () => { + describe('when interceptors array is empty', () => { + let next: sinon.SinonSpy; + beforeEach(() => { + next = sinon.spy(); + }); + it('should call next()', async () => { + await consumer.intercept([], null, { constructor: null }, null, next); + expect(next.calledOnce).to.be.true; + }); }); - describe('intercept', () => { - describe('when interceptors array is empty', () => { - let next: sinon.SinonSpy; - beforeEach(() => { - next = sinon.spy(); - }); - it('should call next()', async () => { - await consumer.intercept([], null, { constructor: null }, null, next); - expect(next.calledOnce).to.be.true; - }); - }); - describe('when interceptors array is not empty', () => { - let next: sinon.SinonSpy; - beforeEach(() => { - next = sinon.spy(); - }); - it('should call every `intercept` method', async () => { - await consumer.intercept(interceptors, null, { constructor: null }, null, next); + describe('when interceptors array is not empty', () => { + let next: sinon.SinonSpy; + beforeEach(() => { + next = sinon.spy(); + }); + it('should call every `intercept` method', async () => { + await consumer.intercept( + interceptors, + null, + { constructor: null }, + null, + next + ); - expect(interceptors[0].intercept.calledOnce).to.be.true; - expect(interceptors[1].intercept.calledOnce).to.be.true; - }); - it('should not call `next` (lazy evaluation)', async () => { - await consumer.intercept(interceptors, null, { constructor: null }, null, next); - expect(next.called).to.be.false; - }); - }); + expect(interceptors[0].intercept.calledOnce).to.be.true; + expect(interceptors[1].intercept.calledOnce).to.be.true; + }); + it('should not call `next` (lazy evaluation)', async () => { + await consumer.intercept( + interceptors, + null, + { constructor: null }, + null, + next + ); + expect(next.called).to.be.false; + }); }); - describe('createContext', () => { - it('should returns execution context object', () => { - const instance = { constructor: {}}; - const callback = () => null; - const context = consumer.createContext(instance, callback); + }); + describe('createContext', () => { + it('should returns execution context object', () => { + const instance = { constructor: {} }; + const callback = () => null; + const context = consumer.createContext(instance, callback); - expect(context).to.be.eql({ - parent: instance.constructor, - handler: callback, - }); - }); + expect(context).to.be.eql({ + parent: instance.constructor, + handler: callback + }); }); - describe('transformDeffered', () => { - describe('when next() result is plain value', () => { - it('should return Promise', async () => { - const val = 3; - const next = () => val; - expect(await consumer.transformDeffered(next)).to.be.eql(val); - }); + }); + describe('transformDeffered', () => { + describe('when next() result is plain value', () => { + it('should return Promise', async () => { + const val = 3; + const next = () => val; + expect(await consumer.transformDeffered(next)).to.be.eql(val); }); - describe('when next() result is Promise', () => { - it('should return Promise', async () => { - const val = 3; - const next = () => Promise.resolve(val); - expect(await consumer.transformDeffered(next)).to.be.eql(val); - }); + }); + describe('when next() result is Promise', () => { + it('should return Promise', async () => { + const val = 3; + const next = () => Promise.resolve(val); + expect(await consumer.transformDeffered(next)).to.be.eql(val); }); - describe('when next() result is Observable', () => { - it('should return Observable', async () => { - const val = 3; - const next = () => Observable.of(val); - expect(await (consumer.transformDeffered(next) as any).toPromise()).to.be.eql(val); - }); + }); + describe('when next() result is Observable', () => { + it('should return Observable', async () => { + const val = 3; + const next = () => Observable.of(val); + expect( + await (consumer.transformDeffered(next) as any).toPromise() + ).to.be.eql(val); }); }); -}); \ No newline at end of file + }); +}); diff --git a/src/core/test/interceptors/interceptors-context-creator.spec.ts b/src/core/test/interceptors/interceptors-context-creator.spec.ts index 39d023c88ec..4634f90cfe8 100644 --- a/src/core/test/interceptors/interceptors-context-creator.spec.ts +++ b/src/core/test/interceptors/interceptors-context-creator.spec.ts @@ -5,58 +5,62 @@ import { InterceptorsContextCreator } from '../../interceptors/interceptors-cont import 'rxjs/add/observable/of'; describe('InterceptorsContextCreator', () => { - let interceptorsContextCreator: InterceptorsContextCreator; - let interceptors: any[]; - let container; - let getSpy; + let interceptorsContextCreator: InterceptorsContextCreator; + let interceptors: any[]; + let container; + let getSpy; - beforeEach(() => { - interceptors = [ - { - name: 'test', - instance: { - intercept: () => Observable.of(true), - }, - }, - { - name: 'test2', - instance: { - intercept: () => Observable.of(true), - }, - }, - {}, - undefined, - ]; - getSpy = sinon.stub().returns({ - injectables: new Map([ - ['test', interceptors[0]], - ['test2', interceptors[1]], - ]), - }); - container = { - getModules: () => ({ - get: getSpy, - }), - }; - interceptorsContextCreator = new InterceptorsContextCreator(container as any); + beforeEach(() => { + interceptors = [ + { + name: 'test', + instance: { + intercept: () => Observable.of(true) + } + }, + { + name: 'test2', + instance: { + intercept: () => Observable.of(true) + } + }, + {}, + undefined + ]; + getSpy = sinon.stub().returns({ + injectables: new Map([ + ['test', interceptors[0]], + ['test2', interceptors[1]] + ]) }); - describe('createConcreteContext', () => { - describe('when `moduleContext` is nil', () => { - it('should returns empty array', () => { - const result = interceptorsContextCreator.createConcreteContext(interceptors); - expect(result).to.be.empty; - }); - }); - describe('when `moduleContext` is defined', () => { - beforeEach(() => { - // tslint:disable-next-line:no-string-literal - interceptorsContextCreator['moduleContext'] = 'test'; - }); - it('should filter metatypes', () => { - expect( - interceptorsContextCreator.createConcreteContext(interceptors), - ).to.have.length(2); - }); - }); + container = { + getModules: () => ({ + get: getSpy + }) + }; + interceptorsContextCreator = new InterceptorsContextCreator( + container as any + ); + }); + describe('createConcreteContext', () => { + describe('when `moduleContext` is nil', () => { + it('should returns empty array', () => { + const result = interceptorsContextCreator.createConcreteContext( + interceptors + ); + expect(result).to.be.empty; + }); }); -}); \ No newline at end of file + describe('when `moduleContext` is defined', () => { + beforeEach(() => { + // tslint:disable-next-line:no-string-literal + interceptorsContextCreator['moduleContext'] = 'test'; + }); + it('should filter metatypes', () => { + expect( + interceptorsContextCreator.createConcreteContext(interceptors) + ).to.have.length(2); + }); + }); + }); +}); diff --git a/src/core/test/metadata-scanner.spec.ts b/src/core/test/metadata-scanner.spec.ts index e0ad4a0c11a..4ac5ef68698 100644 --- a/src/core/test/metadata-scanner.spec.ts +++ b/src/core/test/metadata-scanner.spec.ts @@ -2,21 +2,27 @@ import { expect } from 'chai'; import { MetadataScanner } from '../metadata-scanner'; describe('MetadataScanner', () => { - let scanner: MetadataScanner; - beforeEach(() => { - scanner = new MetadataScanner(); + let scanner: MetadataScanner; + beforeEach(() => { + scanner = new MetadataScanner(); + }); + describe('scanFromPrototype', () => { + class Test { + constructor() {} + get prop() { + return ''; + } + set val(value) {} + public test() {} + public test2() {} + } + it('should returns only methods', () => { + const methods = scanner.scanFromPrototype( + new Test(), + Test.prototype, + a => a + ); + expect(methods).to.eql(['test', 'test2']); }); - describe('scanFromPrototype', () => { - class Test { - constructor() {} - get prop() { return ''; } - set val(value) {} - public test() {} - public test2() {} - } - it('should returns only methods', () => { - const methods = scanner.scanFromPrototype(new Test(), Test.prototype, a => a); - expect(methods).to.eql(['test', 'test2']); - }); - }); -}); \ No newline at end of file + }); +}); diff --git a/src/core/test/middlewares/builder.spec.ts b/src/core/test/middlewares/builder.spec.ts index 8523fc1ce33..5ba1db99d3c 100644 --- a/src/core/test/middlewares/builder.spec.ts +++ b/src/core/test/middlewares/builder.spec.ts @@ -5,79 +5,92 @@ import { RoutesMapper } from '../../middlewares/routes-mapper'; import { Controller, Get } from '../../../index'; describe('MiddlewareBuilder', () => { - let builder: MiddlewareBuilder; + let builder: MiddlewareBuilder; + beforeEach(() => { + builder = new MiddlewareBuilder(new RoutesMapper()); + }); + describe('apply', () => { + let configProxy; beforeEach(() => { - builder = new MiddlewareBuilder(new RoutesMapper()); + configProxy = builder.apply([]); }); - describe('apply', () => { - let configProxy; - beforeEach(() => { - configProxy = builder.apply([]); - }); - it('should return configuration proxy', () => { - const metatype = (MiddlewareBuilder as any).ConfigProxy; - expect(configProxy instanceof metatype).to.be.true; - }); - describe('configuration proxy', () => { - it('should returns itself on "with()" call', () => { - expect(configProxy.with()).to.be.eq(configProxy); - }); - describe('when "forRoutes()" called', () => { - @Controller('path') - class Test { - @Get('route') - public getAll() {} - } - const route = { path: '/test', method: 0 }; - it('should store configuration passed as argument', () => { - configProxy.forRoutes(route, Test); - - expect(builder.build()).to.deep.equal([{ - middlewares: [], - forRoutes: [route, { - path: '/path/route', - method: 0, - }], - }]); - }); - }); - }); + it('should return configuration proxy', () => { + const metatype = (MiddlewareBuilder as any).ConfigProxy; + expect(configProxy instanceof metatype).to.be.true; }); - - describe('use', () => { + describe('configuration proxy', () => { + it('should returns itself on "with()" call', () => { + expect(configProxy.with()).to.be.eq(configProxy); + }); + describe('when "forRoutes()" called', () => { + @Controller('path') + class Test { + @Get('route') + public getAll() {} + } + const route = { path: '/test', method: 0 }; it('should store configuration passed as argument', () => { - builder.use({ - middlewares: 'Test', - forRoutes: 'Test', - } as any); + configProxy.forRoutes(route, Test); - expect(builder.build()).to.deep.equal([{ - middlewares: 'Test', - forRoutes: 'Test', - }]); + expect(builder.build()).to.deep.equal([ + { + middlewares: [], + forRoutes: [ + route, + { + path: '/path/route', + method: 0 + } + ] + } + ]); }); + }); + }); + }); - it('should be possible to chain "use" calls', () => { - builder.use({ - middlewares: 'Test', - forRoutes: 'Test', - } as any).use({ - middlewares: 'Test', - forRoutes: 'Test', - } as any); - expect(builder.build()).to.deep.equal([{ - middlewares: 'Test', - forRoutes: 'Test', - }, { - middlewares: 'Test', - forRoutes: 'Test', - }]); - }); + describe('use', () => { + it('should store configuration passed as argument', () => { + builder.use({ + middlewares: 'Test', + forRoutes: 'Test' + } as any); - it('should throw exception when middleware configuration object is invalid', () => { - expect(builder.use.bind(builder, 'test')).throws(InvalidMiddlewareConfigurationException); - }); + expect(builder.build()).to.deep.equal([ + { + middlewares: 'Test', + forRoutes: 'Test' + } + ]); + }); + + it('should be possible to chain "use" calls', () => { + builder + .use({ + middlewares: 'Test', + forRoutes: 'Test' + } as any) + .use({ + middlewares: 'Test', + forRoutes: 'Test' + } as any); + expect(builder.build()).to.deep.equal([ + { + middlewares: 'Test', + forRoutes: 'Test' + }, + { + middlewares: 'Test', + forRoutes: 'Test' + } + ]); + }); + it('should throw exception when middleware configuration object is invalid', () => { + expect(builder.use.bind(builder, 'test')).throws( + InvalidMiddlewareConfigurationException + ); }); -}); \ No newline at end of file + }); +}); diff --git a/src/core/test/middlewares/container.spec.ts b/src/core/test/middlewares/container.spec.ts index 4fef451c69e..f12060dbaa6 100644 --- a/src/core/test/middlewares/container.spec.ts +++ b/src/core/test/middlewares/container.spec.ts @@ -8,56 +8,53 @@ import { RequestMapping } from '../../../common/decorators/http/request-mapping. import { RequestMethod } from '../../../common/enums/request-method.enum'; describe('MiddlewaresContainer', () => { - @Controller('test') - class TestRoute { - - @RequestMapping({ path: 'test' }) - public getTest() {} - - @RequestMapping({ path: 'another', method: RequestMethod.DELETE }) - public getAnother() {} - } - - @Component() - class TestMiddleware implements NestMiddleware { - public resolve() { - return (req, res, next) => {}; - } + @Controller('test') + class TestRoute { + @RequestMapping({ path: 'test' }) + public getTest() {} + + @RequestMapping({ path: 'another', method: RequestMethod.DELETE }) + public getAnother() {} + } + + @Component() + class TestMiddleware implements NestMiddleware { + public resolve() { + return (req, res, next) => {}; } - - let container: MiddlewaresContainer; - - beforeEach(() => { - container = new MiddlewaresContainer(); + } + + let container: MiddlewaresContainer; + + beforeEach(() => { + container = new MiddlewaresContainer(); + }); + + it('should store expected configurations for given module', () => { + const config: MiddlewareConfiguration[] = [ + { + middlewares: [TestMiddleware], + forRoutes: [TestRoute, { path: 'test' }] + } + ]; + container.addConfig(config, 'Module' as any); + expect([...container.getConfigs().get('Module')]).to.deep.equal(config); + }); + + it('should store expected middlewares for given module', () => { + const config: MiddlewareConfiguration[] = [ + { + middlewares: TestMiddleware, + forRoutes: [TestRoute] + } + ]; + + const key = 'Test' as any; + container.addConfig(config, key); + expect(container.getMiddlewares(key).size).to.eql(config.length); + expect(container.getMiddlewares(key).get('TestMiddleware')).to.eql({ + instance: null, + metatype: TestMiddleware }); - - it('should store expected configurations for given module', () => { - const config: MiddlewareConfiguration[] = [{ - middlewares: [ TestMiddleware ], - forRoutes: [ - TestRoute, - { path: 'test' }, - ], - }, - ]; - container.addConfig(config, 'Module' as any); - expect([ ...container.getConfigs().get('Module') ]).to.deep.equal(config); - }); - - it('should store expected middlewares for given module', () => { - const config: MiddlewareConfiguration[] = [{ - middlewares: TestMiddleware, - forRoutes: [ TestRoute ], - }, - ]; - - const key = 'Test' as any; - container.addConfig(config, key); - expect(container.getMiddlewares(key).size).to.eql(config.length); - expect(container.getMiddlewares(key).get('TestMiddleware')).to.eql({ - instance: null, - metatype: TestMiddleware, - }); - }); - -}); \ No newline at end of file + }); +}); diff --git a/src/core/test/middlewares/middlewares-module.spec.ts b/src/core/test/middlewares/middlewares-module.spec.ts index bd42770eb92..e94f894ed89 100644 --- a/src/core/test/middlewares/middlewares-module.spec.ts +++ b/src/core/test/middlewares/middlewares-module.spec.ts @@ -12,124 +12,142 @@ import { RuntimeException } from '../../errors/exceptions/runtime.exception'; import { RoutesMapper } from '../../middlewares/routes-mapper'; import { RouterExceptionFilters } from '../../router/router-exception-filters'; import { ApplicationConfig } from '../../application-config'; -import { MiddlewaresContainer } from "../../middlewares/container"; +import { MiddlewaresContainer } from '../../middlewares/container'; describe('MiddlewaresModule', () => { - let middlewaresModule: MiddlewaresModule; + let middlewaresModule: MiddlewaresModule; - @Controller('test') - class AnotherRoute { } + @Controller('test') + class AnotherRoute {} - @Controller('test') - class TestRoute { + @Controller('test') + class TestRoute { + @RequestMapping({ path: 'test' }) + public getTest() {} - @RequestMapping({ path: 'test' }) - public getTest() {} + @RequestMapping({ path: 'another', method: RequestMethod.DELETE }) + public getAnother() {} + } - @RequestMapping({ path: 'another', method: RequestMethod.DELETE }) - public getAnother() {} + @Component() + class TestMiddleware implements NestMiddleware { + public resolve() { + return (req, res, next) => {}; } - - @Component() - class TestMiddleware implements NestMiddleware { - public resolve() { - return (req, res, next) => {}; - } - } - - beforeEach(() => { - middlewaresModule = new MiddlewaresModule(); - (middlewaresModule as any).routerExceptionFilter = new RouterExceptionFilters( - new ApplicationConfig(), - ); + } + + beforeEach(() => { + middlewaresModule = new MiddlewaresModule(); + (middlewaresModule as any).routerExceptionFilter = new RouterExceptionFilters( + new ApplicationConfig() + ); + }); + + describe('loadConfiguration', () => { + it('should call "configure" method if method is implemented', () => { + const configureSpy = sinon.spy(); + const mockModule = { + configure: configureSpy + }; + + middlewaresModule.loadConfiguration( + new MiddlewaresContainer(), + mockModule as any, + 'Test' as any + ); + + expect(configureSpy.calledOnce).to.be.true; + expect(configureSpy.calledWith(new MiddlewareBuilder(new RoutesMapper()))) + .to.be.true; }); - - describe('loadConfiguration', () => { - - it('should call "configure" method if method is implemented', () => { - const configureSpy = sinon.spy(); - const mockModule = { - configure: configureSpy, - }; - - middlewaresModule.loadConfiguration(new MiddlewaresContainer(), mockModule as any, 'Test' as any); - - expect(configureSpy.calledOnce).to.be.true; - expect(configureSpy.calledWith(new MiddlewareBuilder(new RoutesMapper()))).to.be.true; - }); + }); + + describe('setupRouteMiddleware', () => { + it('should throw "RuntimeException" exception when middlewares is not stored in container', () => { + const route = { path: 'Test' }; + const configuration = { + middlewares: [TestMiddleware], + forRoutes: [TestRoute] + }; + + const useSpy = sinon.spy(); + const app = { use: useSpy }; + + expect( + middlewaresModule.setupRouteMiddleware( + new MiddlewaresContainer(), + route as any, + configuration, + 'Test' as any, + app as any + ) + ).to.eventually.be.rejectedWith(RuntimeException); }); - describe('setupRouteMiddleware', () => { - - it('should throw "RuntimeException" exception when middlewares is not stored in container', () => { - const route = { path: 'Test' }; - const configuration = { - middlewares: [ TestMiddleware ], - forRoutes: [ TestRoute ], - }; - - const useSpy = sinon.spy(); - const app = { use: useSpy }; - - expect( - middlewaresModule.setupRouteMiddleware(new MiddlewaresContainer(), route as any, configuration, 'Test' as any, app as any), - ).to.eventually.be.rejectedWith(RuntimeException); - }); - - it('should throw "InvalidMiddlewareException" exception when middlewares does not have "resolve" method', () => { - @Component() - class InvalidMiddleware {} - - const route = { path: 'Test' }; - const configuration = { - middlewares: [ InvalidMiddleware ], - forRoutes: [ TestRoute ], - }; - - const useSpy = sinon.spy(); - const app = { use: useSpy }; - - const container = new MiddlewaresContainer(); - const moduleKey = 'Test' as any; - container.addConfig([ configuration as any ], moduleKey); - - const instance = new InvalidMiddleware(); - container.getMiddlewares(moduleKey).set('InvalidMiddleware', { - metatype: InvalidMiddleware, - instance, - } as any); - - expect( - middlewaresModule.setupRouteMiddleware(container, route as any, configuration, moduleKey, app as any), - ).to.be.rejectedWith(InvalidMiddlewareException); - }); - - it('should store middlewares when middleware is stored in container', () => { - const route = { path: 'Test', method: RequestMethod.GET }; - const configuration = { - middlewares: [ TestMiddleware ], - forRoutes: [ { path: 'test' }, AnotherRoute, TestRoute ], - }; - - const useSpy = sinon.spy(); - const app = { - get: useSpy, - }; - - const container = new MiddlewaresContainer(); - const moduleKey = 'Test' as any; - container.addConfig([ configuration ], moduleKey); - - const instance = new TestMiddleware(); - container.getMiddlewares(moduleKey).set('TestMiddleware', { - metatype: TestMiddleware, - instance, - }); - - middlewaresModule.setupRouteMiddleware(container, route, configuration, moduleKey, app as any); - expect(useSpy.calledOnce).to.be.true; - }); - + it('should throw "InvalidMiddlewareException" exception when middlewares does not have "resolve" method', () => { + @Component() + class InvalidMiddleware {} + + const route = { path: 'Test' }; + const configuration = { + middlewares: [InvalidMiddleware], + forRoutes: [TestRoute] + }; + + const useSpy = sinon.spy(); + const app = { use: useSpy }; + + const container = new MiddlewaresContainer(); + const moduleKey = 'Test' as any; + container.addConfig([configuration as any], moduleKey); + + const instance = new InvalidMiddleware(); + container.getMiddlewares(moduleKey).set('InvalidMiddleware', { + metatype: InvalidMiddleware, + instance + } as any); + + expect( + middlewaresModule.setupRouteMiddleware( + container, + route as any, + configuration, + moduleKey, + app as any + ) + ).to.be.rejectedWith(InvalidMiddlewareException); }); -}); \ No newline at end of file + it('should store middlewares when middleware is stored in container', () => { + const route = { path: 'Test', method: RequestMethod.GET }; + const configuration = { + middlewares: [TestMiddleware], + forRoutes: [{ path: 'test' }, AnotherRoute, TestRoute] + }; + + const useSpy = sinon.spy(); + const app = { + get: useSpy + }; + + const container = new MiddlewaresContainer(); + const moduleKey = 'Test' as any; + container.addConfig([configuration], moduleKey); + + const instance = new TestMiddleware(); + container.getMiddlewares(moduleKey).set('TestMiddleware', { + metatype: TestMiddleware, + instance + }); + + middlewaresModule.setupRouteMiddleware( + container, + route, + configuration, + moduleKey, + app as any + ); + expect(useSpy.calledOnce).to.be.true; + }); + }); +}); diff --git a/src/core/test/middlewares/resolver.spec.ts b/src/core/test/middlewares/resolver.spec.ts index fbdd87abd47..28ea0054e26 100644 --- a/src/core/test/middlewares/resolver.spec.ts +++ b/src/core/test/middlewares/resolver.spec.ts @@ -8,45 +8,45 @@ import { Logger } from '../../../common/services/logger.service'; import { NestEnvironment } from '../../../common/enums/nest-environment.enum'; describe('MiddlewaresResolver', () => { - @Component() - class TestMiddleware implements NestMiddleware { - public resolve() { - return (req, res, next) => {}; - } + @Component() + class TestMiddleware implements NestMiddleware { + public resolve() { + return (req, res, next) => {}; } - - let resolver: MiddlewaresResolver; - let container: MiddlewaresContainer; - let mockContainer: sinon.SinonMock; - - before(() => Logger.setMode(NestEnvironment.TEST)); - - beforeEach(() => { - container = new MiddlewaresContainer(); - resolver = new MiddlewaresResolver(container); - mockContainer = sinon.mock(container); - }); - - it('should resolve middleware instances from container', () => { - const loadInstanceOfMiddleware = sinon.stub(resolver['instanceLoader'], 'loadInstanceOfMiddleware'); - const middlewares = new Map(); - const wrapper = { - instance: { metatype: {} }, - metatype: TestMiddleware - }; - middlewares.set('TestMiddleware', wrapper); - - const module = { metatype: { name: '' }}; - mockContainer.expects('getMiddlewares').returns(middlewares); - resolver.resolveInstances(module, null); - - expect(loadInstanceOfMiddleware.callCount).to.be.equal(middlewares.size); - expect(loadInstanceOfMiddleware.calledWith( - wrapper, - middlewares, - module - )).to.be.true; - - loadInstanceOfMiddleware.restore(); - }); -}); \ No newline at end of file + } + + let resolver: MiddlewaresResolver; + let container: MiddlewaresContainer; + let mockContainer: sinon.SinonMock; + + before(() => Logger.setMode(NestEnvironment.TEST)); + + beforeEach(() => { + container = new MiddlewaresContainer(); + resolver = new MiddlewaresResolver(container); + mockContainer = sinon.mock(container); + }); + + it('should resolve middleware instances from container', () => { + const loadInstanceOfMiddleware = sinon.stub( + resolver['instanceLoader'], + 'loadInstanceOfMiddleware' + ); + const middlewares = new Map(); + const wrapper = { + instance: { metatype: {} }, + metatype: TestMiddleware + }; + middlewares.set('TestMiddleware', wrapper); + + const module = { metatype: { name: '' } }; + mockContainer.expects('getMiddlewares').returns(middlewares); + resolver.resolveInstances(module, null); + + expect(loadInstanceOfMiddleware.callCount).to.be.equal(middlewares.size); + expect(loadInstanceOfMiddleware.calledWith(wrapper, middlewares, module)).to + .be.true; + + loadInstanceOfMiddleware.restore(); + }); +}); diff --git a/src/core/test/middlewares/routes-mapper.spec.ts b/src/core/test/middlewares/routes-mapper.spec.ts index ae203d55b2e..8220e40cd60 100644 --- a/src/core/test/middlewares/routes-mapper.spec.ts +++ b/src/core/test/middlewares/routes-mapper.spec.ts @@ -6,51 +6,47 @@ import { RequestMethod } from '../../../common/enums/request-method.enum'; import { UnknownRequestMappingException } from '../../errors/exceptions/unknown-request-mapping.exception'; describe('RoutesMapper', () => { - @Controller('test') - class TestRoute { - - @RequestMapping({ path: 'test' }) - public getTest() {} - - @RequestMapping({ path: 'another', method: RequestMethod.DELETE }) - public getAnother() {} - } - - let mapper: RoutesMapper; - beforeEach(() => { - mapper = new RoutesMapper(); - }); - - it('should map @Controller() to "ControllerMetadata" in forRoutes', () => { - const config = { - middlewares: 'Test', - forRoutes: [ - { path: 'test', method: RequestMethod.GET }, - TestRoute, - ], - }; - - expect(mapper.mapRouteToRouteProps(config.forRoutes[0])).to.deep.equal([{ - path: '/test', method: RequestMethod.GET, - }]); - - expect(mapper.mapRouteToRouteProps(config.forRoutes[1])).to.deep.equal([ - { path: '/test/test', method: RequestMethod.GET }, - { path: '/test/another', method: RequestMethod.DELETE }, - ]); - }); - - it('should throw exception when invalid object was passed as route', () => { - const config = { - middlewares: 'Test', - forRoutes: [ - { method: RequestMethod.GET }, - ], - }; - - expect( - mapper.mapRouteToRouteProps.bind(mapper, config.forRoutes[0]), - ).throws(UnknownRequestMappingException); - }); - -}); \ No newline at end of file + @Controller('test') + class TestRoute { + @RequestMapping({ path: 'test' }) + public getTest() {} + + @RequestMapping({ path: 'another', method: RequestMethod.DELETE }) + public getAnother() {} + } + + let mapper: RoutesMapper; + beforeEach(() => { + mapper = new RoutesMapper(); + }); + + it('should map @Controller() to "ControllerMetadata" in forRoutes', () => { + const config = { + middlewares: 'Test', + forRoutes: [{ path: 'test', method: RequestMethod.GET }, TestRoute] + }; + + expect(mapper.mapRouteToRouteProps(config.forRoutes[0])).to.deep.equal([ + { + path: '/test', + method: RequestMethod.GET + } + ]); + + expect(mapper.mapRouteToRouteProps(config.forRoutes[1])).to.deep.equal([ + { path: '/test/test', method: RequestMethod.GET }, + { path: '/test/another', method: RequestMethod.DELETE } + ]); + }); + + it('should throw exception when invalid object was passed as route', () => { + const config = { + middlewares: 'Test', + forRoutes: [{ method: RequestMethod.GET }] + }; + + expect( + mapper.mapRouteToRouteProps.bind(mapper, config.forRoutes[0]) + ).throws(UnknownRequestMappingException); + }); +}); diff --git a/src/core/test/middlewares/utils.spec.ts b/src/core/test/middlewares/utils.spec.ts index d56566f7263..4e9c494c0bc 100644 --- a/src/core/test/middlewares/utils.spec.ts +++ b/src/core/test/middlewares/utils.spec.ts @@ -1,63 +1,66 @@ import * as sinon from 'sinon'; import { expect } from 'chai'; -import { filterMiddlewares, mapToClass, isClass, assignToken } from '../../middlewares/utils'; +import { + filterMiddlewares, + mapToClass, + isClass, + assignToken +} from '../../middlewares/utils'; describe('middleware utils', () => { - class Test {} - function fnMiddleware(req, res, next) {} + class Test {} + function fnMiddleware(req, res, next) {} - describe('filterMiddlewares', () => { - let middlewares: any[]; - beforeEach(() => { - middlewares = [Test, fnMiddleware, undefined, null]; - }); - it('should returns filtered middlewares', () => { - expect( - filterMiddlewares(middlewares), - ).to.have.length(2); - }); + describe('filterMiddlewares', () => { + let middlewares: any[]; + beforeEach(() => { + middlewares = [Test, fnMiddleware, undefined, null]; }); - describe('mapToClass', () => { - describe('when middleware is a class', () => { - it('should returns identity', () => { - const type = mapToClass(Test); - expect(type).to.eql(Test); - }); - }); - describe('when middleware is a function', () => { - it('should returns metatype', () => { - const metatype = mapToClass(fnMiddleware); - expect(metatype).to.not.eql(fnMiddleware); - }); - it('should define `resolve` method', () => { - const metatype = mapToClass(fnMiddleware); - expect(new metatype().resolve).to.exist; - }); - it('should encapsulate function', () => { - const spy = sinon.spy(); - const metatype = mapToClass(spy); - new metatype().resolve()(); - expect(spy.called).to.be.true; - }); - }); + it('should returns filtered middlewares', () => { + expect(filterMiddlewares(middlewares)).to.have.length(2); }); - describe('isClass', () => { - describe('when middleware is a class', () => { - it('should returns true', () => { - expect(isClass(Test)).to.be.true; - }); - }); - describe('when middleware is a function', () => { - it('should returns false', () => { - expect(isClass(fnMiddleware)).to.be.false; - }); - }); + }); + describe('mapToClass', () => { + describe('when middleware is a class', () => { + it('should returns identity', () => { + const type = mapToClass(Test); + expect(type).to.eql(Test); + }); }); - describe('assignToken', () => { - describe('should define `name` property on metatype', () => { - const anonymousType = class {}; - assignToken(anonymousType); - expect(anonymousType.name).to.exist; - }); + describe('when middleware is a function', () => { + it('should returns metatype', () => { + const metatype = mapToClass(fnMiddleware); + expect(metatype).to.not.eql(fnMiddleware); + }); + it('should define `resolve` method', () => { + const metatype = mapToClass(fnMiddleware); + expect(new metatype().resolve).to.exist; + }); + it('should encapsulate function', () => { + const spy = sinon.spy(); + const metatype = mapToClass(spy); + new metatype().resolve()(); + expect(spy.called).to.be.true; + }); }); -}); \ No newline at end of file + }); + describe('isClass', () => { + describe('when middleware is a class', () => { + it('should returns true', () => { + expect(isClass(Test)).to.be.true; + }); + }); + describe('when middleware is a function', () => { + it('should returns false', () => { + expect(isClass(fnMiddleware)).to.be.false; + }); + }); + }); + describe('assignToken', () => { + describe('should define `name` property on metatype', () => { + const anonymousType = class {}; + assignToken(anonymousType); + expect(anonymousType.name).to.exist; + }); + }); +}); diff --git a/src/core/test/pipes/params-token-factory.spec.ts b/src/core/test/pipes/params-token-factory.spec.ts index 21b1d718616..aeba5ebef36 100644 --- a/src/core/test/pipes/params-token-factory.spec.ts +++ b/src/core/test/pipes/params-token-factory.spec.ts @@ -3,32 +3,38 @@ import { ParamsTokenFactory } from './../../pipes/params-token-factory'; import { RouteParamtypes } from '../../../common/enums/route-paramtypes.enum'; describe('ParamsTokenFactory', () => { - let factory: ParamsTokenFactory; - beforeEach(() => { - factory = new ParamsTokenFactory(); - }); - describe('exchangeEnumForString', () => { - describe('when key is', () => { - describe(`RouteParamtypes.BODY`, () => { - it('should returns body object', () => { - expect(factory.exchangeEnumForString(RouteParamtypes.BODY)).to.be.eql('body'); - }); - }); - describe(`RouteParamtypes.QUERY`, () => { - it('should returns query object', () => { - expect(factory.exchangeEnumForString(RouteParamtypes.QUERY)).to.be.eql('query'); - }); - }); - describe(`RouteParamtypes.PARAM`, () => { - it('should returns params object', () => { - expect(factory.exchangeEnumForString(RouteParamtypes.PARAM)).to.be.eql('param'); - }); - }); - describe('not available', () => { - it('should returns "custom"', () => { - expect(factory.exchangeEnumForString(-1)).to.be.eql('custom'); - }); - }); + let factory: ParamsTokenFactory; + beforeEach(() => { + factory = new ParamsTokenFactory(); + }); + describe('exchangeEnumForString', () => { + describe('when key is', () => { + describe(`RouteParamtypes.BODY`, () => { + it('should returns body object', () => { + expect(factory.exchangeEnumForString(RouteParamtypes.BODY)).to.be.eql( + 'body' + ); + }); + }); + describe(`RouteParamtypes.QUERY`, () => { + it('should returns query object', () => { + expect( + factory.exchangeEnumForString(RouteParamtypes.QUERY) + ).to.be.eql('query'); + }); + }); + describe(`RouteParamtypes.PARAM`, () => { + it('should returns params object', () => { + expect( + factory.exchangeEnumForString(RouteParamtypes.PARAM) + ).to.be.eql('param'); + }); + }); + describe('not available', () => { + it('should returns "custom"', () => { + expect(factory.exchangeEnumForString(-1)).to.be.eql('custom'); }); + }); }); -}); \ No newline at end of file + }); +}); diff --git a/src/core/test/pipes/pipes-consumer.spec.ts b/src/core/test/pipes/pipes-consumer.spec.ts index ad439dc52ae..33ab95dc566 100644 --- a/src/core/test/pipes/pipes-consumer.spec.ts +++ b/src/core/test/pipes/pipes-consumer.spec.ts @@ -4,36 +4,38 @@ import { PipesConsumer } from './../../pipes/pipes-consumer'; import { RouteParamtypes } from './../../../common/enums/route-paramtypes.enum'; describe('PipesConsumer', () => { - let consumer: PipesConsumer; + let consumer: PipesConsumer; + beforeEach(() => { + consumer = new PipesConsumer(); + }); + describe('apply', () => { + let value, metatype, type, stringifiedType, transforms, data; beforeEach(() => { - consumer = new PipesConsumer(); + value = 0; + data = null; + (metatype = {}), (type = RouteParamtypes.QUERY); + stringifiedType = 'query'; + transforms = [ + sinon.stub().callsFake(val => val + 1), + sinon.stub().callsFake(val => Promise.resolve(val + 1)), + sinon.stub().callsFake(val => val + 1) + ]; }); - describe('apply', () => { - let value, metatype, type, stringifiedType, transforms, data; - beforeEach(() => { - value = 0; - data = null; - metatype = {}, - type = RouteParamtypes.QUERY; - stringifiedType = 'query'; - transforms = [ - sinon.stub().callsFake((val) => val + 1), - sinon.stub().callsFake((val) => Promise.resolve(val + 1)), - sinon.stub().callsFake((val) => val + 1), - ]; - }); - it('should call all transform functions', (done) => { - consumer.apply(value, { metatype, type, data }, transforms).then(() => { - expect(transforms.reduce((prev, next) => prev && next.called, true)).to.be.true; - done(); - }); - }); - it('should returns expected result', (done) => { - const expectedResult = 3; - consumer.apply(value, { metatype, type, data }, transforms).then((result) => { - expect(result).to.be.eql(expectedResult); - done(); - }); + it('should call all transform functions', done => { + consumer.apply(value, { metatype, type, data }, transforms).then(() => { + expect(transforms.reduce((prev, next) => prev && next.called, true)).to + .be.true; + done(); + }); + }); + it('should returns expected result', done => { + const expectedResult = 3; + consumer + .apply(value, { metatype, type, data }, transforms) + .then(result => { + expect(result).to.be.eql(expectedResult); + done(); }); }); -}); \ No newline at end of file + }); +}); diff --git a/src/core/test/pipes/pipes-context-creator.spec.ts b/src/core/test/pipes/pipes-context-creator.spec.ts index b0ee7342533..e8737e49dc3 100644 --- a/src/core/test/pipes/pipes-context-creator.spec.ts +++ b/src/core/test/pipes/pipes-context-creator.spec.ts @@ -3,27 +3,23 @@ import { expect } from 'chai'; import { PipesContextCreator } from './../../pipes/pipes-context-creator'; describe('PipesContextCreator', () => { - let creator: PipesContextCreator; - beforeEach(() => { - creator = new PipesContextCreator(null); + let creator: PipesContextCreator; + beforeEach(() => { + creator = new PipesContextCreator(null); + }); + describe('createConcreteContext', () => { + describe('when metadata is empty or undefined', () => { + it('should returns empty array', () => { + expect(creator.createConcreteContext(undefined)).to.be.deep.equal([]); + expect(creator.createConcreteContext([])).to.be.deep.equal([]); + }); }); - describe('createConcreteContext', () => { - describe('when metadata is empty or undefined', () => { - it('should returns empty array', () => { - expect(creator.createConcreteContext(undefined)).to.be.deep.equal([]); - expect(creator.createConcreteContext([])).to.be.deep.equal([]); - }); - }); - describe('when metadata is not empty or undefined', () => { - const metadata = [ - null, - {}, - { transform: () => ({}) }, - ]; - it('should returns expected array', () => { - const transforms = creator.createConcreteContext(metadata as any); - expect(transforms).to.have.length(1); - }); - }); + describe('when metadata is not empty or undefined', () => { + const metadata = [null, {}, { transform: () => ({}) }]; + it('should returns expected array', () => { + const transforms = creator.createConcreteContext(metadata as any); + expect(transforms).to.have.length(1); + }); }); -}); \ No newline at end of file + }); +}); diff --git a/src/core/test/router/route-params-factory.spec.ts b/src/core/test/router/route-params-factory.spec.ts index f966d0b7a83..d6f7fe4b954 100644 --- a/src/core/test/router/route-params-factory.spec.ts +++ b/src/core/test/router/route-params-factory.spec.ts @@ -3,75 +3,105 @@ import { RouteParamtypes } from '../../../common/enums/route-paramtypes.enum'; import { RouteParamsFactory } from '../../router/route-params-factory'; describe('RouteParamsFactory', () => { - let factory: RouteParamsFactory; - beforeEach(() => { - factory = new RouteParamsFactory(); - }); - describe('exchangeKeyForValue', () => { - const res = {}; - const next = () => ({}); - const req = { - session: null, - body: { - foo: 'bar', - }, - headers: { - foo: 'bar', - }, - params: { - foo: 'bar', - }, - query: { - foo: 'bar', - }, - }; - describe('when key is', () => { - const args = [null, { res, req, next }]; - describe(`RouteParamtypes.NEXT`, () => { - it('should returns next object', () => { - expect((factory as any).exchangeKeyForValue(RouteParamtypes.NEXT, ...args)).to.be.eql(next); - }); - }); - describe(`RouteParamtypes.RESPONSE`, () => { - it('should returns response object', () => { - expect((factory as any).exchangeKeyForValue(RouteParamtypes.RESPONSE, ...args)).to.be.eql(res); - }); - }); - describe(`RouteParamtypes.REQUEST`, () => { - it('should returns request object', () => { - expect((factory as any).exchangeKeyForValue(RouteParamtypes.REQUEST, ...args)).to.be.eql(req); - }); - }); - describe(`RouteParamtypes.BODY`, () => { - it('should returns body object', () => { - expect((factory as any).exchangeKeyForValue(RouteParamtypes.BODY, ...args)).to.be.eql(req.body); - }); - }); - describe(`RouteParamtypes.HEADERS`, () => { - it('should returns headers object', () => { - expect((factory as any).exchangeKeyForValue(RouteParamtypes.HEADERS, ...args)).to.be.eql(req.headers); - }); - }); - describe(`RouteParamtypes.SESSION`, () => { - it('should returns session object', () => { - expect((factory as any).exchangeKeyForValue(RouteParamtypes.SESSION, ...args)).to.be.eql(req.session); - }); - }); - describe(`RouteParamtypes.QUERY`, () => { - it('should returns query object', () => { - expect((factory as any).exchangeKeyForValue(RouteParamtypes.QUERY, ...args)).to.be.eql(req.query); - }); - }); - describe(`RouteParamtypes.PARAM`, () => { - it('should returns params object', () => { - expect((factory as any).exchangeKeyForValue(RouteParamtypes.PARAM, ...args)).to.be.eql(req.params); - }); - }); - describe('not available', () => { - it('should returns null', () => { - expect((factory as any).exchangeKeyForValue(-1, ...args)).to.be.eql(null); - }); - }); + let factory: RouteParamsFactory; + beforeEach(() => { + factory = new RouteParamsFactory(); + }); + describe('exchangeKeyForValue', () => { + const res = {}; + const next = () => ({}); + const req = { + session: null, + body: { + foo: 'bar' + }, + headers: { + foo: 'bar' + }, + params: { + foo: 'bar' + }, + query: { + foo: 'bar' + } + }; + describe('when key is', () => { + const args = [null, { res, req, next }]; + describe(`RouteParamtypes.NEXT`, () => { + it('should returns next object', () => { + expect( + (factory as any).exchangeKeyForValue(RouteParamtypes.NEXT, ...args) + ).to.be.eql(next); + }); + }); + describe(`RouteParamtypes.RESPONSE`, () => { + it('should returns response object', () => { + expect( + (factory as any).exchangeKeyForValue( + RouteParamtypes.RESPONSE, + ...args + ) + ).to.be.eql(res); + }); + }); + describe(`RouteParamtypes.REQUEST`, () => { + it('should returns request object', () => { + expect( + (factory as any).exchangeKeyForValue( + RouteParamtypes.REQUEST, + ...args + ) + ).to.be.eql(req); + }); + }); + describe(`RouteParamtypes.BODY`, () => { + it('should returns body object', () => { + expect( + (factory as any).exchangeKeyForValue(RouteParamtypes.BODY, ...args) + ).to.be.eql(req.body); + }); + }); + describe(`RouteParamtypes.HEADERS`, () => { + it('should returns headers object', () => { + expect( + (factory as any).exchangeKeyForValue( + RouteParamtypes.HEADERS, + ...args + ) + ).to.be.eql(req.headers); + }); + }); + describe(`RouteParamtypes.SESSION`, () => { + it('should returns session object', () => { + expect( + (factory as any).exchangeKeyForValue( + RouteParamtypes.SESSION, + ...args + ) + ).to.be.eql(req.session); + }); + }); + describe(`RouteParamtypes.QUERY`, () => { + it('should returns query object', () => { + expect( + (factory as any).exchangeKeyForValue(RouteParamtypes.QUERY, ...args) + ).to.be.eql(req.query); + }); + }); + describe(`RouteParamtypes.PARAM`, () => { + it('should returns params object', () => { + expect( + (factory as any).exchangeKeyForValue(RouteParamtypes.PARAM, ...args) + ).to.be.eql(req.params); + }); + }); + describe('not available', () => { + it('should returns null', () => { + expect((factory as any).exchangeKeyForValue(-1, ...args)).to.be.eql( + null + ); }); + }); }); -}); \ No newline at end of file + }); +}); diff --git a/src/core/test/router/router-exception-filters.spec.ts b/src/core/test/router/router-exception-filters.spec.ts index c894750eff1..9ede3ea83aa 100644 --- a/src/core/test/router/router-exception-filters.spec.ts +++ b/src/core/test/router/router-exception-filters.spec.ts @@ -7,61 +7,74 @@ import { UnknownModuleException } from '../../errors/exceptions/unknown-module.e import { ApplicationConfig } from '../../application-config'; describe('RouterExceptionFilters', () => { - let moduleName: string; - let exceptionFilter: RouterExceptionFilters; + let moduleName: string; + let exceptionFilter: RouterExceptionFilters; - class CustomException {} - @Catch(CustomException) - class ExceptionFilter { - public catch(exc, res) {} - } + class CustomException {} + @Catch(CustomException) + class ExceptionFilter { + public catch(exc, res) {} + } - beforeEach(() => { - moduleName = 'Test'; - exceptionFilter = new RouterExceptionFilters(new ApplicationConfig()); + beforeEach(() => { + moduleName = 'Test'; + exceptionFilter = new RouterExceptionFilters(new ApplicationConfig()); + }); + describe('create', () => { + describe('when filters metadata is empty', () => { + class EmptyMetadata {} + beforeEach(() => { + sinon.stub(exceptionFilter, 'createContext').returns([]); + }); + it('should returns plain ExceptionHandler object', () => { + const filter = exceptionFilter.create( + new EmptyMetadata(), + () => ({} as any) + ); + expect((filter as any).filters).to.be.empty; + }); }); - describe('create', () => { - describe('when filters metadata is empty', () => { - class EmptyMetadata {} - beforeEach(() => { - sinon.stub(exceptionFilter, 'createContext').returns([]); - }); - it('should returns plain ExceptionHandler object', () => { - const filter = exceptionFilter.create(new EmptyMetadata(), () => ({}) as any); - expect((filter as any).filters).to.be.empty; - }); - }); - describe('when filters metadata is not empty', () => { - @UseFilters(new ExceptionFilter()) - class WithMetadata {} + describe('when filters metadata is not empty', () => { + @UseFilters(new ExceptionFilter()) + class WithMetadata {} - it('should returns ExceptionHandler object with exception filters', () => { - const filter = exceptionFilter.create(new WithMetadata(), () => ({}) as any); - expect((filter as any).filters).to.not.be.empty; - }); - }); + it('should returns ExceptionHandler object with exception filters', () => { + const filter = exceptionFilter.create( + new WithMetadata(), + () => ({} as any) + ); + expect((filter as any).filters).to.not.be.empty; + }); }); - describe('reflectCatchExceptions', () => { - it('should returns FILTER_CATCH_EXCEPTIONS metadata', () => { - expect( - exceptionFilter.reflectCatchExceptions(new ExceptionFilter()), - ).to.be.eql([ CustomException ]); - }); + }); + describe('reflectCatchExceptions', () => { + it('should returns FILTER_CATCH_EXCEPTIONS metadata', () => { + expect( + exceptionFilter.reflectCatchExceptions(new ExceptionFilter()) + ).to.be.eql([CustomException]); }); - describe('createConcreteContext', () => { - class InvalidFilter {} - const filters = [ new ExceptionFilter(), new InvalidFilter(), 'test' ]; + }); + describe('createConcreteContext', () => { + class InvalidFilter {} + const filters = [new ExceptionFilter(), new InvalidFilter(), 'test']; - beforeEach(() => { - sinon.stub(exceptionFilter, 'findExceptionsFilterInstance').onFirstCall().returns({ - catch: () => ({}), - }).onSecondCall().returns({}); - }); - it('should returns expected exception filters metadata', () => { - const resolved = exceptionFilter.createConcreteContext(filters as any); - expect(resolved).to.have.length(1); - expect(resolved[0].exceptionMetatypes).to.be.deep.equal([ CustomException ]); - expect(resolved[0].func).to.be.a('function'); - }); + beforeEach(() => { + sinon + .stub(exceptionFilter, 'findExceptionsFilterInstance') + .onFirstCall() + .returns({ + catch: () => ({}) + }) + .onSecondCall() + .returns({}); + }); + it('should returns expected exception filters metadata', () => { + const resolved = exceptionFilter.createConcreteContext(filters as any); + expect(resolved).to.have.length(1); + expect(resolved[0].exceptionMetatypes).to.be.deep.equal([ + CustomException + ]); + expect(resolved[0].func).to.be.a('function'); }); -}); \ No newline at end of file + }); +}); diff --git a/src/core/test/router/router-execution-context.spec.ts b/src/core/test/router/router-execution-context.spec.ts index e4f690a2bbf..825b1f1b78b 100644 --- a/src/core/test/router/router-execution-context.spec.ts +++ b/src/core/test/router/router-execution-context.spec.ts @@ -16,232 +16,302 @@ import { InterceptorsContextCreator } from '../../interceptors/interceptors-cont import { InterceptorsConsumer } from '../../interceptors/interceptors-consumer'; describe('RouterExecutionContext', () => { - let contextCreator: RouterExecutionContext; - let callback; - let applySpy: sinon.SinonSpy; - let bindSpy: sinon.SinonSpy; - let factory: RouteParamsFactory; - let consumer: PipesConsumer; - let guardsConsumer: GuardsConsumer; + let contextCreator: RouterExecutionContext; + let callback; + let applySpy: sinon.SinonSpy; + let bindSpy: sinon.SinonSpy; + let factory: RouteParamsFactory; + let consumer: PipesConsumer; + let guardsConsumer: GuardsConsumer; - beforeEach(() => { - callback = { - bind: () => ({}), - apply: () => ({}), - }; - bindSpy = sinon.spy(callback, 'bind'); - applySpy = sinon.spy(callback, 'apply'); + beforeEach(() => { + callback = { + bind: () => ({}), + apply: () => ({}) + }; + bindSpy = sinon.spy(callback, 'bind'); + applySpy = sinon.spy(callback, 'apply'); - factory = new RouteParamsFactory(); - consumer = new PipesConsumer(); - guardsConsumer = new GuardsConsumer(); + factory = new RouteParamsFactory(); + consumer = new PipesConsumer(); + guardsConsumer = new GuardsConsumer(); - contextCreator = new RouterExecutionContext( - factory, new PipesContextCreator(new ApplicationConfig()), consumer, - new GuardsContextCreator(new NestContainer()), guardsConsumer, - new InterceptorsContextCreator(new NestContainer()), new InterceptorsConsumer(), + contextCreator = new RouterExecutionContext( + factory, + new PipesContextCreator(new ApplicationConfig()), + consumer, + new GuardsContextCreator(new NestContainer()), + guardsConsumer, + new InterceptorsContextCreator(new NestContainer()), + new InterceptorsConsumer() + ); + }); + describe('create', () => { + describe('when callback metadata is not undefined', () => { + let metadata: RouteParamsMetadata; + let exchangeKeysForValuesSpy: sinon.SinonSpy; + beforeEach(() => { + metadata = { + [RouteParamtypes.NEXT]: { index: 0 }, + [RouteParamtypes.BODY]: { + index: 2, + data: 'test' + } + }; + sinon.stub(contextCreator, 'reflectCallbackMetadata').returns(metadata); + sinon.stub(contextCreator, 'reflectCallbackParamtypes').returns([]); + exchangeKeysForValuesSpy = sinon.spy( + contextCreator, + 'exchangeKeysForValues' ); - }); - describe('create', () => { - describe('when callback metadata is not undefined', () => { - let metadata: RouteParamsMetadata; - let exchangeKeysForValuesSpy: sinon.SinonSpy; - beforeEach(() => { - metadata = { - [RouteParamtypes.NEXT]: { index: 0 }, - [RouteParamtypes.BODY]: { - index: 2, - data: 'test', - }, - }; - sinon.stub(contextCreator, 'reflectCallbackMetadata').returns(metadata); - sinon.stub(contextCreator, 'reflectCallbackParamtypes').returns([]); - exchangeKeysForValuesSpy = sinon.spy(contextCreator, 'exchangeKeysForValues'); - }); - it('should call "exchangeKeysForValues" with expected arguments', (done) => { - const keys = Object.keys(metadata); + }); + it('should call "exchangeKeysForValues" with expected arguments', done => { + const keys = Object.keys(metadata); - contextCreator.create({ foo: 'bar' }, callback as any, '', '', 0); - expect(exchangeKeysForValuesSpy.called).to.be.true; - expect( - exchangeKeysForValuesSpy.calledWith(keys, metadata), - ).to.be.true; - done(); - }); - describe('returns proxy function', () => { - let proxyContext; - let instance; + contextCreator.create({ foo: 'bar' }, callback as any, '', '', 0); + expect(exchangeKeysForValuesSpy.called).to.be.true; + expect(exchangeKeysForValuesSpy.calledWith(keys, metadata)).to.be.true; + done(); + }); + describe('returns proxy function', () => { + let proxyContext; + let instance; - beforeEach(() => { - instance = { foo: 'bar' }; - proxyContext = contextCreator.create(instance, callback as any, '', '', 0); - }); - it('should be a function', () => { - expect(proxyContext).to.be.a('function'); - }); - describe('when proxy function called', () => { - let request; - const response = { - status: () => response, - send: () => response, - json: () => response, - }; - const next = {}; + beforeEach(() => { + instance = { foo: 'bar' }; + proxyContext = contextCreator.create( + instance, + callback as any, + '', + '', + 0 + ); + }); + it('should be a function', () => { + expect(proxyContext).to.be.a('function'); + }); + describe('when proxy function called', () => { + let request; + const response = { + status: () => response, + send: () => response, + json: () => response + }; + const next = {}; - beforeEach(() => { - request = { - body: { - test: 3, - }, - }; - }); - it('should apply expected context and arguments to callback', (done) => { - proxyContext(request, response, next).then(() => { - const args = [ next, null, request.body.test ]; - expect(applySpy.called).to.be.true; - expect(applySpy.calledWith(instance, args)).to.be.true; - done(); - }); - }); - it('should throw exception when "tryActivate" returns false', () => { - sinon.stub(guardsConsumer, 'tryActivate', () => false); - expect( - proxyContext(request, response, next), - ).to.eventually.throw(); - }); - }); + beforeEach(() => { + request = { + body: { + test: 3 + } + }; + }); + it('should apply expected context and arguments to callback', done => { + proxyContext(request, response, next).then(() => { + const args = [next, null, request.body.test]; + expect(applySpy.called).to.be.true; + expect(applySpy.calledWith(instance, args)).to.be.true; + done(); }); + }); + it('should throw exception when "tryActivate" returns false', () => { + sinon.stub(guardsConsumer, 'tryActivate', () => false); + expect(proxyContext(request, response, next)).to.eventually.throw(); + }); }); + }); }); - describe('reflectCallbackMetadata', () => { - const CustomDecorator = createRouteParamDecorator(() => {}); - class TestController { - public callback(@Request() req, @Body() body, @CustomDecorator() custom) {} + }); + describe('reflectCallbackMetadata', () => { + const CustomDecorator = createRouteParamDecorator(() => {}); + class TestController { + public callback( + @Request() req, + @Body() body, + @CustomDecorator() custom + ) {} + } + it('should returns ROUTE_ARGS_METADATA callback metadata', () => { + const instance = new TestController(); + const metadata = contextCreator.reflectCallbackMetadata( + instance, + 'callback' + ); + console.log(metadata); + + const expectedMetadata = { + [`${RouteParamtypes.REQUEST}:0`]: { + index: 0, + data: undefined, + pipes: [] + }, + [`${RouteParamtypes.BODY}:1`]: { + index: 1, + data: undefined, + pipes: [] + }, + [`custom${CUSTOM_ROUTE_AGRS_METADATA}:2`]: { + index: 2, + factory: () => {}, + data: undefined } - it('should returns ROUTE_ARGS_METADATA callback metadata', () => { - const instance = new TestController(); - const metadata = contextCreator.reflectCallbackMetadata(instance, 'callback'); - console.log(metadata); - - const expectedMetadata = { - [`${RouteParamtypes.REQUEST}:0`]: { - index: 0, - data: undefined, - pipes: [], - }, - [`${RouteParamtypes.BODY}:1`]: { - index: 1, - data: undefined, - pipes: [], - }, - [`custom${CUSTOM_ROUTE_AGRS_METADATA}:2`]: { - index: 2, - factory: () => {}, - data: undefined, - }, - }; - expect(metadata[`${RouteParamtypes.REQUEST}:0`]).to.deep.equal(expectedMetadata[`${RouteParamtypes.REQUEST}:0`]); - expect(metadata[`${RouteParamtypes.REQUEST}:1`]).to.deep.equal(expectedMetadata[`${RouteParamtypes.REQUEST}:1`]); + }; + expect(metadata[`${RouteParamtypes.REQUEST}:0`]).to.deep.equal( + expectedMetadata[`${RouteParamtypes.REQUEST}:0`] + ); + expect(metadata[`${RouteParamtypes.REQUEST}:1`]).to.deep.equal( + expectedMetadata[`${RouteParamtypes.REQUEST}:1`] + ); - const keys = Object.keys(metadata); - const custom = keys.find((key) => key.includes(CUSTOM_ROUTE_AGRS_METADATA)); + const keys = Object.keys(metadata); + const custom = keys.find(key => key.includes(CUSTOM_ROUTE_AGRS_METADATA)); - expect(metadata[custom]).to.be.an('object'); - expect(metadata[custom].index).to.be.eq(2); - expect(metadata[custom].data).to.be.eq(undefined); - expect(metadata[custom].factory).to.be.a('function'); - }); + expect(metadata[custom]).to.be.an('object'); + expect(metadata[custom].index).to.be.eq(2); + expect(metadata[custom].data).to.be.eq(undefined); + expect(metadata[custom].factory).to.be.a('function'); }); - describe('getArgumentsLength', () => { - it('should returns maximum index + 1 (length) placed in array', () => { - const max = 4; - const metadata = { - [RouteParamtypes.REQUEST]: { index: 0 }, - [RouteParamtypes.BODY]: { - index: max, - }, - }; - expect( - contextCreator.getArgumentsLength(Object.keys(metadata), metadata), - ).to.be.eq(max + 1); - }); + }); + describe('getArgumentsLength', () => { + it('should returns maximum index + 1 (length) placed in array', () => { + const max = 4; + const metadata = { + [RouteParamtypes.REQUEST]: { index: 0 }, + [RouteParamtypes.BODY]: { + index: max + } + }; + expect( + contextCreator.getArgumentsLength(Object.keys(metadata), metadata) + ).to.be.eq(max + 1); }); - describe('createNullArray', () => { - it('should create N size array filled with null', () => { - const size = 3; - expect(contextCreator.createNullArray(size)).to.be.deep.eq([ null, null, null ]); - }); + }); + describe('createNullArray', () => { + it('should create N size array filled with null', () => { + const size = 3; + expect(contextCreator.createNullArray(size)).to.be.deep.eq([ + null, + null, + null + ]); }); - describe('exchangeKeysForValues', () => { - const res = { body: 'res' }; - const req = { body: { test: 'req' } }; - const next = () => {}; + }); + describe('exchangeKeysForValues', () => { + const res = { body: 'res' }; + const req = { body: { test: 'req' } }; + const next = () => {}; - it('should exchange arguments keys for appropriate values', () => { - const metadata = { - [RouteParamtypes.REQUEST]: { index: 0, data: 'test', pipes: [] }, - [RouteParamtypes.BODY]: { index: 2, data: 'test', pipes: [] }, - [`key${CUSTOM_ROUTE_AGRS_METADATA}`]: { index: 3, data: 'custom', pipes: [] }, - }; - const keys = Object.keys(metadata); - const values = contextCreator.exchangeKeysForValues(keys, metadata); - const expectedValues = [ - { index: 0, type: RouteParamtypes.REQUEST, data: 'test' }, - { index: 2, type: RouteParamtypes.BODY, data: 'test' }, - { index: 3, type: `key${CUSTOM_ROUTE_AGRS_METADATA}`, data: 'custom' }, - ]; - expect(values[0]).to.deep.include(expectedValues[0]); - expect(values[1]).to.deep.include(expectedValues[1]); - }); + it('should exchange arguments keys for appropriate values', () => { + const metadata = { + [RouteParamtypes.REQUEST]: { index: 0, data: 'test', pipes: [] }, + [RouteParamtypes.BODY]: { index: 2, data: 'test', pipes: [] }, + [`key${CUSTOM_ROUTE_AGRS_METADATA}`]: { + index: 3, + data: 'custom', + pipes: [] + } + }; + const keys = Object.keys(metadata); + const values = contextCreator.exchangeKeysForValues(keys, metadata); + const expectedValues = [ + { index: 0, type: RouteParamtypes.REQUEST, data: 'test' }, + { index: 2, type: RouteParamtypes.BODY, data: 'test' }, + { index: 3, type: `key${CUSTOM_ROUTE_AGRS_METADATA}`, data: 'custom' } + ]; + expect(values[0]).to.deep.include(expectedValues[0]); + expect(values[1]).to.deep.include(expectedValues[1]); }); - describe('getCustomFactory', () => { - describe('when factory is function', () => { - it('should return curried factory', () => { - const data = 3; - const result = 10; - const customFactory = (_, req) => result; + }); + describe('getCustomFactory', () => { + describe('when factory is function', () => { + it('should return curried factory', () => { + const data = 3; + const result = 10; + const customFactory = (_, req) => result; - expect(contextCreator.getCustomFactory(customFactory, data)()).to.be.eql(result); - }); - }); - describe('when factory is undefined / is not a function', () => { - it('should return curried null identity', () => { - const result = 10; - const customFactory = undefined; - expect(contextCreator.getCustomFactory(customFactory, undefined)()).to.be.eql(null); - }); + expect( + contextCreator.getCustomFactory(customFactory, data)() + ).to.be.eql(result); }); }); - describe('mergeParamsMetatypes', () => { - it('should return "paramsProperties" when paramtypes array doesnt exists', () => { - const paramsProperties = ['1']; - expect(contextCreator.mergeParamsMetatypes(paramsProperties as any, null)).to.be.eql(paramsProperties); + describe('when factory is undefined / is not a function', () => { + it('should return curried null identity', () => { + const result = 10; + const customFactory = undefined; + expect( + contextCreator.getCustomFactory(customFactory, undefined)() + ).to.be.eql(null); }); }); - describe('getParamValue', () => { - let consumerApplySpy: sinon.SinonSpy; - const value = 3, metatype = null, transforms = []; + }); + describe('mergeParamsMetatypes', () => { + it('should return "paramsProperties" when paramtypes array doesnt exists', () => { + const paramsProperties = ['1']; + expect( + contextCreator.mergeParamsMetatypes(paramsProperties as any, null) + ).to.be.eql(paramsProperties); + }); + }); + describe('getParamValue', () => { + let consumerApplySpy: sinon.SinonSpy; + const value = 3, + metatype = null, + transforms = []; - beforeEach(() => { - consumerApplySpy = sinon.spy(consumer, 'apply'); - }); - describe('when paramtype is query, body or param', () => { - it('should call "consumer.apply" with expected arguments', () => { - contextCreator.getParamValue(value, { metatype, type: RouteParamtypes.QUERY, data: null } , transforms); - expect(consumerApplySpy.calledWith(value, { metatype, type: RouteParamtypes.QUERY, data: null }, transforms)).to.be.true; + beforeEach(() => { + consumerApplySpy = sinon.spy(consumer, 'apply'); + }); + describe('when paramtype is query, body or param', () => { + it('should call "consumer.apply" with expected arguments', () => { + contextCreator.getParamValue( + value, + { metatype, type: RouteParamtypes.QUERY, data: null }, + transforms + ); + expect( + consumerApplySpy.calledWith( + value, + { metatype, type: RouteParamtypes.QUERY, data: null }, + transforms + ) + ).to.be.true; - contextCreator.getParamValue(value, { metatype, type: RouteParamtypes.BODY, data: null }, transforms); - expect(consumerApplySpy.calledWith(value, { metatype, type: RouteParamtypes.BODY, data: null }, transforms)).to.be.true; + contextCreator.getParamValue( + value, + { metatype, type: RouteParamtypes.BODY, data: null }, + transforms + ); + expect( + consumerApplySpy.calledWith( + value, + { metatype, type: RouteParamtypes.BODY, data: null }, + transforms + ) + ).to.be.true; - contextCreator.getParamValue(value, { metatype, type: RouteParamtypes.PARAM, data: null }, transforms); - expect(consumerApplySpy.calledWith(value, { metatype, type: RouteParamtypes.PARAM, data: null }, transforms)).to.be.true; - }); - }); - describe('when paramtype is not query, body and param', () => { - it('should not call "consumer.apply"', () => { - contextCreator.getParamValue(value, { metatype, type: RouteParamtypes.NEXT, data: null }, transforms); - expect(consumerApplySpy.called).to.be.false; - }); - }); + contextCreator.getParamValue( + value, + { metatype, type: RouteParamtypes.PARAM, data: null }, + transforms + ); + expect( + consumerApplySpy.calledWith( + value, + { metatype, type: RouteParamtypes.PARAM, data: null }, + transforms + ) + ).to.be.true; + }); + }); + describe('when paramtype is not query, body and param', () => { + it('should not call "consumer.apply"', () => { + contextCreator.getParamValue( + value, + { metatype, type: RouteParamtypes.NEXT, data: null }, + transforms + ); + expect(consumerApplySpy.called).to.be.false; + }); }); -}); \ No newline at end of file + }); +}); diff --git a/src/core/test/router/router-explorer.spec.ts b/src/core/test/router/router-explorer.spec.ts index a51a9ddbf71..067006bc6ad 100644 --- a/src/core/test/router/router-explorer.spec.ts +++ b/src/core/test/router/router-explorer.spec.ts @@ -7,60 +7,64 @@ import { RequestMethod } from '../../../common/enums/request-method.enum'; import { MetadataScanner } from '../../metadata-scanner'; describe('RouterExplorer', () => { - @Controller('global') - class TestRoute { - @RequestMapping({ path: 'test' }) - public getTest() {} + @Controller('global') + class TestRoute { + @RequestMapping({ path: 'test' }) + public getTest() {} - @RequestMapping({ path: 'test', method: RequestMethod.POST }) - public postTest() {} + @RequestMapping({ path: 'test', method: RequestMethod.POST }) + public postTest() {} - @RequestMapping({ path: 'another-test', method: RequestMethod.ALL }) - public anotherTest() {} - } + @RequestMapping({ path: 'another-test', method: RequestMethod.ALL }) + public anotherTest() {} + } - let routerBuilder: ExpressRouterExplorer; - beforeEach(() => { - routerBuilder = new ExpressRouterExplorer(new MetadataScanner(), null); - }); - describe('scanForPaths', () => { - it('should method return expected list of route paths', () => { - const paths = routerBuilder.scanForPaths(new TestRoute()); + let routerBuilder: ExpressRouterExplorer; + beforeEach(() => { + routerBuilder = new ExpressRouterExplorer(new MetadataScanner(), null); + }); + describe('scanForPaths', () => { + it('should method return expected list of route paths', () => { + const paths = routerBuilder.scanForPaths(new TestRoute()); - expect(paths).to.have.length(3); + expect(paths).to.have.length(3); - expect(paths[0].path).to.eql('/test'); - expect(paths[1].path).to.eql('/test'); - expect(paths[2].path).to.eql('/another-test'); + expect(paths[0].path).to.eql('/test'); + expect(paths[1].path).to.eql('/test'); + expect(paths[2].path).to.eql('/another-test'); - expect(paths[0].requestMethod).to.eql(RequestMethod.GET); - expect(paths[1].requestMethod).to.eql(RequestMethod.POST); - expect(paths[2].requestMethod).to.eql(RequestMethod.ALL); - }); + expect(paths[0].requestMethod).to.eql(RequestMethod.GET); + expect(paths[1].requestMethod).to.eql(RequestMethod.POST); + expect(paths[2].requestMethod).to.eql(RequestMethod.ALL); }); - describe('exploreMethodMetadata', () => { - it('should method return expected object which represent single route', () => { - const instance = new TestRoute(); - const instanceProto = Object.getPrototypeOf(instance); + }); + describe('exploreMethodMetadata', () => { + it('should method return expected object which represent single route', () => { + const instance = new TestRoute(); + const instanceProto = Object.getPrototypeOf(instance); - const route = routerBuilder.exploreMethodMetadata(new TestRoute(), instanceProto, 'getTest'); + const route = routerBuilder.exploreMethodMetadata( + new TestRoute(), + instanceProto, + 'getTest' + ); - expect(route.path).to.eql('/test'); - expect(route.requestMethod).to.eql(RequestMethod.GET); - }); + expect(route.path).to.eql('/test'); + expect(route.requestMethod).to.eql(RequestMethod.GET); }); - describe('applyPathsToRouterProxy', () => { - it('should method return expected object which represent single route', () => { - const bindStub = sinon.stub(routerBuilder, 'applyCallbackToRouter'); - const paths = [ - { path: '', requestMethod: RequestMethod.GET }, - { path: 'test', requestMethod: RequestMethod.GET }, - ]; + }); + describe('applyPathsToRouterProxy', () => { + it('should method return expected object which represent single route', () => { + const bindStub = sinon.stub(routerBuilder, 'applyCallbackToRouter'); + const paths = [ + { path: '', requestMethod: RequestMethod.GET }, + { path: 'test', requestMethod: RequestMethod.GET } + ]; - routerBuilder.applyPathsToRouterProxy(null, paths as any, null, ''); + routerBuilder.applyPathsToRouterProxy(null, paths as any, null, ''); - expect(bindStub.calledWith(null, paths[0], null)).to.be.true; - expect(bindStub.callCount).to.be.eql(paths.length); - }); + expect(bindStub.calledWith(null, paths[0], null)).to.be.true; + expect(bindStub.callCount).to.be.eql(paths.length); }); -}); \ No newline at end of file + }); +}); diff --git a/src/core/test/router/router-proxy.spec.ts b/src/core/test/router/router-proxy.spec.ts index efb6d3ea922..f83a208982a 100644 --- a/src/core/test/router/router-proxy.spec.ts +++ b/src/core/test/router/router-proxy.spec.ts @@ -5,75 +5,77 @@ import { ExceptionsHandler } from '../../exceptions/exceptions-handler'; import { HttpException } from '../../exceptions/http-exception'; describe('RouterProxy', () => { - let routerProxy: RouterProxy; - let handlerMock: sinon.SinonMock; - let handler: ExceptionsHandler; + let routerProxy: RouterProxy; + let handlerMock: sinon.SinonMock; + let handler: ExceptionsHandler; - beforeEach(() => { - handler = new ExceptionsHandler(); - handlerMock = sinon.mock(handler); - routerProxy = new RouterProxy(); - }); - - describe('createProxy', () => { - - it('should method return thunk', () => { - const proxy = routerProxy.createProxy(() => {}, handler); - expect(typeof proxy === 'function').to.be.true; - }); - - it('should method encapsulate callback passed as argument', () => { - const expectation = handlerMock.expects('next').once(); - const proxy = routerProxy.createProxy((req, res, next) => { - throw new HttpException('test', 500); - }, handler); - proxy(null, null, null); - expectation.verify(); - }); - - it('should method encapsulate async callback passed as argument', (done) => { - const expectation = handlerMock.expects('next').once(); - const proxy = routerProxy.createProxy(async (req, res, next) => { - throw new HttpException('test', 500); - }, handler); - proxy(null, null, null); + beforeEach(() => { + handler = new ExceptionsHandler(); + handlerMock = sinon.mock(handler); + routerProxy = new RouterProxy(); + }); - setTimeout(() => { - expectation.verify(); - done(); - }, 0); - }); + describe('createProxy', () => { + it('should method return thunk', () => { + const proxy = routerProxy.createProxy(() => {}, handler); + expect(typeof proxy === 'function').to.be.true; + }); + it('should method encapsulate callback passed as argument', () => { + const expectation = handlerMock.expects('next').once(); + const proxy = routerProxy.createProxy((req, res, next) => { + throw new HttpException('test', 500); + }, handler); + proxy(null, null, null); + expectation.verify(); }); - describe('createExceptionLayerProxy', () => { + it('should method encapsulate async callback passed as argument', done => { + const expectation = handlerMock.expects('next').once(); + const proxy = routerProxy.createProxy(async (req, res, next) => { + throw new HttpException('test', 500); + }, handler); + proxy(null, null, null); - it('should method return thunk', () => { - const proxy = routerProxy.createExceptionLayerProxy(() => {}, handler); - expect(typeof proxy === 'function').to.be.true; - }); + setTimeout(() => { + expectation.verify(); + done(); + }, 0); + }); + }); - it('should method encapsulate callback passed as argument', () => { - const expectation = handlerMock.expects('next').once(); - const proxy = routerProxy.createExceptionLayerProxy((err, req, res, next) => { - throw new HttpException('test', 500); - }, handler); - proxy(null, null, null, null); - expectation.verify(); - }); + describe('createExceptionLayerProxy', () => { + it('should method return thunk', () => { + const proxy = routerProxy.createExceptionLayerProxy(() => {}, handler); + expect(typeof proxy === 'function').to.be.true; + }); - it('should method encapsulate async callback passed as argument', (done) => { - const expectation = handlerMock.expects('next').once(); - const proxy = routerProxy.createExceptionLayerProxy(async (err, req, res, next) => { - throw new HttpException('test', 500); - }, handler); - proxy(null, null, null, null); + it('should method encapsulate callback passed as argument', () => { + const expectation = handlerMock.expects('next').once(); + const proxy = routerProxy.createExceptionLayerProxy( + (err, req, res, next) => { + throw new HttpException('test', 500); + }, + handler + ); + proxy(null, null, null, null); + expectation.verify(); + }); - setTimeout(() => { - expectation.verify(); - done(); - }, 0); - }); + it('should method encapsulate async callback passed as argument', done => { + const expectation = handlerMock.expects('next').once(); + const proxy = routerProxy.createExceptionLayerProxy( + async (err, req, res, next) => { + throw new HttpException('test', 500); + }, + handler + ); + proxy(null, null, null, null); + setTimeout(() => { + expectation.verify(); + done(); + }, 0); }); -}); \ No newline at end of file + }); +}); diff --git a/src/core/test/router/router-response-controller.spec.ts b/src/core/test/router/router-response-controller.spec.ts index ff6905525a2..e6678495871 100644 --- a/src/core/test/router/router-response-controller.spec.ts +++ b/src/core/test/router/router-response-controller.spec.ts @@ -6,81 +6,99 @@ import { Observable } from 'rxjs/Observable'; import 'rxjs/add/observable/of'; describe('RouterResponseController', () => { - let routerResponseController: RouterResponseController; - let handlerMock: sinon.SinonMock; + let routerResponseController: RouterResponseController; + let handlerMock: sinon.SinonMock; + beforeEach(() => { + routerResponseController = new RouterResponseController(); + }); + + describe('apply', () => { + let response: { + send: sinon.SinonSpy; + status?: sinon.SinonSpy; + json: sinon.SinonSpy; + }; beforeEach(() => { - routerResponseController = new RouterResponseController(); + response = { send: sinon.spy(), json: sinon.spy() }; + response.status = sinon.stub().returns(response); }); - - describe('apply', () => { - let response: { send: sinon.SinonSpy, status?: sinon.SinonSpy, json: sinon.SinonSpy }; - beforeEach(() => { - response = { send: sinon.spy(), json: sinon.spy() }; - response.status = sinon.stub().returns(response); + describe('when result is', () => { + describe('nil', () => { + it('should call send()', async () => { + const value = null; + await routerResponseController.apply(value, response, 1, 200); + expect(response.send.called).to.be.true; }); - describe('when result is', () => { - describe('nil', () => { - it('should call send()', async () => { - const value = null; - await routerResponseController.apply(value, response, 1, 200); - expect(response.send.called).to.be.true; - }); - }); - describe('string', () => { - it('should call send(value)', async () => { - const value = 'string'; - await routerResponseController.apply(value, response, 1, 200); - expect(response.send.called).to.be.true; - expect(response.send.calledWith(String(value))).to.be.true; - }); - }); - describe('object', () => { - it('should call json(value)', async () => { - const value = { test: 'test' }; - await routerResponseController.apply(value, response, 1, 200); - expect(response.json.called).to.be.true; - expect(response.json.calledWith(value)).to.be.true; - }); - }); + }); + describe('string', () => { + it('should call send(value)', async () => { + const value = 'string'; + await routerResponseController.apply(value, response, 1, 200); + expect(response.send.called).to.be.true; + expect(response.send.calledWith(String(value))).to.be.true; }); + }); + describe('object', () => { + it('should call json(value)', async () => { + const value = { test: 'test' }; + await routerResponseController.apply(value, response, 1, 200); + expect(response.json.called).to.be.true; + expect(response.json.calledWith(value)).to.be.true; + }); + }); }); + }); - describe('transformToResult', () => { - describe('when resultOrDeffered', () => { - describe('is Promise', () => { - it('should returns Promise', async () => { - const value = 100; - expect(await routerResponseController.transformToResult(Promise.resolve(value))).to.be.eq(100); - }); - }); + describe('transformToResult', () => { + describe('when resultOrDeffered', () => { + describe('is Promise', () => { + it('should returns Promise', async () => { + const value = 100; + expect( + await routerResponseController.transformToResult( + Promise.resolve(value) + ) + ).to.be.eq(100); + }); + }); - describe('is Observable', () => { - it('should returns Promise', async () => { - const value = 100; - expect(await routerResponseController.transformToResult(Observable.of(value))).to.be.eq(100); - }); - }); + describe('is Observable', () => { + it('should returns Promise', async () => { + const value = 100; + expect( + await routerResponseController.transformToResult( + Observable.of(value) + ) + ).to.be.eq(100); + }); + }); - describe('is value', () => { - it('should returns Promise', async () => { - const value = 100; - expect(await routerResponseController.transformToResult(value)).to.be.eq(100); - }); - }); + describe('is value', () => { + it('should returns Promise', async () => { + const value = 100; + expect( + await routerResponseController.transformToResult(value) + ).to.be.eq(100); }); + }); }); + }); - describe('getStatusByMethod', () => { - describe('when RequestMethod is POST', () => { - it('should returns 201', () => { - expect(routerResponseController.getStatusByMethod(RequestMethod.POST)).to.be.eql(201); - }); - }); - describe('when RequestMethod is not POST', () => { - it('should returns 200', () => { - expect(routerResponseController.getStatusByMethod(RequestMethod.GET)).to.be.eql(200); - }); - }); + describe('getStatusByMethod', () => { + describe('when RequestMethod is POST', () => { + it('should returns 201', () => { + expect( + routerResponseController.getStatusByMethod(RequestMethod.POST) + ).to.be.eql(201); + }); + }); + describe('when RequestMethod is not POST', () => { + it('should returns 200', () => { + expect( + routerResponseController.getStatusByMethod(RequestMethod.GET) + ).to.be.eql(200); + }); }); -}); \ No newline at end of file + }); +}); diff --git a/src/core/test/router/routes-resolver.spec.ts b/src/core/test/router/routes-resolver.spec.ts index 85c54baec9b..d7eb68a06ea 100644 --- a/src/core/test/router/routes-resolver.spec.ts +++ b/src/core/test/router/routes-resolver.spec.ts @@ -10,10 +10,10 @@ describe('RoutesResolver', () => { @Controller('global') class TestRoute { @RequestMapping({ path: 'test' }) - public getTest() { } + public getTest() {} @RequestMapping({ path: 'another-test', method: RequestMethod.POST }) - public anotherTest() { } + public anotherTest() {} } let router; @@ -24,18 +24,22 @@ describe('RoutesResolver', () => { before(() => { modules = new Map(); container = { - getModules: () => modules, + getModules: () => modules }; router = { - get() { }, - post() { }, + get() {}, + post() {} }; }); beforeEach(() => { - routesResolver = new RoutesResolver(container, { - createRouter: () => router, - }, new ApplicationConfig()); + routesResolver = new RoutesResolver( + container, + { + createRouter: () => router + }, + new ApplicationConfig() + ); }); describe('setupRouters', () => { @@ -43,7 +47,7 @@ describe('RoutesResolver', () => { const routes = new Map(); routes.set('TestRoute', { instance: new TestRoute(), - metatype: TestRoute, + metatype: TestRoute }); const use = sinon.spy(); @@ -57,15 +61,16 @@ describe('RoutesResolver', () => { const routes = new Map(); routes.set('TestRoute', { instance: new TestRoute(), - metatype: TestRoute, + metatype: TestRoute }); modules.set('TestModule', { routes }); modules.set('TestModule2', { routes }); - const spy = sinon.stub(routesResolver, 'setupRouters').callsFake(() => undefined); + const spy = sinon + .stub(routesResolver, 'setupRouters') + .callsFake(() => undefined); routesResolver.resolve({ use: sinon.spy() } as any); expect(spy.calledTwice).to.be.true; }); - }); -}); \ No newline at end of file +}); diff --git a/src/core/test/scanner.spec.ts b/src/core/test/scanner.spec.ts index 794fb9032a1..85a1ce23aeb 100644 --- a/src/core/test/scanner.spec.ts +++ b/src/core/test/scanner.spec.ts @@ -11,134 +11,149 @@ import { MetadataScanner } from '../metadata-scanner'; import { GUARDS_METADATA } from '../../common/constants'; describe('DependenciesScanner', () => { - - @Component() class TestComponent {} - @Controller('') class TestRoute {} - - @Module({ - components: [ TestComponent ], - controllers: [ TestRoute ], - exports: [ TestComponent ], - }) - class AnotherTestModule {} - - @Module({ - modules: [ AnotherTestModule ], - components: [ TestComponent ], - controllers: [ TestRoute ], - }) - class TestModule {} - - let scanner: DependenciesScanner; - let mockContainer: sinon.SinonMock; - let container: NestContainer; - - before(() => { - container = new NestContainer(); - mockContainer = sinon.mock(container); - }); - - beforeEach(() => { - scanner = new DependenciesScanner(container, new MetadataScanner()); - }); - - afterEach(() => { - mockContainer.restore(); - }); - - it('should "storeModule" call twice (2 modules) container method "addModule"', () => { - const expectation = mockContainer.expects('addModule').twice(); - scanner.scan(TestModule as any); - expectation.verify(); - }); - - it('should "storeComponent" call twice (2 components) container method "addComponent"', () => { - const expectation = mockContainer.expects('addComponent').twice(); - const stub = sinon.stub(scanner, 'storeExportedComponent'); - - scanner.scan(TestModule as any); - expectation.verify(); - stub.restore(); - }); - - it('should "storeRoute" call twice (2 components) container method "addController"', () => { - const expectation = mockContainer.expects('addController').twice(); - scanner.scan(TestModule as any); - expectation.verify(); - }); - - it('should "storeExportedComponent" call once (1 component) container method "addExportedComponent"', () => { - const expectation = mockContainer.expects('addExportedComponent').once(); - scanner.scan(TestModule as any); - expectation.verify(); - }); - - describe('reflectDynamicMetadata', () => { - describe('when param has prototype', () => { - it('should call "reflectGuards" and "reflectInterceptors"', () => { - const reflectGuards = sinon.stub(scanner, 'reflectGuards').callsFake(() => undefined); - const reflectInterceptors = sinon.stub(scanner, 'reflectInterceptors').callsFake(() => undefined); - scanner.reflectDynamicMetadata({ prototype: true } as any, ''); - - expect(reflectGuards.called).to.be.true; - expect(reflectInterceptors.called).to.be.true; - }); - }); - describe('when param has not prototype', () => { - it('should not call "reflectGuards" and "reflectInterceptors"', () => { - const reflectGuards = sinon.stub(scanner, 'reflectGuards').callsFake(() => undefined); - const reflectInterceptors = sinon.stub(scanner, 'reflectInterceptors').callsFake(() => undefined); - scanner.reflectDynamicMetadata({} as any, ''); - - expect(reflectGuards.called).to.be.false; - expect(reflectInterceptors.called).to.be.false; - }); + @Component() + class TestComponent {} + @Controller('') + class TestRoute {} + + @Module({ + components: [TestComponent], + controllers: [TestRoute], + exports: [TestComponent] + }) + class AnotherTestModule {} + + @Module({ + modules: [AnotherTestModule], + components: [TestComponent], + controllers: [TestRoute] + }) + class TestModule {} + + let scanner: DependenciesScanner; + let mockContainer: sinon.SinonMock; + let container: NestContainer; + + before(() => { + container = new NestContainer(); + mockContainer = sinon.mock(container); + }); + + beforeEach(() => { + scanner = new DependenciesScanner(container, new MetadataScanner()); + }); + + afterEach(() => { + mockContainer.restore(); + }); + + it('should "storeModule" call twice (2 modules) container method "addModule"', () => { + const expectation = mockContainer.expects('addModule').twice(); + scanner.scan(TestModule as any); + expectation.verify(); + }); + + it('should "storeComponent" call twice (2 components) container method "addComponent"', () => { + const expectation = mockContainer.expects('addComponent').twice(); + const stub = sinon.stub(scanner, 'storeExportedComponent'); + + scanner.scan(TestModule as any); + expectation.verify(); + stub.restore(); + }); + + it('should "storeRoute" call twice (2 components) container method "addController"', () => { + const expectation = mockContainer.expects('addController').twice(); + scanner.scan(TestModule as any); + expectation.verify(); + }); + + it('should "storeExportedComponent" call once (1 component) container method "addExportedComponent"', () => { + const expectation = mockContainer.expects('addExportedComponent').once(); + scanner.scan(TestModule as any); + expectation.verify(); + }); + + describe('reflectDynamicMetadata', () => { + describe('when param has prototype', () => { + it('should call "reflectGuards" and "reflectInterceptors"', () => { + const reflectGuards = sinon + .stub(scanner, 'reflectGuards') + .callsFake(() => undefined); + const reflectInterceptors = sinon + .stub(scanner, 'reflectInterceptors') + .callsFake(() => undefined); + scanner.reflectDynamicMetadata({ prototype: true } as any, ''); + + expect(reflectGuards.called).to.be.true; + expect(reflectInterceptors.called).to.be.true; }); }); - - describe('storeInjectable', () => { - it('should call "addInjectable"', () => { - const addInjectable = sinon.stub((scanner as any).container, 'addInjectable').callsFake(() => undefined); - const comp = {}; - const token = 'token'; - - scanner.storeInjectable(comp as any, token); - expect(addInjectable.calledWith(comp, token)).to.be.true; + describe('when param has not prototype', () => { + it('should not call "reflectGuards" and "reflectInterceptors"', () => { + const reflectGuards = sinon + .stub(scanner, 'reflectGuards') + .callsFake(() => undefined); + const reflectInterceptors = sinon + .stub(scanner, 'reflectInterceptors') + .callsFake(() => undefined); + scanner.reflectDynamicMetadata({} as any, ''); + + expect(reflectGuards.called).to.be.false; + expect(reflectInterceptors.called).to.be.false; }); }); - - class CompMethod { - @UseGuards('test') - public method() {} - } - describe('reflectKeyMetadata', () => { - it('should return undefined', () => { - const result = scanner.reflectKeyMetadata(TestComponent, 'key', 'method'); - expect(result).to.be.undefined; - }); - it('should return array', () => { - const result = scanner.reflectKeyMetadata(CompMethod, GUARDS_METADATA, 'method'); - expect(result).to.be.eql(['test']); - }); + }); + + describe('storeInjectable', () => { + it('should call "addInjectable"', () => { + const addInjectable = sinon + .stub((scanner as any).container, 'addInjectable') + .callsFake(() => undefined); + const comp = {}; + const token = 'token'; + + scanner.storeInjectable(comp as any, token); + expect(addInjectable.calledWith(comp, token)).to.be.true; + }); + }); + + class CompMethod { + @UseGuards('test') + public method() {} + } + describe('reflectKeyMetadata', () => { + it('should return undefined', () => { + const result = scanner.reflectKeyMetadata(TestComponent, 'key', 'method'); + expect(result).to.be.undefined; }); + it('should return array', () => { + const result = scanner.reflectKeyMetadata( + CompMethod, + GUARDS_METADATA, + 'method' + ); + expect(result).to.be.eql(['test']); + }); + }); - describe('storeModule', () => { - it('should call forwardRef() when forwardRef property exists', () => { - const module = { forwardRef: sinon.spy() }; + describe('storeModule', () => { + it('should call forwardRef() when forwardRef property exists', () => { + const module = { forwardRef: sinon.spy() }; - sinon.stub(container, 'addModule').returns({}); - scanner.storeModule(module as any, [] as any); - expect(module.forwardRef.called).to.be.true; - }); + sinon.stub(container, 'addModule').returns({}); + scanner.storeModule(module as any, [] as any); + expect(module.forwardRef.called).to.be.true; }); + }); - describe('storeRelatedModule', () => { - it('should call forwardRef() when forwardRef property exists', () => { - const module = { forwardRef: sinon.stub().returns({}) }; + describe('storeRelatedModule', () => { + it('should call forwardRef() when forwardRef property exists', () => { + const module = { forwardRef: sinon.stub().returns({}) }; - sinon.stub(container, 'addRelatedModule').returns({}); - scanner.storeRelatedModule(module as any, [] as any); - expect(module.forwardRef.called).to.be.true; - }); + sinon.stub(container, 'addRelatedModule').returns({}); + scanner.storeRelatedModule(module as any, [] as any); + expect(module.forwardRef.called).to.be.true; }); -}); \ No newline at end of file + }); +}); diff --git a/src/core/test/services/reflector.service.spec.ts b/src/core/test/services/reflector.service.spec.ts index c7a59f1c699..d491110f5b9 100644 --- a/src/core/test/services/reflector.service.spec.ts +++ b/src/core/test/services/reflector.service.spec.ts @@ -15,4 +15,4 @@ describe('Reflector', () => { expect(reflector.get(key, Test)).to.eql(value); }); }); -}); \ No newline at end of file +}); diff --git a/src/index.ts b/src/index.ts index ad72ba367fb..ebf57eee311 100644 --- a/src/index.ts +++ b/src/index.ts @@ -7,4 +7,4 @@ export * from './common'; export * from './core/nest-factory'; -export * from './core/nest-application'; \ No newline at end of file +export * from './core/nest-application'; diff --git a/src/microservices/client/client-proxy-factory.ts b/src/microservices/client/client-proxy-factory.ts index 2915e98b216..15747600f73 100644 --- a/src/microservices/client/client-proxy-factory.ts +++ b/src/microservices/client/client-proxy-factory.ts @@ -6,12 +6,14 @@ import { ClientProxy } from './client-proxy'; import { Closeable } from '../interfaces/closeable.interface'; export class ClientProxyFactory { - public static create(metadata: ClientMetadata): ClientProxy & Closeable { - const { transport } = metadata; + public static create(metadata: ClientMetadata): ClientProxy & Closeable { + const { transport } = metadata; - switch (transport) { - case Transport.REDIS: return new ClientRedis(metadata); - default: return new ClientTCP(metadata); - } + switch (transport) { + case Transport.REDIS: + return new ClientRedis(metadata); + default: + return new ClientTCP(metadata); } -} \ No newline at end of file + } +} diff --git a/src/microservices/client/client-proxy.ts b/src/microservices/client/client-proxy.ts index d2931bfb554..4c2fa70f495 100644 --- a/src/microservices/client/client-proxy.ts +++ b/src/microservices/client/client-proxy.ts @@ -4,32 +4,32 @@ import { isNil } from '@nestjs/common/utils/shared.utils'; import { InvalidMessageException } from '../exceptions/invalid-message.exception'; export abstract class ClientProxy { - protected abstract sendSingleMessage(msg, callback: (err, result, disposed?: boolean) => void); + protected abstract sendSingleMessage( + msg, + callback: (err, result, disposed?: boolean) => void + ); - public send(pattern, data): Observable { - if (isNil(pattern) || isNil(data)) { - return Observable.throw(new InvalidMessageException()); - } - return Observable.create((observer: Observer) => { - this.sendSingleMessage( - { pattern, data }, - this.createObserver(observer), - ); - }); + public send(pattern, data): Observable { + if (isNil(pattern) || isNil(data)) { + return Observable.throw(new InvalidMessageException()); } + return Observable.create((observer: Observer) => { + this.sendSingleMessage({ pattern, data }, this.createObserver(observer)); + }); + } - protected createObserver(observer: Observer): (err, result, disposed?: boolean) => void { - return (err, result, disposed) => { - if (err) { - observer.error(err); - return; - } - else if (disposed) { - observer.complete(); - return; - } - observer.next(result); - }; - } - -} \ No newline at end of file + protected createObserver( + observer: Observer + ): (err, result, disposed?: boolean) => void { + return (err, result, disposed) => { + if (err) { + observer.error(err); + return; + } else if (disposed) { + observer.complete(); + return; + } + observer.next(result); + }; + } +} diff --git a/src/microservices/client/client-redis.ts b/src/microservices/client/client-redis.ts index e1bee9db237..be335ff99e1 100644 --- a/src/microservices/client/client-redis.ts +++ b/src/microservices/client/client-redis.ts @@ -8,72 +8,72 @@ const MESSAGE_EVENT = 'message'; const ERROR_EVENT = 'error'; export class ClientRedis extends ClientProxy { - private readonly logger = new Logger(ClientProxy.name); - private readonly url: string; + private readonly logger = new Logger(ClientProxy.name); + private readonly url: string; - private pub: redis.RedisClient; - private sub: redis.RedisClient; + private pub: redis.RedisClient; + private sub: redis.RedisClient; - constructor(metadata: ClientMetadata) { - super(); + constructor(metadata: ClientMetadata) { + super(); - const { url } = metadata; - this.url = url || DEFAULT_URL; - } - - protected sendSingleMessage(msg, callback: (...args) => any) { - if (!this.pub || !this.sub) { - this.init(callback); - } - const pattern = JSON.stringify(msg.pattern); - const responseCallback = (channel, message) => { - const { err, response, disposed } = JSON.parse(message); - if (disposed) { - callback(null, null, true); - this.sub.unsubscribe(this.getResPatternName(pattern)); - this.sub.removeListener(MESSAGE_EVENT, responseCallback); - return; - } - callback(err, response); - }; + const { url } = metadata; + this.url = url || DEFAULT_URL; + } - this.sub.on(MESSAGE_EVENT, responseCallback); - this.sub.subscribe(this.getResPatternName(pattern)); - this.pub.publish(this.getAckPatternName(pattern), JSON.stringify(msg)); - return responseCallback; + protected sendSingleMessage(msg, callback: (...args) => any) { + if (!this.pub || !this.sub) { + this.init(callback); } + const pattern = JSON.stringify(msg.pattern); + const responseCallback = (channel, message) => { + const { err, response, disposed } = JSON.parse(message); + if (disposed) { + callback(null, null, true); + this.sub.unsubscribe(this.getResPatternName(pattern)); + this.sub.removeListener(MESSAGE_EVENT, responseCallback); + return; + } + callback(err, response); + }; - public getAckPatternName(pattern: string): string { - return `${pattern}_ack`; - } + this.sub.on(MESSAGE_EVENT, responseCallback); + this.sub.subscribe(this.getResPatternName(pattern)); + this.pub.publish(this.getAckPatternName(pattern), JSON.stringify(msg)); + return responseCallback; + } - public getResPatternName(pattern: string): string { - return `${pattern}_res`; - } + public getAckPatternName(pattern: string): string { + return `${pattern}_ack`; + } - public close() { - this.pub && this.pub.quit(); - this.sub && this.sub.quit(); - } + public getResPatternName(pattern: string): string { + return `${pattern}_res`; + } - public init(callback: (...args) => any) { - this.pub = this.createClient(); - this.sub = this.createClient(); + public close() { + this.pub && this.pub.quit(); + this.sub && this.sub.quit(); + } - this.handleErrors(this.pub, callback); - this.handleErrors(this.sub, callback); - } + public init(callback: (...args) => any) { + this.pub = this.createClient(); + this.sub = this.createClient(); - public createClient(): redis.RedisClient { - return redis.createClient({ url: this.url }); - } + this.handleErrors(this.pub, callback); + this.handleErrors(this.sub, callback); + } - public handleErrors(stream, callback: (...args) => any) { - stream.on(ERROR_EVENT, (err) => { - if (err.code === 'ECONNREFUSED') { - callback(err, null); - } - this.logger.error(err); - }); - } -} \ No newline at end of file + public createClient(): redis.RedisClient { + return redis.createClient({ url: this.url }); + } + + public handleErrors(stream, callback: (...args) => any) { + stream.on(ERROR_EVENT, err => { + if (err.code === 'ECONNREFUSED') { + callback(err, null); + } + this.logger.error(err); + }); + } +} diff --git a/src/microservices/client/client-tcp.ts b/src/microservices/client/client-tcp.ts index 0e7a2afddc3..70dba13f2b4 100644 --- a/src/microservices/client/client-tcp.ts +++ b/src/microservices/client/client-tcp.ts @@ -12,74 +12,76 @@ const ERROR_EVENT = 'error'; const CLOSE_EVENT = 'close'; export class ClientTCP extends ClientProxy { - private readonly logger = new Logger(ClientTCP.name); - private readonly port: number; - private readonly host: string; - private isConnected = false; - private socket; + private readonly logger = new Logger(ClientTCP.name); + private readonly port: number; + private readonly host: string; + private isConnected = false; + private socket; - constructor({ port, host }: ClientMetadata) { - super(); - this.port = port || DEFAULT_PORT; - this.host = host || DEFAULT_HOST; - } + constructor({ port, host }: ClientMetadata) { + super(); + this.port = port || DEFAULT_PORT; + this.host = host || DEFAULT_HOST; + } - public init(callback: (...args) => any): Promise<{}> { - this.socket = this.createSocket(); + public init(callback: (...args) => any): Promise<{}> { + this.socket = this.createSocket(); - return new Promise((resolve) => { - this.bindEvents(this.socket, callback); - this.socket.on(CONNECT_EVENT, () => { - this.isConnected = true; - resolve(this.socket); - }); - this.socket.connect(this.port, this.host); - }); - } + return new Promise(resolve => { + this.bindEvents(this.socket, callback); + this.socket.on(CONNECT_EVENT, () => { + this.isConnected = true; + resolve(this.socket); + }); + this.socket.connect(this.port, this.host); + }); + } - protected async sendSingleMessage(msg, callback: (...args) => any) { - const sendMessage = (socket) => { - socket.sendMessage(msg); - socket.on(MESSAGE_EVENT, (buffer) => this.handleResponse(socket, callback, buffer)); - }; - if (this.isConnected) { - sendMessage(this.socket); - return Promise.resolve(); - } - const socket = await this.init(callback); - sendMessage(socket); + protected async sendSingleMessage(msg, callback: (...args) => any) { + const sendMessage = socket => { + socket.sendMessage(msg); + socket.on(MESSAGE_EVENT, buffer => + this.handleResponse(socket, callback, buffer) + ); + }; + if (this.isConnected) { + sendMessage(this.socket); + return Promise.resolve(); } + const socket = await this.init(callback); + sendMessage(socket); + } - public handleResponse(socket, callback: (...args) => any, buffer) { - const { err, response, disposed } = buffer; - if (disposed) { - callback(null, null, true); - socket.end(); - return; - } - callback(err, response); + public handleResponse(socket, callback: (...args) => any, buffer) { + const { err, response, disposed } = buffer; + if (disposed) { + callback(null, null, true); + socket.end(); + return; } + callback(err, response); + } - public createSocket() { - return new JsonSocket(new net.Socket()); - } + public createSocket() { + return new JsonSocket(new net.Socket()); + } - public close() { - this.socket && this.socket.end(); - this.isConnected = false; - this.socket = null; - } + public close() { + this.socket && this.socket.end(); + this.isConnected = false; + this.socket = null; + } - public bindEvents(socket, callback: (...args) => any) { - socket.on(ERROR_EVENT, (err) => { - if (err.code === 'ECONNREFUSED') { - callback(err, null); - } - this.logger.error(err); - }); - socket.on(CLOSE_EVENT, () => { - this.isConnected = false; - this.socket = null; - }); - } -} \ No newline at end of file + public bindEvents(socket, callback: (...args) => any) { + socket.on(ERROR_EVENT, err => { + if (err.code === 'ECONNREFUSED') { + callback(err, null); + } + this.logger.error(err); + }); + socket.on(CLOSE_EVENT, () => { + this.isConnected = false; + this.socket = null; + }); + } +} diff --git a/src/microservices/client/index.ts b/src/microservices/client/index.ts index 90c2b4d42d7..d6867e23115 100644 --- a/src/microservices/client/index.ts +++ b/src/microservices/client/index.ts @@ -1,2 +1,2 @@ export * from './client-proxy'; -export * from './client-proxy-factory'; \ No newline at end of file +export * from './client-proxy-factory'; diff --git a/src/microservices/constants.ts b/src/microservices/constants.ts index 1ab6178fff9..3edf701ab57 100644 --- a/src/microservices/constants.ts +++ b/src/microservices/constants.ts @@ -2,4 +2,4 @@ export const PATTERN_METADATA = 'pattern'; export const CLIENT_CONFIGURATION_METADATA = 'client'; export const CLIENT_METADATA = '__isClient'; export const PATTERN_HANDLER_METADATA = '__isPattern'; -export const NO_PATTERN_MESSAGE = `There's no equivalent message pattern.`; \ No newline at end of file +export const NO_PATTERN_MESSAGE = `There's no equivalent message pattern.`; diff --git a/src/microservices/container.ts b/src/microservices/container.ts index feee5e9ef45..bd585e88253 100644 --- a/src/microservices/container.ts +++ b/src/microservices/container.ts @@ -4,17 +4,17 @@ import { Closeable } from './interfaces/closeable.interface'; export type CloseableClient = Closeable & ClientProxy; export class ClientsContainer { - private clients: CloseableClient[] = []; + private clients: CloseableClient[] = []; - public getAllClients(): CloseableClient[] { - return this.clients; - } + public getAllClients(): CloseableClient[] { + return this.clients; + } - public addClient(client: CloseableClient) { - this.clients.push(client); - } + public addClient(client: CloseableClient) { + this.clients.push(client); + } - public clear() { - this.clients = []; - } -} \ No newline at end of file + public clear() { + this.clients = []; + } +} diff --git a/src/microservices/context/exception-filters-context.ts b/src/microservices/context/exception-filters-context.ts index 8260fbceb82..9ab8b206bfa 100644 --- a/src/microservices/context/exception-filters-context.ts +++ b/src/microservices/context/exception-filters-context.ts @@ -3,29 +3,43 @@ import iterate from 'iterare'; import { Controller } from '@nestjs/common/interfaces/controllers/controller.interface'; import { Observable } from 'rxjs/Observable'; import { RpcExceptionsHandler } from '../exceptions/rpc-exceptions-handler'; -import { EXCEPTION_FILTERS_METADATA, FILTER_CATCH_EXCEPTIONS } from '@nestjs/common/constants'; -import { isEmpty, isUndefined, isFunction } from '@nestjs/common/utils/shared.utils'; +import { + EXCEPTION_FILTERS_METADATA, + FILTER_CATCH_EXCEPTIONS +} from '@nestjs/common/constants'; +import { + isEmpty, + isUndefined, + isFunction +} from '@nestjs/common/utils/shared.utils'; import { RpcExceptionFilter } from '@nestjs/common/interfaces/exceptions'; import { Metatype } from '@nestjs/common/interfaces'; import { BaseExceptionFilterContext } from '@nestjs/core/exceptions/base-exception-filter-context'; import { ApplicationConfig } from '@nestjs/core/application-config'; export class ExceptionFiltersContext extends BaseExceptionFilterContext { - constructor(private readonly config: ApplicationConfig) { - super(); - } + constructor(private readonly config: ApplicationConfig) { + super(); + } - public create(instance: Controller, callback: (data) => Observable): RpcExceptionsHandler { - const exceptionHandler = new RpcExceptionsHandler(); - const filters = this.createContext(instance, callback, EXCEPTION_FILTERS_METADATA); - if (isEmpty(filters)) { - return exceptionHandler; - } - exceptionHandler.setCustomFilters(filters); - return exceptionHandler; + public create( + instance: Controller, + callback: (data) => Observable + ): RpcExceptionsHandler { + const exceptionHandler = new RpcExceptionsHandler(); + const filters = this.createContext( + instance, + callback, + EXCEPTION_FILTERS_METADATA + ); + if (isEmpty(filters)) { + return exceptionHandler; } + exceptionHandler.setCustomFilters(filters); + return exceptionHandler; + } - public getGlobalMetadata(): T { - return this.config.getGlobalFilters() as T; - } -} \ No newline at end of file + public getGlobalMetadata(): T { + return this.config.getGlobalFilters() as T; + } +} diff --git a/src/microservices/context/rpc-context-creator.ts b/src/microservices/context/rpc-context-creator.ts index ef280bcefb5..5497e6874fb 100644 --- a/src/microservices/context/rpc-context-creator.ts +++ b/src/microservices/context/rpc-context-creator.ts @@ -14,47 +14,71 @@ import { InterceptorsContextCreator } from '@nestjs/core/interceptors/intercepto import { InterceptorsConsumer } from '@nestjs/core/interceptors/interceptors-consumer'; export class RpcContextCreator { - constructor( - private readonly rpcProxy: RpcProxy, - private readonly exceptionFiltersContext: ExceptionFiltersContext, - private readonly pipesCreator: PipesContextCreator, - private readonly pipesConsumer: PipesConsumer, - private readonly guardsContextCreator: GuardsContextCreator, - private readonly guardsConsumer: GuardsConsumer, - private readonly interceptorsContextCreator: InterceptorsContextCreator, - private readonly interceptorsConsumer: InterceptorsConsumer) {} + constructor( + private readonly rpcProxy: RpcProxy, + private readonly exceptionFiltersContext: ExceptionFiltersContext, + private readonly pipesCreator: PipesContextCreator, + private readonly pipesConsumer: PipesConsumer, + private readonly guardsContextCreator: GuardsContextCreator, + private readonly guardsConsumer: GuardsConsumer, + private readonly interceptorsContextCreator: InterceptorsContextCreator, + private readonly interceptorsConsumer: InterceptorsConsumer + ) {} - public create( - instance: Controller, - callback: (data) => Observable, - module): (data) => Promise> { + public create( + instance: Controller, + callback: (data) => Observable, + module + ): (data) => Promise> { + const exceptionHandler = this.exceptionFiltersContext.create( + instance, + callback + ); + const pipes = this.pipesCreator.create(instance, callback); + const guards = this.guardsContextCreator.create(instance, callback, module); + const metatype = this.getDataMetatype(instance, callback); + const interceptors = this.interceptorsContextCreator.create( + instance, + callback, + module + ); - const exceptionHandler = this.exceptionFiltersContext.create(instance, callback); - const pipes = this.pipesCreator.create(instance, callback); - const guards = this.guardsContextCreator.create(instance, callback, module); - const metatype = this.getDataMetatype(instance, callback); - const interceptors = this.interceptorsContextCreator.create(instance, callback, module); + return this.rpcProxy.create(async data => { + const canActivate = await this.guardsConsumer.tryActivate( + guards, + data, + instance, + callback + ); + if (!canActivate) { + throw new RpcException(FORBIDDEN_MESSAGE); + } + const result = await this.pipesConsumer.applyPipes( + data, + { metatype }, + pipes + ); + const handler = () => callback.call(instance, result); - return this.rpcProxy.create(async (data) => { - const canActivate = await this.guardsConsumer.tryActivate(guards, data, instance, callback); - if (!canActivate) { - throw new RpcException(FORBIDDEN_MESSAGE); - } - const result = await this.pipesConsumer.applyPipes(data, { metatype }, pipes); - const handler = () => callback.call(instance, result); + return await this.interceptorsConsumer.intercept( + interceptors, + result, + instance, + callback, + handler + ); + }, exceptionHandler); + } - return await this.interceptorsConsumer.intercept( - interceptors, result, instance, callback, handler, - ); - }, exceptionHandler); - } + public reflectCallbackParamtypes( + instance: Controller, + callback: (...args) => any + ): any[] { + return Reflect.getMetadata(PARAMTYPES_METADATA, instance, callback.name); + } - public reflectCallbackParamtypes(instance: Controller, callback: (...args) => any): any[] { - return Reflect.getMetadata(PARAMTYPES_METADATA, instance, callback.name); - } - - public getDataMetatype(instance, callback) { - const paramtypes = this.reflectCallbackParamtypes(instance, callback); - return paramtypes && paramtypes.length ? paramtypes[0] : null; - } -} \ No newline at end of file + public getDataMetatype(instance, callback) { + const paramtypes = this.reflectCallbackParamtypes(instance, callback); + return paramtypes && paramtypes.length ? paramtypes[0] : null; + } +} diff --git a/src/microservices/context/rpc-proxy.ts b/src/microservices/context/rpc-proxy.ts index eb63553792f..c515e4d855c 100644 --- a/src/microservices/context/rpc-proxy.ts +++ b/src/microservices/context/rpc-proxy.ts @@ -2,17 +2,16 @@ import { Observable } from 'rxjs/Observable'; import { RpcExceptionsHandler } from '../exceptions/rpc-exceptions-handler'; export class RpcProxy { - public create( - targetCallback: (data) => Promise>, - exceptionsHandler: RpcExceptionsHandler): (data) => Promise> { - - return async (data) => { - try { - return await targetCallback(data); - } - catch (e) { - return exceptionsHandler.handle(e); - } - }; - } + public create( + targetCallback: (data) => Promise>, + exceptionsHandler: RpcExceptionsHandler + ): (data) => Promise> { + return async data => { + try { + return await targetCallback(data); + } catch (e) { + return exceptionsHandler.handle(e); + } + }; + } } diff --git a/src/microservices/enums/index.ts b/src/microservices/enums/index.ts index bfffee654dc..cce3c6aee76 100644 --- a/src/microservices/enums/index.ts +++ b/src/microservices/enums/index.ts @@ -1 +1 @@ -export * from './transport.enum'; \ No newline at end of file +export * from './transport.enum'; diff --git a/src/microservices/enums/transport.enum.ts b/src/microservices/enums/transport.enum.ts index f49db143306..5ae8544b15b 100644 --- a/src/microservices/enums/transport.enum.ts +++ b/src/microservices/enums/transport.enum.ts @@ -1,4 +1,4 @@ export enum Transport { - TCP, - REDIS, -} \ No newline at end of file + TCP, + REDIS +} diff --git a/src/microservices/exceptions/index.ts b/src/microservices/exceptions/index.ts index 444159f1aa7..b44d5af56bf 100644 --- a/src/microservices/exceptions/index.ts +++ b/src/microservices/exceptions/index.ts @@ -1 +1 @@ -export * from './rpc-exception'; \ No newline at end of file +export * from './rpc-exception'; diff --git a/src/microservices/exceptions/invalid-message.exception.ts b/src/microservices/exceptions/invalid-message.exception.ts index 4de67b2c0d6..4763d2b3566 100644 --- a/src/microservices/exceptions/invalid-message.exception.ts +++ b/src/microservices/exceptions/invalid-message.exception.ts @@ -1,7 +1,7 @@ import { RuntimeException } from '@nestjs/core/errors/exceptions/runtime.exception'; export class InvalidMessageException extends RuntimeException { - constructor() { - super(`Invalid message pattern or data!`); - } -} \ No newline at end of file + constructor() { + super(`Invalid message pattern or data!`); + } +} diff --git a/src/microservices/exceptions/rpc-exception.ts b/src/microservices/exceptions/rpc-exception.ts index ed9b47dd840..e35be23cc9a 100644 --- a/src/microservices/exceptions/rpc-exception.ts +++ b/src/microservices/exceptions/rpc-exception.ts @@ -1,7 +1,7 @@ export class RpcException { - constructor(private readonly error: string | object) {} + constructor(private readonly error: string | object) {} - public getError(): string | object { - return this.error; - } + public getError(): string | object { + return this.error; + } } diff --git a/src/microservices/exceptions/rpc-exceptions-handler.ts b/src/microservices/exceptions/rpc-exceptions-handler.ts index 5f18819b565..01c48936afb 100644 --- a/src/microservices/exceptions/rpc-exceptions-handler.ts +++ b/src/microservices/exceptions/rpc-exceptions-handler.ts @@ -46,7 +46,7 @@ export class RpcExceptionsHandler { const filter = this.filters.find(({ exceptionMetatypes, func }) => { const hasMetatype = !!exceptionMetatypes.find( - ExceptionMetatype => exception instanceof ExceptionMetatype, + ExceptionMetatype => exception instanceof ExceptionMetatype ); return hasMetatype; }); diff --git a/src/microservices/index.ts b/src/microservices/index.ts index dd9b41fdb5a..06380bf0c9b 100644 --- a/src/microservices/index.ts +++ b/src/microservices/index.ts @@ -11,4 +11,4 @@ export * from './client'; export * from './enums'; export * from './server'; export * from './exceptions'; -export * from './nest-microservice'; \ No newline at end of file +export * from './nest-microservice'; diff --git a/src/microservices/interfaces/client-metadata.interface.ts b/src/microservices/interfaces/client-metadata.interface.ts index aae32a9c98d..2cfa0031b10 100644 --- a/src/microservices/interfaces/client-metadata.interface.ts +++ b/src/microservices/interfaces/client-metadata.interface.ts @@ -1,8 +1,8 @@ import { Transport } from './../enums/transport.enum'; export interface ClientMetadata { - transport?: Transport; - url?: string; - port?: number; - host?: string; -} \ No newline at end of file + transport?: Transport; + url?: string; + port?: number; + host?: string; +} diff --git a/src/microservices/interfaces/closeable.interface.ts b/src/microservices/interfaces/closeable.interface.ts index c95c6501f80..a5cc2c694db 100644 --- a/src/microservices/interfaces/closeable.interface.ts +++ b/src/microservices/interfaces/closeable.interface.ts @@ -1,3 +1,3 @@ export interface Closeable { - close(): void; -} \ No newline at end of file + close(): void; +} diff --git a/src/microservices/interfaces/custom-transport-strategy.interface.ts b/src/microservices/interfaces/custom-transport-strategy.interface.ts index 215dfcefa1e..189ccd2f2b0 100644 --- a/src/microservices/interfaces/custom-transport-strategy.interface.ts +++ b/src/microservices/interfaces/custom-transport-strategy.interface.ts @@ -1,4 +1,4 @@ export interface CustomTransportStrategy { - listen(callback: () => void); - close(); -} \ No newline at end of file + listen(callback: () => void); + close(); +} diff --git a/src/microservices/interfaces/index.ts b/src/microservices/interfaces/index.ts index b7af58fe1ca..d385fc445b0 100644 --- a/src/microservices/interfaces/index.ts +++ b/src/microservices/interfaces/index.ts @@ -4,4 +4,4 @@ export * from './pattern-metadata.interface'; export * from './custom-transport-strategy.interface'; export * from './message-handlers.interface'; export * from './microservice-response.interface'; -export * from './closeable.interface'; \ No newline at end of file +export * from './closeable.interface'; diff --git a/src/microservices/interfaces/message-handlers.interface.ts b/src/microservices/interfaces/message-handlers.interface.ts index 9bc30033f86..2330a8ee925 100644 --- a/src/microservices/interfaces/message-handlers.interface.ts +++ b/src/microservices/interfaces/message-handlers.interface.ts @@ -1,5 +1,5 @@ import { Observable } from 'rxjs/Observable'; export interface MessageHandlers { - [pattern: string]: (data) => Promise>; -} \ No newline at end of file + [pattern: string]: (data) => Promise>; +} diff --git a/src/microservices/interfaces/microservice-configuration.interface.ts b/src/microservices/interfaces/microservice-configuration.interface.ts index ae64dff8f9b..463330fe7b9 100644 --- a/src/microservices/interfaces/microservice-configuration.interface.ts +++ b/src/microservices/interfaces/microservice-configuration.interface.ts @@ -3,9 +3,9 @@ import { CustomTransportStrategy } from './custom-transport-strategy.interface'; import { Server } from './../server/server'; export interface MicroserviceConfiguration { - transport?: Transport; - url?: string; - port?: number; - host?: string; - strategy?: Server & CustomTransportStrategy; -} \ No newline at end of file + transport?: Transport; + url?: string; + port?: number; + host?: string; + strategy?: Server & CustomTransportStrategy; +} diff --git a/src/microservices/interfaces/microservice-response.interface.ts b/src/microservices/interfaces/microservice-response.interface.ts index 67f1caba103..6ea59c3b46d 100644 --- a/src/microservices/interfaces/microservice-response.interface.ts +++ b/src/microservices/interfaces/microservice-response.interface.ts @@ -1,5 +1,5 @@ export interface MicroserviceResponse { - response?: any; - err?: any; - disposed?: boolean; -} \ No newline at end of file + response?: any; + err?: any; + disposed?: boolean; +} diff --git a/src/microservices/interfaces/pattern-metadata.interface.ts b/src/microservices/interfaces/pattern-metadata.interface.ts index 3ddaa708830..7c440634542 100644 --- a/src/microservices/interfaces/pattern-metadata.interface.ts +++ b/src/microservices/interfaces/pattern-metadata.interface.ts @@ -1,3 +1,3 @@ export interface PatternMetadata { - [prop: string]: any; -} \ No newline at end of file + [prop: string]: any; +} diff --git a/src/microservices/listener-metadata-explorer.ts b/src/microservices/listener-metadata-explorer.ts index 75c256a8fa2..aff45f517c3 100644 --- a/src/microservices/listener-metadata-explorer.ts +++ b/src/microservices/listener-metadata-explorer.ts @@ -1,60 +1,75 @@ import { Controller } from '@nestjs/common/interfaces/controllers/controller.interface'; import { isFunction, isUndefined } from '@nestjs/common/utils/shared.utils'; import { - PATTERN_METADATA, PATTERN_HANDLER_METADATA, CLIENT_CONFIGURATION_METADATA, - CLIENT_METADATA, + PATTERN_METADATA, + PATTERN_HANDLER_METADATA, + CLIENT_CONFIGURATION_METADATA, + CLIENT_METADATA } from './constants'; import { PatternMetadata } from './interfaces/pattern-metadata.interface'; import { ClientMetadata } from './interfaces/client-metadata.interface'; import { MetadataScanner } from '@nestjs/core/metadata-scanner'; export class ListenerMetadataExplorer { - constructor(private readonly metadataScanner: MetadataScanner) {} - - public explore(instance: Controller): PatternProperties[] { - const instancePrototype = Object.getPrototypeOf(instance); - return this.metadataScanner.scanFromPrototype( - instance, - instancePrototype, - (method) => this.exploreMethodMetadata(instance, instancePrototype, method), - ); - } + constructor(private readonly metadataScanner: MetadataScanner) {} + + public explore(instance: Controller): PatternProperties[] { + const instancePrototype = Object.getPrototypeOf(instance); + return this.metadataScanner.scanFromPrototype< + Controller, + PatternProperties + >(instance, instancePrototype, method => + this.exploreMethodMetadata(instance, instancePrototype, method) + ); + } + + public exploreMethodMetadata( + instance, + instancePrototype, + methodName: string + ): PatternProperties { + const targetCallback = instancePrototype[methodName]; + const isPattern = Reflect.getMetadata( + PATTERN_HANDLER_METADATA, + targetCallback + ); - public exploreMethodMetadata(instance, instancePrototype, methodName: string): PatternProperties { - const targetCallback = instancePrototype[methodName]; - const isPattern = Reflect.getMetadata(PATTERN_HANDLER_METADATA, targetCallback); - - if (isUndefined(isPattern)) { - return null; - } - const pattern = Reflect.getMetadata(PATTERN_METADATA, targetCallback); - return { - targetCallback, - pattern, - }; + if (isUndefined(isPattern)) { + return null; } + const pattern = Reflect.getMetadata(PATTERN_METADATA, targetCallback); + return { + targetCallback, + pattern + }; + } - public *scanForClientHooks(instance: Controller): IterableIterator { - for (const propertyKey in instance) { - if (isFunction(propertyKey)) continue; + public *scanForClientHooks( + instance: Controller + ): IterableIterator { + for (const propertyKey in instance) { + if (isFunction(propertyKey)) continue; - const property = String(propertyKey); - const isClient = Reflect.getMetadata(CLIENT_METADATA, instance, property); - if (isUndefined(isClient)) continue; + const property = String(propertyKey); + const isClient = Reflect.getMetadata(CLIENT_METADATA, instance, property); + if (isUndefined(isClient)) continue; - const metadata = Reflect.getMetadata(CLIENT_CONFIGURATION_METADATA, instance, property); - yield { property, metadata }; - } + const metadata = Reflect.getMetadata( + CLIENT_CONFIGURATION_METADATA, + instance, + property + ); + yield { property, metadata }; } - + } } export interface ClientProperties { - property: string; - metadata: ClientMetadata; + property: string; + metadata: ClientMetadata; } export interface PatternProperties { - pattern: PatternMetadata; - targetCallback: (...args) => any; -} \ No newline at end of file + pattern: PatternMetadata; + targetCallback: (...args) => any; +} diff --git a/src/microservices/listeners-controller.ts b/src/microservices/listeners-controller.ts index e70d0dfe8e0..483a245320e 100644 --- a/src/microservices/listeners-controller.ts +++ b/src/microservices/listeners-controller.ts @@ -9,26 +9,40 @@ import { ClientsContainer } from './container'; import { RpcContextCreator } from './context/rpc-context-creator'; export class ListenersController { - private readonly metadataExplorer = new ListenerMetadataExplorer(new MetadataScanner()); + private readonly metadataExplorer = new ListenerMetadataExplorer( + new MetadataScanner() + ); - constructor( - private readonly clientsContainer: ClientsContainer, - private readonly contextCreator: RpcContextCreator) {} + constructor( + private readonly clientsContainer: ClientsContainer, + private readonly contextCreator: RpcContextCreator + ) {} - public bindPatternHandlers(instance: Controller, server: Server & CustomTransportStrategy, module: string) { - const patternHandlers = this.metadataExplorer.explore(instance); - patternHandlers.forEach(({ pattern, targetCallback }) => { - const proxy = this.contextCreator.create(instance, targetCallback, module); - server.add(pattern, proxy); - }); - } + public bindPatternHandlers( + instance: Controller, + server: Server & CustomTransportStrategy, + module: string + ) { + const patternHandlers = this.metadataExplorer.explore(instance); + patternHandlers.forEach(({ pattern, targetCallback }) => { + const proxy = this.contextCreator.create( + instance, + targetCallback, + module + ); + server.add(pattern, proxy); + }); + } - public bindClientsToProperties(instance: Controller) { - for (const { property, metadata } of this.metadataExplorer.scanForClientHooks(instance)) { - const client = ClientProxyFactory.create(metadata); + public bindClientsToProperties(instance: Controller) { + for (const { + property, + metadata + } of this.metadataExplorer.scanForClientHooks(instance)) { + const client = ClientProxyFactory.create(metadata); - this.clientsContainer.addClient(client); - Reflect.set(instance, property, client); - } + this.clientsContainer.addClient(client); + Reflect.set(instance, property, client); } + } } diff --git a/src/microservices/microservices-module.ts b/src/microservices/microservices-module.ts index 1e054fe8734..4f044d0d01a 100644 --- a/src/microservices/microservices-module.ts +++ b/src/microservices/microservices-module.ts @@ -16,64 +16,67 @@ import { InterceptorsContextCreator } from '@nestjs/core/interceptors/intercepto import { InterceptorsConsumer } from '@nestjs/core/interceptors/interceptors-consumer'; export class MicroservicesModule { - private readonly clientsContainer = new ClientsContainer(); - private listenersController: ListenersController; + private readonly clientsContainer = new ClientsContainer(); + private listenersController: ListenersController; - public setup(container, config) { - const contextCreator = new RpcContextCreator( - new RpcProxy(), - new ExceptionFiltersContext(config), - new PipesContextCreator(config), - new PipesConsumer(), - new GuardsContextCreator(container, config), - new GuardsConsumer(), - new InterceptorsContextCreator(container, config), - new InterceptorsConsumer(), - ); - this.listenersController = new ListenersController( - this.clientsContainer, - contextCreator, - ); - } + public setup(container, config) { + const contextCreator = new RpcContextCreator( + new RpcProxy(), + new ExceptionFiltersContext(config), + new PipesContextCreator(config), + new PipesConsumer(), + new GuardsContextCreator(container, config), + new GuardsConsumer(), + new InterceptorsContextCreator(container, config), + new InterceptorsConsumer() + ); + this.listenersController = new ListenersController( + this.clientsContainer, + contextCreator + ); + } - public setupListeners(container, server: Server & CustomTransportStrategy) { - if (!this.listenersController) { - throw new RuntimeException(); - } - const modules = container.getModules(); - modules.forEach(({ routes }, module) => this.bindListeners(routes, server, module)); + public setupListeners(container, server: Server & CustomTransportStrategy) { + if (!this.listenersController) { + throw new RuntimeException(); } + const modules = container.getModules(); + modules.forEach(({ routes }, module) => + this.bindListeners(routes, server, module) + ); + } - public setupClients(container) { - if (!this.listenersController) { - throw new RuntimeException(); - } - const modules = container.getModules(); - modules.forEach(({ routes, components }) => { - this.bindClients(routes); - this.bindClients(components); - }); + public setupClients(container) { + if (!this.listenersController) { + throw new RuntimeException(); } + const modules = container.getModules(); + modules.forEach(({ routes, components }) => { + this.bindClients(routes); + this.bindClients(components); + }); + } - public bindListeners( - controllers: Map>, - server: Server & CustomTransportStrategy, - module: string) { + public bindListeners( + controllers: Map>, + server: Server & CustomTransportStrategy, + module: string + ) { + controllers.forEach(({ instance }) => { + this.listenersController.bindPatternHandlers(instance, server, module); + }); + } - controllers.forEach(({ instance }) => { - this.listenersController.bindPatternHandlers(instance, server, module); - }); - } + public bindClients(controllers: Map>) { + controllers.forEach(({ instance, isNotMetatype }) => { + !isNotMetatype && + this.listenersController.bindClientsToProperties(instance); + }); + } - public bindClients(controllers: Map>) { - controllers.forEach(({ instance, isNotMetatype }) => { - !isNotMetatype && this.listenersController.bindClientsToProperties(instance); - }); - } - - public close() { - const clients = this.clientsContainer.getAllClients(); - clients.forEach((client) => client.close()); - this.clientsContainer.clear(); - } -} \ No newline at end of file + public close() { + const clients = this.clientsContainer.getAllClients(); + clients.forEach(client => client.close()); + this.clientsContainer.clear(); + } +} diff --git a/src/microservices/nest-microservice.ts b/src/microservices/nest-microservice.ts index 4a0d91b6792..98dd7f85d0c 100644 --- a/src/microservices/nest-microservice.ts +++ b/src/microservices/nest-microservice.ts @@ -8,147 +8,159 @@ import { Server } from './server/server'; import { MicroserviceConfiguration } from './interfaces/microservice-configuration.interface'; import { ServerFactory } from './server/server-factory'; import { Transport } from './enums/transport.enum'; -import { INestMicroservice, WebSocketAdapter, CanActivate, PipeTransform, NestInterceptor, ExceptionFilter, OnModuleInit } from '@nestjs/common'; +import { + INestMicroservice, + WebSocketAdapter, + CanActivate, + PipeTransform, + NestInterceptor, + ExceptionFilter, + OnModuleInit +} from '@nestjs/common'; import { ApplicationConfig } from '@nestjs/core/application-config'; import { CustomTransportStrategy } from '@nestjs/microservices'; import { Module } from '@nestjs/core/injector/module'; import { isNil, isUndefined } from '@nestjs/common/utils/shared.utils'; import { OnModuleDestroy } from '@nestjs/common/interfaces'; -const { SocketModule } = optional('@nestjs/websockets/socket-module') || {} as any; -const { IoAdapter } = optional('@nestjs/websockets/adapters/io-adapter') || {} as any; +const { SocketModule } = + optional('@nestjs/websockets/socket-module') || ({} as any); +const { IoAdapter } = + optional('@nestjs/websockets/adapters/io-adapter') || ({} as any); export class NestMicroservice implements INestMicroservice { - private readonly logger = new Logger(NestMicroservice.name, true); - private readonly microservicesModule = new MicroservicesModule(); - private readonly socketModule = SocketModule - ? new SocketModule() - : null; - - private readonly microserviceConfig: MicroserviceConfiguration; - private readonly server: Server & CustomTransportStrategy; - private readonly config: ApplicationConfig; - private isTerminated = false; - private isInitialized = false; - private isInitHookCalled = false; - - constructor( - private readonly container: NestContainer, - config: MicroserviceConfiguration = {}, - ) { - const ioAdapter = IoAdapter ? new IoAdapter() : null; - this.config = new ApplicationConfig(ioAdapter); - - this.microservicesModule.setup(container, this.config); - this.microserviceConfig = { - transport: Transport.TCP, - ...config, - }; - const { strategy } = config; - this.server = strategy ? strategy : ServerFactory.create(this.microserviceConfig); - } - - public setupModules() { - this.socketModule && this.socketModule.setup(this.container, this.config); - this.microservicesModule.setupClients(this.container); - - this.setupListeners(); - this.setIsInitialized(true); - - !this.isInitHookCalled && this.callInitHook(); - } - - public setupListeners() { - this.microservicesModule.setupListeners(this.container, this.server); - } - - public useWebSocketAdapter(adapter: WebSocketAdapter) { - this.config.setIoAdapter(adapter); - } - - public useGlobalFilters(...filters: ExceptionFilter[]) { - this.config.useGlobalFilters(...filters); - } - - public useGlobalPipes(...pipes: PipeTransform[]) { - this.config.useGlobalPipes(...pipes); - } - - public useGlobalInterceptors(...interceptors: NestInterceptor[]) { - this.config.useGlobalInterceptors(...interceptors); - } - - public useGlobalGuards(...guards: CanActivate[]) { - this.config.useGlobalGuards(...guards); - } - - public listen(callback: () => void) { - (!this.isInitialized) && this.setupModules(); - - this.logger.log(messages.MICROSERVICE_READY); - this.server.listen(callback); - } - - public close() { - this.server.close(); - !this.isTerminated && this.closeApplication(); - } - - public setIsInitialized(isInitialized: boolean) { - this.isInitialized = isInitialized; - } - - public setIsTerminated(isTerminaed: boolean) { - this.isTerminated = isTerminaed; - } - - public setIsInitHookCalled(isInitHookCalled: boolean) { - this.isInitHookCalled = isInitHookCalled; - } - - private closeApplication() { - this.socketModule && this.socketModule.close(); - - this.callDestroyHook(); - this.setIsTerminated(true); - } - - private callInitHook() { - const modules = this.container.getModules(); - modules.forEach((module) => { - this.callModuleInitHook(module); - }); - this.setIsInitHookCalled(true); - } - - private callModuleInitHook(module: Module) { - const components = [...module.routes, ...module.components]; - iterate(components).map(([key, {instance}]) => instance) - .filter((instance) => !isNil(instance)) - .filter(this.hasOnModuleInitHook) - .forEach((instance) => (instance as OnModuleInit).onModuleInit()); - } - - private hasOnModuleInitHook(instance): instance is OnModuleInit { - return !isUndefined((instance as OnModuleInit).onModuleInit); - } - - private callDestroyHook() { - const modules = this.container.getModules(); - modules.forEach((module) => { - this.callModuleDestroyHook(module); - }); - } - - private callModuleDestroyHook(module: Module) { - const components = [...module.routes, ...module.components]; - iterate(components).map(([key, {instance}]) => instance) - .filter((instance) => !isNil(instance)) - .filter(this.hasOnModuleDestroyHook) - .forEach((instance) => (instance as OnModuleDestroy).onModuleDestroy()); - } - - private hasOnModuleDestroyHook(instance): instance is OnModuleDestroy { - return !isUndefined((instance as OnModuleDestroy).onModuleDestroy); - } -} \ No newline at end of file + private readonly logger = new Logger(NestMicroservice.name, true); + private readonly microservicesModule = new MicroservicesModule(); + private readonly socketModule = SocketModule ? new SocketModule() : null; + + private readonly microserviceConfig: MicroserviceConfiguration; + private readonly server: Server & CustomTransportStrategy; + private readonly config: ApplicationConfig; + private isTerminated = false; + private isInitialized = false; + private isInitHookCalled = false; + + constructor( + private readonly container: NestContainer, + config: MicroserviceConfiguration = {} + ) { + const ioAdapter = IoAdapter ? new IoAdapter() : null; + this.config = new ApplicationConfig(ioAdapter); + + this.microservicesModule.setup(container, this.config); + this.microserviceConfig = { + transport: Transport.TCP, + ...config + }; + const { strategy } = config; + this.server = strategy + ? strategy + : ServerFactory.create(this.microserviceConfig); + } + + public setupModules() { + this.socketModule && this.socketModule.setup(this.container, this.config); + this.microservicesModule.setupClients(this.container); + + this.setupListeners(); + this.setIsInitialized(true); + + !this.isInitHookCalled && this.callInitHook(); + } + + public setupListeners() { + this.microservicesModule.setupListeners(this.container, this.server); + } + + public useWebSocketAdapter(adapter: WebSocketAdapter) { + this.config.setIoAdapter(adapter); + } + + public useGlobalFilters(...filters: ExceptionFilter[]) { + this.config.useGlobalFilters(...filters); + } + + public useGlobalPipes(...pipes: PipeTransform[]) { + this.config.useGlobalPipes(...pipes); + } + + public useGlobalInterceptors(...interceptors: NestInterceptor[]) { + this.config.useGlobalInterceptors(...interceptors); + } + + public useGlobalGuards(...guards: CanActivate[]) { + this.config.useGlobalGuards(...guards); + } + + public listen(callback: () => void) { + !this.isInitialized && this.setupModules(); + + this.logger.log(messages.MICROSERVICE_READY); + this.server.listen(callback); + } + + public close() { + this.server.close(); + !this.isTerminated && this.closeApplication(); + } + + public setIsInitialized(isInitialized: boolean) { + this.isInitialized = isInitialized; + } + + public setIsTerminated(isTerminaed: boolean) { + this.isTerminated = isTerminaed; + } + + public setIsInitHookCalled(isInitHookCalled: boolean) { + this.isInitHookCalled = isInitHookCalled; + } + + private closeApplication() { + this.socketModule && this.socketModule.close(); + + this.callDestroyHook(); + this.setIsTerminated(true); + } + + private callInitHook() { + const modules = this.container.getModules(); + modules.forEach(module => { + this.callModuleInitHook(module); + }); + this.setIsInitHookCalled(true); + } + + private callModuleInitHook(module: Module) { + const components = [...module.routes, ...module.components]; + iterate(components) + .map(([key, { instance }]) => instance) + .filter(instance => !isNil(instance)) + .filter(this.hasOnModuleInitHook) + .forEach(instance => (instance as OnModuleInit).onModuleInit()); + } + + private hasOnModuleInitHook(instance): instance is OnModuleInit { + return !isUndefined((instance as OnModuleInit).onModuleInit); + } + + private callDestroyHook() { + const modules = this.container.getModules(); + modules.forEach(module => { + this.callModuleDestroyHook(module); + }); + } + + private callModuleDestroyHook(module: Module) { + const components = [...module.routes, ...module.components]; + iterate(components) + .map(([key, { instance }]) => instance) + .filter(instance => !isNil(instance)) + .filter(this.hasOnModuleDestroyHook) + .forEach(instance => (instance as OnModuleDestroy).onModuleDestroy()); + } + + private hasOnModuleDestroyHook(instance): instance is OnModuleDestroy { + return !isUndefined((instance as OnModuleDestroy).onModuleDestroy); + } +} diff --git a/src/microservices/server/index.ts b/src/microservices/server/index.ts index 7e59ff5d16e..0ce5251aa32 100644 --- a/src/microservices/server/index.ts +++ b/src/microservices/server/index.ts @@ -1 +1 @@ -export * from './server'; \ No newline at end of file +export * from './server'; diff --git a/src/microservices/server/server-factory.ts b/src/microservices/server/server-factory.ts index 6c381391376..66b1793f744 100644 --- a/src/microservices/server/server-factory.ts +++ b/src/microservices/server/server-factory.ts @@ -1,15 +1,22 @@ import { ServerTCP } from './server-tcp'; import { ServerRedis } from './server-redis'; -import { MicroserviceConfiguration, CustomTransportStrategy } from '../interfaces'; +import { + MicroserviceConfiguration, + CustomTransportStrategy +} from '../interfaces'; import { Server } from './server'; import { Transport } from '../enums/transport.enum'; export class ServerFactory { - public static create(config: MicroserviceConfiguration): Server & CustomTransportStrategy { - const { transport } = config; - switch (transport) { - case Transport.REDIS: return new ServerRedis(config); - default: return new ServerTCP(config); - } + public static create( + config: MicroserviceConfiguration + ): Server & CustomTransportStrategy { + const { transport } = config; + switch (transport) { + case Transport.REDIS: + return new ServerRedis(config); + default: + return new ServerTCP(config); } -} \ No newline at end of file + } +} diff --git a/src/microservices/server/server-redis.ts b/src/microservices/server/server-redis.ts index f2bb47cdb32..c0c18941eb8 100644 --- a/src/microservices/server/server-redis.ts +++ b/src/microservices/server/server-redis.ts @@ -14,91 +14,92 @@ const MESSAGE_EVENT = 'message'; const ERROR_EVENT = 'error'; export class ServerRedis extends Server implements CustomTransportStrategy { - private readonly url: string; - private sub = null; - private pub = null; - - constructor(config: MicroserviceConfiguration) { - super(); - this.url = config.url || DEFAULT_URL; - } - - public listen(callback: () => void) { - this.sub = this.createRedisClient(); - this.pub = this.createRedisClient(); - - this.handleErrors(this.pub); - this.handleErrors(this.sub); - this.start(callback); - } - - public start(callback?: () => void) { - this.sub.on(CONNECT_EVENT, () => this.handleConnection(callback, this.sub, this.pub)); + private readonly url: string; + private sub = null; + private pub = null; + + constructor(config: MicroserviceConfiguration) { + super(); + this.url = config.url || DEFAULT_URL; + } + + public listen(callback: () => void) { + this.sub = this.createRedisClient(); + this.pub = this.createRedisClient(); + + this.handleErrors(this.pub); + this.handleErrors(this.sub); + this.start(callback); + } + + public start(callback?: () => void) { + this.sub.on(CONNECT_EVENT, () => + this.handleConnection(callback, this.sub, this.pub) + ); + } + + public close() { + this.pub && this.pub.quit(); + this.sub && this.sub.quit(); + } + + public createRedisClient() { + return redis.createClient({ url: this.url }); + } + + public handleConnection(callback, sub, pub) { + sub.on(MESSAGE_EVENT, this.getMessageHandler(pub).bind(this)); + + const patterns = Object.keys(this.messageHandlers); + patterns.forEach(pattern => sub.subscribe(this.getAckQueueName(pattern))); + callback && callback(); + } + + public getMessageHandler(pub) { + return async (channel, buffer) => + await this.handleMessage(channel, buffer, pub); + } + + public async handleMessage(channel, buffer, pub) { + const msg = this.tryParse(buffer); + const pattern = channel.replace(/_ack$/, ''); + const publish = this.getPublisher(pub, pattern); + const status = 'error'; + + if (!this.messageHandlers[pattern]) { + publish({ status, error: NO_PATTERN_MESSAGE }); + return; } - - public close() { - this.pub && this.pub.quit(); - this.sub && this.sub.quit(); - } - - public createRedisClient() { - return redis.createClient({ url: this.url }); + const handler = this.messageHandlers[pattern]; + const response$ = this.transformToObservable( + await handler(msg.data) + ) as Observable; + response$ && this.send(response$, publish); + } + + public getPublisher(pub, pattern) { + return respond => { + pub.publish(this.getResQueueName(pattern), JSON.stringify(respond)); + }; + } + + public tryParse(content) { + try { + return JSON.parse(content); + } catch (e) { + return content; } + } - public handleConnection(callback, sub, pub) { - sub.on(MESSAGE_EVENT, this.getMessageHandler(pub).bind(this)); + public getAckQueueName(pattern) { + return `${pattern}_ack`; + } - const patterns = Object.keys(this.messageHandlers); - patterns.forEach((pattern) => sub.subscribe(this.getAckQueueName(pattern))); - callback && callback(); - } - - public getMessageHandler(pub) { - return async (channel, buffer) => await this.handleMessage(channel, buffer, pub); - } + public getResQueueName(pattern) { + return `${pattern}_res`; + } - public async handleMessage(channel, buffer, pub) { - const msg = this.tryParse(buffer); - const pattern = channel.replace(/_ack$/, ''); - const publish = this.getPublisher(pub, pattern); - const status = 'error'; - - if (!this.messageHandlers[pattern]) { - publish({ status, error: NO_PATTERN_MESSAGE }); - return; - } - const handler = this.messageHandlers[pattern]; - const response$ = this.transformToObservable(await handler(msg.data)) as Observable; - response$ && this.send(response$, publish); - } - - public getPublisher(pub, pattern) { - return (respond) => { - pub.publish( - this.getResQueueName(pattern), - JSON.stringify(respond), - ); - }; - } - - public tryParse(content) { - try { - return JSON.parse(content); - } - catch (e) { - return content; - } - } - - public getAckQueueName(pattern) { - return `${pattern}_ack`; - } - - public getResQueueName(pattern) { - return `${pattern}_res`; - } - - public handleErrors(stream) { - stream.on(ERROR_EVENT, (err) => this.logger.error(err)); - } -} \ No newline at end of file + public handleErrors(stream) { + stream.on(ERROR_EVENT, err => this.logger.error(err)); + } +} diff --git a/src/microservices/server/server-tcp.ts b/src/microservices/server/server-tcp.ts index 1c4a282310f..dfee4b06faf 100644 --- a/src/microservices/server/server-tcp.ts +++ b/src/microservices/server/server-tcp.ts @@ -14,48 +14,49 @@ const MESSAGE_EVENT = 'message'; const ERROR_EVENT = 'error'; export class ServerTCP extends Server implements CustomTransportStrategy { - private readonly port: number; - private server: NetSocket; - - constructor(config) { - super(); - this.port = config.port || DEFAULT_PORT; - this.init(); - } - - public listen(callback: () => void) { - this.server.listen(this.port, callback); - } - - public close() { - this.server.close(); - } - - public bindHandler(socket) { - const sock = this.getSocketInstance(socket); - sock.on(MESSAGE_EVENT, async msg => await this.handleMessage(sock, msg)); - } - - public async handleMessage(socket, msg: { pattern: any, data: {} }) { - const pattern = JSON.stringify(msg.pattern); - const status = 'error'; - if (!this.messageHandlers[pattern]) { - socket.sendMessage({ status, error: NO_PATTERN_MESSAGE }); - return; - } - - const handler = this.messageHandlers[pattern]; - const response$ = this.transformToObservable(await handler(msg.data)) as Observable; - response$ && this.send(response$, socket.sendMessage.bind(socket)); - } - - private init() { - this.server = net.createServer(this.bindHandler.bind(this)); - this.server.on(ERROR_EVENT, this.handleError.bind(this)); - } - - private getSocketInstance(socket) { - return new JsonSocket(socket); + private readonly port: number; + private server: NetSocket; + + constructor(config) { + super(); + this.port = config.port || DEFAULT_PORT; + this.init(); + } + + public listen(callback: () => void) { + this.server.listen(this.port, callback); + } + + public close() { + this.server.close(); + } + + public bindHandler(socket) { + const sock = this.getSocketInstance(socket); + sock.on(MESSAGE_EVENT, async msg => await this.handleMessage(sock, msg)); + } + + public async handleMessage(socket, msg: { pattern: any; data: {} }) { + const pattern = JSON.stringify(msg.pattern); + const status = 'error'; + if (!this.messageHandlers[pattern]) { + socket.sendMessage({ status, error: NO_PATTERN_MESSAGE }); + return; } -} \ No newline at end of file + const handler = this.messageHandlers[pattern]; + const response$ = this.transformToObservable( + await handler(msg.data) + ) as Observable; + response$ && this.send(response$, socket.sendMessage.bind(socket)); + } + + private init() { + this.server = net.createServer(this.bindHandler.bind(this)); + this.server.on(ERROR_EVENT, this.handleError.bind(this)); + } + + private getSocketInstance(socket) { + return new JsonSocket(socket); + } +} diff --git a/src/microservices/server/server.ts b/src/microservices/server/server.ts index 1233a4b344b..4b20f0513cf 100644 --- a/src/microservices/server/server.ts +++ b/src/microservices/server/server.ts @@ -10,37 +10,40 @@ import 'rxjs/add/observable/of'; import 'rxjs/add/observable/fromPromise'; export abstract class Server { - protected readonly messageHandlers: MessageHandlers = {}; - protected readonly logger = new Logger(Server.name); + protected readonly messageHandlers: MessageHandlers = {}; + protected readonly logger = new Logger(Server.name); - public getHandlers(): MessageHandlers { - return this.messageHandlers; - } + public getHandlers(): MessageHandlers { + return this.messageHandlers; + } - public add(pattern, callback: (data) => Promise>) { - this.messageHandlers[JSON.stringify(pattern)] = callback; - } + public add(pattern, callback: (data) => Promise>) { + this.messageHandlers[JSON.stringify(pattern)] = callback; + } - public send(stream$: Observable, respond: (data: MicroserviceResponse) => void): Subscription { - return stream$.catch((err) => { - respond({ err, response: null }); - return Observable.empty(); - }) - .finally(() => respond({ disposed: true })) - .subscribe((response) => respond({ err: null, response })); - } + public send( + stream$: Observable, + respond: (data: MicroserviceResponse) => void + ): Subscription { + return stream$ + .catch(err => { + respond({ err, response: null }); + return Observable.empty(); + }) + .finally(() => respond({ disposed: true })) + .subscribe(response => respond({ err: null, response })); + } - public transformToObservable(resultOrDeffered) { - if (resultOrDeffered instanceof Promise) { - return Observable.fromPromise(resultOrDeffered); - } - else if (!(resultOrDeffered instanceof Observable)) { - return Observable.of(resultOrDeffered); - } - return resultOrDeffered; + public transformToObservable(resultOrDeffered) { + if (resultOrDeffered instanceof Promise) { + return Observable.fromPromise(resultOrDeffered); + } else if (!(resultOrDeffered instanceof Observable)) { + return Observable.of(resultOrDeffered); } - - protected handleError(error: string) { - this.logger.error(error); - } -} \ No newline at end of file + return resultOrDeffered; + } + + protected handleError(error: string) { + this.logger.error(error); + } +} diff --git a/src/microservices/test/client/client-proxy-factory.spec.ts b/src/microservices/test/client/client-proxy-factory.spec.ts index 601f1a20526..b5f8c697d2c 100644 --- a/src/microservices/test/client/client-proxy-factory.spec.ts +++ b/src/microservices/test/client/client-proxy-factory.spec.ts @@ -5,15 +5,15 @@ import { Transport } from '../../enums/transport.enum'; import { ClientRedis } from '../../client/client-redis'; describe('ClientProxyFactory', () => { - describe('create', () => { - it(`should create tcp client by default`, () => { - const proxy = ClientProxyFactory.create({}); - expect(proxy instanceof ClientTCP).to.be.true; - }); + describe('create', () => { + it(`should create tcp client by default`, () => { + const proxy = ClientProxyFactory.create({}); + expect(proxy instanceof ClientTCP).to.be.true; + }); - it(`should create redis client`, () => { - const proxy = ClientProxyFactory.create({ transport: Transport.REDIS }); - expect(proxy instanceof ClientRedis).to.be.true; - }); + it(`should create redis client`, () => { + const proxy = ClientProxyFactory.create({ transport: Transport.REDIS }); + expect(proxy instanceof ClientRedis).to.be.true; }); -}); \ No newline at end of file + }); +}); diff --git a/src/microservices/test/client/client-proxy.spec.ts b/src/microservices/test/client/client-proxy.spec.ts index 54a33b8e87b..3fe241e9055 100644 --- a/src/microservices/test/client/client-proxy.spec.ts +++ b/src/microservices/test/client/client-proxy.spec.ts @@ -4,66 +4,66 @@ import { ClientProxy } from '../../client/client-proxy'; import { Observable } from 'rxjs'; class TestClientProxy extends ClientProxy { - public sendSingleMessage(pattern, callback) {} + public sendSingleMessage(pattern, callback) {} } describe('ClientProxy', () => { - const client = new TestClientProxy(); + const client = new TestClientProxy(); - describe('send', () => { - it(`should return an observable stream`, () => { - const stream$ = client.send({}, ''); - expect(stream$ instanceof Observable).to.be.true; - }); - it(`should call "sendSingleMessage" on subscribe`, () => { - const pattern = { test: 3 }; - const data = 'test'; - const sendSingleMessageSpy = sinon.spy(); - const stream$ = client.send(pattern, data); - client.sendSingleMessage = sendSingleMessageSpy; + describe('send', () => { + it(`should return an observable stream`, () => { + const stream$ = client.send({}, ''); + expect(stream$ instanceof Observable).to.be.true; + }); + it(`should call "sendSingleMessage" on subscribe`, () => { + const pattern = { test: 3 }; + const data = 'test'; + const sendSingleMessageSpy = sinon.spy(); + const stream$ = client.send(pattern, data); + client.sendSingleMessage = sendSingleMessageSpy; - stream$.subscribe(); - expect(sendSingleMessageSpy.calledOnce).to.be.true; - }); + stream$.subscribe(); + expect(sendSingleMessageSpy.calledOnce).to.be.true; }); + }); - describe('createObserver', () => { - it(`should return function`, () => { - expect(typeof client['createObserver'](null)).to.be.eql('function'); - }); + describe('createObserver', () => { + it(`should return function`, () => { + expect(typeof client['createObserver'](null)).to.be.eql('function'); + }); - describe('returned function calls', () => { - let fn; - const error = sinon.spy(), - next = sinon.spy(), - complete = sinon.spy(), - observer = { - error, - next, - complete, - }; + describe('returned function calls', () => { + let fn; + const error = sinon.spy(), + next = sinon.spy(), + complete = sinon.spy(), + observer = { + error, + next, + complete + }; - before(() => { - fn = client['createObserver'](observer); - }); + before(() => { + fn = client['createObserver'](observer); + }); - it(`"error" when first parameter is not null or undefined`, () => { - const err = 'test'; - fn(err); - expect(error.calledWith(err)).to.be.true; - }); + it(`"error" when first parameter is not null or undefined`, () => { + const err = 'test'; + fn(err); + expect(error.calledWith(err)).to.be.true; + }); - it(`"next" when first parameter is null or undefined`, () => { - const data = 'test'; - fn(null, data); - expect(next.calledWith(data)).to.be.true; - }); + it(`"next" when first parameter is null or undefined`, () => { + const data = 'test'; + fn(null, data); + expect(next.calledWith(data)).to.be.true; + }); - it(`"complete" when third parameter is true`, () => { - const data = 'test'; - fn(null, data, true); - expect(complete.called).to.be.true; - }); - }); + it(`"complete" when third parameter is true`, () => { + const data = 'test'; + fn(null, data, true); + expect(complete.called).to.be.true; + }); }); -}); \ No newline at end of file + }); +}); diff --git a/src/microservices/test/client/client-redis.spec.ts b/src/microservices/test/client/client-redis.spec.ts index aab52b83628..459697de555 100644 --- a/src/microservices/test/client/client-redis.spec.ts +++ b/src/microservices/test/client/client-redis.spec.ts @@ -3,167 +3,168 @@ import { expect } from 'chai'; import { ClientRedis } from '../../client/client-redis'; describe('ClientRedis', () => { - const test = 'test'; - const client = new ClientRedis({}); + const test = 'test'; + const client = new ClientRedis({}); - describe('getAckPatternName', () => { - it(`should append _ack to string`, () => { - const expectedResult = test + '_ack'; - expect(client.getAckPatternName(test)).to.equal((expectedResult)); - }); + describe('getAckPatternName', () => { + it(`should append _ack to string`, () => { + const expectedResult = test + '_ack'; + expect(client.getAckPatternName(test)).to.equal(expectedResult); }); - describe('getResPatternName', () => { - it(`should append _res to string`, () => { - const expectedResult = test + '_res'; - expect(client.getResPatternName(test)).to.equal((expectedResult)); - }); + }); + describe('getResPatternName', () => { + it(`should append _res to string`, () => { + const expectedResult = test + '_res'; + expect(client.getResPatternName(test)).to.equal(expectedResult); }); - describe('sendSingleMessage', () => { - const pattern = 'test'; - const msg = { pattern }; - let subscribeSpy: sinon.SinonSpy, - publishSpy: sinon.SinonSpy, - onSpy: sinon.SinonSpy, - removeListenerSpy: sinon.SinonSpy, - unsubscribeSpy: sinon.SinonSpy, - initSpy: sinon.SinonSpy, - sub, - pub; - - beforeEach(() => { - subscribeSpy = sinon.spy(); - publishSpy = sinon.spy(); - onSpy = sinon.spy(); - removeListenerSpy = sinon.spy(); - unsubscribeSpy = sinon.spy(); + }); + describe('sendSingleMessage', () => { + const pattern = 'test'; + const msg = { pattern }; + let subscribeSpy: sinon.SinonSpy, + publishSpy: sinon.SinonSpy, + onSpy: sinon.SinonSpy, + removeListenerSpy: sinon.SinonSpy, + unsubscribeSpy: sinon.SinonSpy, + initSpy: sinon.SinonSpy, + sub, + pub; - sub = { - subscribe: subscribeSpy, - on: onSpy, - removeListener: removeListenerSpy, - unsubscribe: unsubscribeSpy, - }; - pub = { publish: publishSpy }; - (client as any).sub = sub; - (client as any).pub = pub; - initSpy = sinon.spy(client, 'init'); - }); - afterEach(() => { - initSpy.restore(); - }); - it('should not call "init()" when pub and sub are null', () => { - client['sendSingleMessage'](msg, () => {}); - expect(initSpy.called).to.be.false; - }); - it('should call "init()" when pub and sub are null', () => { - (client as any).sub = null; - (client as any).pub = null; - client['sendSingleMessage'](msg, () => {}); - expect(initSpy.called).to.be.true; - }); - it('should subscribe to response pattern name', () => { - client['sendSingleMessage'](msg, () => {}); - expect(subscribeSpy.calledWith(`"${pattern}"_res`)).to.be.true; - }); - it('should publish stringified message to acknowledge pattern name', () => { - client['sendSingleMessage'](msg, () => {}); - expect(publishSpy.calledWith(`"${pattern}"_ack`, JSON.stringify(msg))).to.be.true; - }); - it('should listen on messages', () => { - client['sendSingleMessage'](msg, () => {}); - expect(onSpy.called).to.be.true; - }); - describe('responseCallback', () => { - let callback, subscription; - const resMsg = { - err: 'err', - response: 'test', - }; + beforeEach(() => { + subscribeSpy = sinon.spy(); + publishSpy = sinon.spy(); + onSpy = sinon.spy(); + removeListenerSpy = sinon.spy(); + unsubscribeSpy = sinon.spy(); - describe('not disposed', () => { - beforeEach(() => { - callback = sinon.spy(); - subscription = client['sendSingleMessage'](msg, callback); - subscription(null, JSON.stringify(resMsg)); - }); - it('should call callback with expected arguments', () => { - expect(callback.calledWith(resMsg.err, resMsg.response)).to.be.true; - }); - it('should not unsubscribe to response pattern name', () => { - expect(unsubscribeSpy.calledWith(`"${pattern}"_res`)).to.be.false; - }); - it('should not remove listener', () => { - expect(removeListenerSpy.called).to.be.false; - }); - }); - describe('disposed', () => { - beforeEach(() => { - callback = sinon.spy(); - subscription = client['sendSingleMessage'](msg, callback); - subscription(null, JSON.stringify({ disposed: true })); - }); - it('should call callback with dispose param', () => { - expect(callback.called).to.be.true; - expect(callback.calledWith(null, null, true)).to.be.true; - }); - it('should unsubscribe to response pattern name', () => { - expect(unsubscribeSpy.calledWith(`"${pattern}"_res`)).to.be.true; - }); - it('should remove listener', () => { - expect(removeListenerSpy.called).to.be.true; - }); - }); - }); + sub = { + subscribe: subscribeSpy, + on: onSpy, + removeListener: removeListenerSpy, + unsubscribe: unsubscribeSpy + }; + pub = { publish: publishSpy }; + (client as any).sub = sub; + (client as any).pub = pub; + initSpy = sinon.spy(client, 'init'); + }); + afterEach(() => { + initSpy.restore(); + }); + it('should not call "init()" when pub and sub are null', () => { + client['sendSingleMessage'](msg, () => {}); + expect(initSpy.called).to.be.false; + }); + it('should call "init()" when pub and sub are null', () => { + (client as any).sub = null; + (client as any).pub = null; + client['sendSingleMessage'](msg, () => {}); + expect(initSpy.called).to.be.true; + }); + it('should subscribe to response pattern name', () => { + client['sendSingleMessage'](msg, () => {}); + expect(subscribeSpy.calledWith(`"${pattern}"_res`)).to.be.true; }); - describe('close', () => { - let pubClose: sinon.SinonSpy; - let subClose: sinon.SinonSpy; - let pub, sub; + it('should publish stringified message to acknowledge pattern name', () => { + client['sendSingleMessage'](msg, () => {}); + expect(publishSpy.calledWith(`"${pattern}"_ack`, JSON.stringify(msg))).to + .be.true; + }); + it('should listen on messages', () => { + client['sendSingleMessage'](msg, () => {}); + expect(onSpy.called).to.be.true; + }); + describe('responseCallback', () => { + let callback, subscription; + const resMsg = { + err: 'err', + response: 'test' + }; + + describe('not disposed', () => { beforeEach(() => { - pubClose = sinon.spy(); - subClose = sinon.spy(); - pub = { quit: pubClose }; - sub = { quit: subClose }; - (client as any).pub = pub; - (client as any).sub = sub; - }); - it('should close "pub" when it is not null', () => { - client.close(); - expect(pubClose.called).to.be.true; + callback = sinon.spy(); + subscription = client['sendSingleMessage'](msg, callback); + subscription(null, JSON.stringify(resMsg)); }); - it('should not close "pub" when it is null', () => { - (client as any).pub = null; - client.close(); - expect(pubClose.called).to.be.false; + it('should call callback with expected arguments', () => { + expect(callback.calledWith(resMsg.err, resMsg.response)).to.be.true; }); - it('should close "sub" when it is not null', () => { - client.close(); - expect(subClose.called).to.be.true; + it('should not unsubscribe to response pattern name', () => { + expect(unsubscribeSpy.calledWith(`"${pattern}"_res`)).to.be.false; }); - it('should not close "sub" when it is null', () => { - (client as any).sub = null; - client.close(); - expect(subClose.called).to.be.false; + it('should not remove listener', () => { + expect(removeListenerSpy.called).to.be.false; }); - }); - describe('init', () => { - let createClientSpy: sinon.SinonSpy; - let handleErrorsSpy: sinon.SinonSpy; - + }); + describe('disposed', () => { beforeEach(() => { - createClientSpy = sinon.spy(client, 'createClient'); - handleErrorsSpy = sinon.spy(client, 'handleErrors'); - client.init(sinon.spy()); + callback = sinon.spy(); + subscription = client['sendSingleMessage'](msg, callback); + subscription(null, JSON.stringify({ disposed: true })); }); - afterEach(() => { - createClientSpy.restore(); - handleErrorsSpy.restore(); + it('should call callback with dispose param', () => { + expect(callback.called).to.be.true; + expect(callback.calledWith(null, null, true)).to.be.true; }); - it('should call "createClient" twice', () => { - expect(createClientSpy.calledTwice).to.be.true; + it('should unsubscribe to response pattern name', () => { + expect(unsubscribeSpy.calledWith(`"${pattern}"_res`)).to.be.true; }); - it('should call "handleErrors" twice', () => { - expect(handleErrorsSpy.calledTwice).to.be.true; + it('should remove listener', () => { + expect(removeListenerSpy.called).to.be.true; }); + }); + }); + }); + describe('close', () => { + let pubClose: sinon.SinonSpy; + let subClose: sinon.SinonSpy; + let pub, sub; + beforeEach(() => { + pubClose = sinon.spy(); + subClose = sinon.spy(); + pub = { quit: pubClose }; + sub = { quit: subClose }; + (client as any).pub = pub; + (client as any).sub = sub; + }); + it('should close "pub" when it is not null', () => { + client.close(); + expect(pubClose.called).to.be.true; + }); + it('should not close "pub" when it is null', () => { + (client as any).pub = null; + client.close(); + expect(pubClose.called).to.be.false; + }); + it('should close "sub" when it is not null', () => { + client.close(); + expect(subClose.called).to.be.true; + }); + it('should not close "sub" when it is null', () => { + (client as any).sub = null; + client.close(); + expect(subClose.called).to.be.false; + }); + }); + describe('init', () => { + let createClientSpy: sinon.SinonSpy; + let handleErrorsSpy: sinon.SinonSpy; + + beforeEach(() => { + createClientSpy = sinon.spy(client, 'createClient'); + handleErrorsSpy = sinon.spy(client, 'handleErrors'); + client.init(sinon.spy()); + }); + afterEach(() => { + createClientSpy.restore(); + handleErrorsSpy.restore(); + }); + it('should call "createClient" twice', () => { + expect(createClientSpy.calledTwice).to.be.true; + }); + it('should call "handleErrors" twice', () => { + expect(handleErrorsSpy.calledTwice).to.be.true; }); -}); \ No newline at end of file + }); +}); diff --git a/src/microservices/test/client/client-tcp.spec.ts b/src/microservices/test/client/client-tcp.spec.ts index e2accf52570..8820a96d5ec 100644 --- a/src/microservices/test/client/client-tcp.spec.ts +++ b/src/microservices/test/client/client-tcp.spec.ts @@ -3,106 +3,113 @@ import { expect } from 'chai'; import { ClientTCP } from '../../client/client-tcp'; describe('ClientTCP', () => { - const client = new ClientTCP({}); - let socket: { - connect: sinon.SinonSpy, - sendMessage: sinon.SinonSpy, - on: sinon.SinonStub, - end: sinon.SinonSpy, - }; - let createSocketStub: sinon.SinonStub; + const client = new ClientTCP({}); + let socket: { + connect: sinon.SinonSpy; + sendMessage: sinon.SinonSpy; + on: sinon.SinonStub; + end: sinon.SinonSpy; + }; + let createSocketStub: sinon.SinonStub; + beforeEach(() => { + socket = { + connect: sinon.spy(), + sendMessage: sinon.spy(), + on: sinon + .stub() + .callsFake( + (event, callback) => + event !== 'error' && event !== 'close' && callback({}) + ), + end: sinon.spy() + }; + createSocketStub = sinon + .stub(client, 'createSocket') + .callsFake(() => socket); + }); + afterEach(() => { + createSocketStub.restore(); + }); + describe('sendSingleMessage', () => { + let msg; beforeEach(() => { - socket = { - connect: sinon.spy(), - sendMessage: sinon.spy(), - on: sinon.stub().callsFake((event, callback) => event !== 'error' && event !== 'close' && callback({})), - end: sinon.spy(), - }; - createSocketStub = sinon.stub(client, 'createSocket').callsFake(() => socket); + msg = { test: 3 }; }); - afterEach(() => { - createSocketStub.restore(); + it('should connect to server when is not connected', done => { + client['sendSingleMessage'](msg, () => ({})).then(() => { + expect(socket.connect.calledOnce).to.be.true; + done(); + }); }); - describe('sendSingleMessage', () => { - let msg; - beforeEach(() => { - msg = { test: 3 }; - }); - it('should connect to server when is not connected', (done) => { - client['sendSingleMessage'](msg, () => ({})).then(() => { - expect(socket.connect.calledOnce).to.be.true; - done(); - }); - }); - it('should not connect to server when is already connected', () => { - (client as any).isConnected = true; - client['sendSingleMessage'](msg, () => ({})); - expect(socket.connect.called).to.be.false; - }); - describe('after connection', () => { - it('should send message', (done) => { - (client as any).isConnected = false; - client['sendSingleMessage'](msg, () => ({})).then(() => { - expect(socket.sendMessage.called).to.be.true; - expect(socket.sendMessage.calledWith(msg)).to.be.true; - done(); - }); - }); - it('should listen on messages', (done) => { - (client as any).isConnected = false; - client['sendSingleMessage'](msg, () => ({})).then(() => { - expect(socket.on.called).to.be.true; - done(); - }); - }); - }); + it('should not connect to server when is already connected', () => { + (client as any).isConnected = true; + client['sendSingleMessage'](msg, () => ({})); + expect(socket.connect.called).to.be.false; }); - describe('handleResponse', () => { - let callback; - describe('when disposed', () => { - beforeEach(() => { - callback = sinon.spy(); - client.handleResponse(socket, callback, { disposed: true }); - }); - it('should end server', () => { - expect(socket.end.called).to.be.true; - }); - it('should emit disposed callback', () => { - expect(callback.called).to.be.true; - expect(callback.calledWith(null, null, true)).to.be.true; - }); + describe('after connection', () => { + it('should send message', done => { + (client as any).isConnected = false; + client['sendSingleMessage'](msg, () => ({})).then(() => { + expect(socket.sendMessage.called).to.be.true; + expect(socket.sendMessage.calledWith(msg)).to.be.true; + done(); }); - describe('when not disposed', () => { - let buffer; - beforeEach(() => { - buffer = { err: 'test', response: 'res' }; - callback = sinon.spy(); - client.handleResponse(socket, callback, buffer); - }); - it('should not end server', () => { - expect(socket.end.called).to.be.false; - }); - it('should call callback with error and response data', () => { - expect(callback.called).to.be.true; - expect(callback.calledWith(buffer.err, buffer.response)).to.be.true; - }); + }); + it('should listen on messages', done => { + (client as any).isConnected = false; + client['sendSingleMessage'](msg, () => ({})).then(() => { + expect(socket.on.called).to.be.true; + done(); }); + }); }); - describe('close', () => { - beforeEach(() => { - (client as any).socket = socket; - (client as any).isConnected = true; - client.close(); - }); - it('should end() socket', () => { - expect(socket.end.called).to.be.true; - }); - it('should set "isConnected" to false', () => { - expect((client as any).isConnected).to.be.false; - }); - it('should set "socket" to null', () => { - expect((client as any).socket).to.be.null; - }); + }); + describe('handleResponse', () => { + let callback; + describe('when disposed', () => { + beforeEach(() => { + callback = sinon.spy(); + client.handleResponse(socket, callback, { disposed: true }); + }); + it('should end server', () => { + expect(socket.end.called).to.be.true; + }); + it('should emit disposed callback', () => { + expect(callback.called).to.be.true; + expect(callback.calledWith(null, null, true)).to.be.true; + }); + }); + describe('when not disposed', () => { + let buffer; + beforeEach(() => { + buffer = { err: 'test', response: 'res' }; + callback = sinon.spy(); + client.handleResponse(socket, callback, buffer); + }); + it('should not end server', () => { + expect(socket.end.called).to.be.false; + }); + it('should call callback with error and response data', () => { + expect(callback.called).to.be.true; + expect(callback.calledWith(buffer.err, buffer.response)).to.be.true; + }); + }); + }); + describe('close', () => { + beforeEach(() => { + (client as any).socket = socket; + (client as any).isConnected = true; + client.close(); + }); + it('should end() socket', () => { + expect(socket.end.called).to.be.true; + }); + it('should set "isConnected" to false', () => { + expect((client as any).isConnected).to.be.false; + }); + it('should set "socket" to null', () => { + expect((client as any).socket).to.be.null; }); -}); \ No newline at end of file + }); +}); diff --git a/src/microservices/test/container.spec.ts b/src/microservices/test/container.spec.ts index 6b06aafee4f..8b831539615 100644 --- a/src/microservices/test/container.spec.ts +++ b/src/microservices/test/container.spec.ts @@ -3,30 +3,30 @@ import { expect } from 'chai'; import { ClientsContainer } from '../container'; describe('ClientsContainer', () => { - let instance: ClientsContainer; - beforeEach(() => { - instance = new ClientsContainer(); + let instance: ClientsContainer; + beforeEach(() => { + instance = new ClientsContainer(); + }); + describe('getAllClients', () => { + it('should returns array of clients', () => { + const clients = [1, 2, 3]; + (instance as any).clients = clients; + expect(instance.getAllClients()).to.be.eql(clients); }); - describe('getAllClients', () => { - it('should returns array of clients', () => { - const clients = [ 1, 2, 3 ]; - (instance as any).clients = clients; - expect(instance.getAllClients()).to.be.eql(clients); - }); + }); + describe('addClient', () => { + it('should push client into clients array', () => { + const client = 'test'; + instance.addClient(client as any); + expect(instance.getAllClients()).to.be.deep.equal([client]); }); - describe('addClient', () => { - it('should push client into clients array', () => { - const client = 'test'; - instance.addClient(client as any); - expect(instance.getAllClients()).to.be.deep.equal([client]); - }); + }); + describe('clear', () => { + it('should remove all clients', () => { + const clients = [1, 2, 3]; + (instance as any).clients = clients; + instance.clear(); + expect(instance.getAllClients()).to.be.deep.equal([]); }); - describe('clear', () => { - it('should remove all clients', () => { - const clients = [ 1, 2, 3 ]; - (instance as any).clients = clients; - instance.clear(); - expect(instance.getAllClients()).to.be.deep.equal([]); - }); - }); -}); \ No newline at end of file + }); +}); diff --git a/src/microservices/test/context/exception-filters-context.spec.ts b/src/microservices/test/context/exception-filters-context.spec.ts index 9a94e6db52a..22abd2b866d 100644 --- a/src/microservices/test/context/exception-filters-context.spec.ts +++ b/src/microservices/test/context/exception-filters-context.spec.ts @@ -6,38 +6,46 @@ import { ExceptionFiltersContext } from './../../context/exception-filters-conte import { ApplicationConfig } from './../../../core/application-config'; describe('ExceptionFiltersContext', () => { - let moduleName: string; - let exceptionFilter: ExceptionFiltersContext; + let moduleName: string; + let exceptionFilter: ExceptionFiltersContext; - class CustomException {} - @Catch(CustomException) - class ExceptionFilter { - public catch(exc, res) {} - } + class CustomException {} + @Catch(CustomException) + class ExceptionFilter { + public catch(exc, res) {} + } - beforeEach(() => { - moduleName = 'Test'; - exceptionFilter = new ExceptionFiltersContext(new ApplicationConfig() as any); + beforeEach(() => { + moduleName = 'Test'; + exceptionFilter = new ExceptionFiltersContext( + new ApplicationConfig() as any + ); + }); + describe('create', () => { + describe('when filters metadata is empty', () => { + class EmptyMetadata {} + beforeEach(() => { + sinon.stub(exceptionFilter, 'createContext').returns([]); + }); + it('should returns plain ExceptionHandler object', () => { + const filter = exceptionFilter.create( + new EmptyMetadata(), + () => ({} as any) + ); + expect((filter as any).filters).to.be.empty; + }); }); - describe('create', () => { - describe('when filters metadata is empty', () => { - class EmptyMetadata {} - beforeEach(() => { - sinon.stub(exceptionFilter, 'createContext').returns([]); - }); - it('should returns plain ExceptionHandler object', () => { - const filter = exceptionFilter.create(new EmptyMetadata(), () => ({}) as any); - expect((filter as any).filters).to.be.empty; - }); - }); - describe('when filters metadata is not empty', () => { - @UseFilters(new ExceptionFilter()) - class WithMetadata {} + describe('when filters metadata is not empty', () => { + @UseFilters(new ExceptionFilter()) + class WithMetadata {} - it('should returns ExceptionHandler object with exception filters', () => { - const filter = exceptionFilter.create(new WithMetadata(), () => ({}) as any); - expect((filter as any).filters).to.not.be.empty; - }); - }); + it('should returns ExceptionHandler object with exception filters', () => { + const filter = exceptionFilter.create( + new WithMetadata(), + () => ({} as any) + ); + expect((filter as any).filters).to.not.be.empty; + }); }); -}); \ No newline at end of file + }); +}); diff --git a/src/microservices/test/context/rpc-context-creator.spec.ts b/src/microservices/test/context/rpc-context-creator.spec.ts index a941114b664..3a019bf674b 100644 --- a/src/microservices/test/context/rpc-context-creator.spec.ts +++ b/src/microservices/test/context/rpc-context-creator.spec.ts @@ -19,117 +19,144 @@ import { InterceptorsConsumer } from '../../../core/interceptors/interceptors-co import { ApplicationConfig } from '../../../core/application-config'; @Guard() -class TestGuard { canActivate: () => true; } +class TestGuard { + canActivate: () => true; +} @Pipe() class TestPipe { - transform(val) { - return val; - } + transform(val) { + return val; + } } describe('RpcContextCreator', () => { - let contextCreator: RpcContextCreator; - let rpcProxy: RpcProxy; - let exceptionFiltersContext: ExceptionFiltersContext; - let pipesCreator: PipesContextCreator; - let pipesConsumer: PipesConsumer; - let guardsContextCreator: GuardsContextCreator; - let guardsConsumer: GuardsConsumer; - let instance: Test; - let module: string; + let contextCreator: RpcContextCreator; + let rpcProxy: RpcProxy; + let exceptionFiltersContext: ExceptionFiltersContext; + let pipesCreator: PipesContextCreator; + let pipesConsumer: PipesConsumer; + let guardsContextCreator: GuardsContextCreator; + let guardsConsumer: GuardsConsumer; + let instance: Test; + let module: string; - @UseGuards(TestGuard) - @Component() - class Test { - @UsePipes(new TestPipe()) - test(data: string) { - return Observable.of(false); - } + @UseGuards(TestGuard) + @Component() + class Test { + @UsePipes(new TestPipe()) + test(data: string) { + return Observable.of(false); } + } - beforeEach(() => { - rpcProxy = new RpcProxy(); - exceptionFiltersContext = new ExceptionFiltersContext(new ApplicationConfig() as any); - pipesCreator = new PipesContextCreator(); - pipesConsumer = new PipesConsumer(); - guardsContextCreator = new GuardsContextCreator(new NestContainer()); - guardsConsumer = new GuardsConsumer(); - contextCreator = new RpcContextCreator( - rpcProxy, exceptionFiltersContext, pipesCreator as any, - pipesConsumer as any, guardsContextCreator as any, guardsConsumer as any, - new InterceptorsContextCreator(new NestContainer()) as any, new InterceptorsConsumer(), - ); + beforeEach(() => { + rpcProxy = new RpcProxy(); + exceptionFiltersContext = new ExceptionFiltersContext( + new ApplicationConfig() as any + ); + pipesCreator = new PipesContextCreator(); + pipesConsumer = new PipesConsumer(); + guardsContextCreator = new GuardsContextCreator(new NestContainer()); + guardsConsumer = new GuardsConsumer(); + contextCreator = new RpcContextCreator( + rpcProxy, + exceptionFiltersContext, + pipesCreator as any, + pipesConsumer as any, + guardsContextCreator as any, + guardsConsumer as any, + new InterceptorsContextCreator(new NestContainer()) as any, + new InterceptorsConsumer() + ); - instance = new Test(); - module = 'test'; + instance = new Test(); + module = 'test'; + }); + describe('create', () => { + it('should create exception handler', () => { + const handlerCreateSpy = sinon.spy(exceptionFiltersContext, 'create'); + contextCreator.create(instance, instance.test, module); + expect(handlerCreateSpy.calledWith(instance, instance.test)).to.be.true; }); - describe('create', () => { - it('should create exception handler', () => { - const handlerCreateSpy = sinon.spy(exceptionFiltersContext, 'create'); - contextCreator.create(instance, instance.test, module); - expect(handlerCreateSpy.calledWith(instance, instance.test)).to.be.true; - }); - it('should create pipes context', () => { - const pipesCreateSpy = sinon.spy(pipesCreator, 'create'); - contextCreator.create(instance, instance.test, module); - expect(pipesCreateSpy.calledWith(instance, instance.test)).to.be.true; - }); - it('should create guards context', () => { - const guardsCreateSpy = sinon.spy(guardsContextCreator, 'create'); - contextCreator.create(instance, instance.test, module); - expect(guardsCreateSpy.calledWith(instance, instance.test, module)).to.be.true; - }); - describe('when proxy called', () => { - it('should call guards consumer `tryActivate`', async () => { - const tryActivateSpy = sinon.spy(guardsConsumer, 'tryActivate'); - const proxy = await contextCreator.create(instance, instance.test, module); - const data = 'test'; - await proxy(data); + it('should create pipes context', () => { + const pipesCreateSpy = sinon.spy(pipesCreator, 'create'); + contextCreator.create(instance, instance.test, module); + expect(pipesCreateSpy.calledWith(instance, instance.test)).to.be.true; + }); + it('should create guards context', () => { + const guardsCreateSpy = sinon.spy(guardsContextCreator, 'create'); + contextCreator.create(instance, instance.test, module); + expect(guardsCreateSpy.calledWith(instance, instance.test, module)).to.be + .true; + }); + describe('when proxy called', () => { + it('should call guards consumer `tryActivate`', async () => { + const tryActivateSpy = sinon.spy(guardsConsumer, 'tryActivate'); + const proxy = await contextCreator.create( + instance, + instance.test, + module + ); + const data = 'test'; + await proxy(data); - expect(tryActivateSpy.called).to.be.true; - }); - describe('when can activate', () => { - it('should call pipes consumer `applyPipes`', async () => { - const applyPipesSpy = sinon.spy(pipesConsumer, 'applyPipes'); - const proxy = await contextCreator.create(instance, instance.test, module); - const data = 'test'; - await proxy(data); + expect(tryActivateSpy.called).to.be.true; + }); + describe('when can activate', () => { + it('should call pipes consumer `applyPipes`', async () => { + const applyPipesSpy = sinon.spy(pipesConsumer, 'applyPipes'); + const proxy = await contextCreator.create( + instance, + instance.test, + module + ); + const data = 'test'; + await proxy(data); - expect(applyPipesSpy.called).to.be.true; - }); - }); - describe('when can not activate', () => { - it('should throws forbidden exception', async () => { - const tryActivateStub = sinon.stub(guardsConsumer, 'tryActivate').returns(false); - const proxy = await contextCreator.create(instance, instance.test, module); - const data = 'test'; + expect(applyPipesSpy.called).to.be.true; + }); + }); + describe('when can not activate', () => { + it('should throws forbidden exception', async () => { + const tryActivateStub = sinon + .stub(guardsConsumer, 'tryActivate') + .returns(false); + const proxy = await contextCreator.create( + instance, + instance.test, + module + ); + const data = 'test'; - expect(proxy(data)).to.eventually.rejectedWith(RpcException); - }); - }); + expect(proxy(data)).to.eventually.rejectedWith(RpcException); }); + }); }); + }); - describe('reflectCallbackParamtypes', () => { - it('should returns paramtypes array', () => { - const paramtypes = contextCreator.reflectCallbackParamtypes(instance, instance.test); - expect(paramtypes).to.be.eql([String]); - }); + describe('reflectCallbackParamtypes', () => { + it('should returns paramtypes array', () => { + const paramtypes = contextCreator.reflectCallbackParamtypes( + instance, + instance.test + ); + expect(paramtypes).to.be.eql([String]); }); + }); - describe('getDataMetatype', () => { - describe('when paramtypes are reflected', () => { - it('should returns data paramtype', () => { - const type = contextCreator.getDataMetatype(instance, instance.test); - expect(type).to.be.eql(String); - }); - }); - describe('when paramtypes are not reflected', () => { - it('should returns null', () => { - const type = contextCreator.getDataMetatype(instance, () => ({})); - expect(type).to.be.null; - }); - }); + describe('getDataMetatype', () => { + describe('when paramtypes are reflected', () => { + it('should returns data paramtype', () => { + const type = contextCreator.getDataMetatype(instance, instance.test); + expect(type).to.be.eql(String); + }); + }); + describe('when paramtypes are not reflected', () => { + it('should returns null', () => { + const type = contextCreator.getDataMetatype(instance, () => ({})); + expect(type).to.be.null; + }); }); -}); \ No newline at end of file + }); +}); diff --git a/src/microservices/test/context/rpc-proxy.spec.ts b/src/microservices/test/context/rpc-proxy.spec.ts index 4f9d9493079..6eb173e8729 100644 --- a/src/microservices/test/context/rpc-proxy.spec.ts +++ b/src/microservices/test/context/rpc-proxy.spec.ts @@ -7,31 +7,32 @@ import { Observable } from 'rxjs/Observable'; import 'rxjs/add/observable/of'; describe('RpcProxy', () => { - let routerProxy: RpcProxy; - let handlerMock: sinon.SinonMock; - let handler: RpcExceptionsHandler; + let routerProxy: RpcProxy; + let handlerMock: sinon.SinonMock; + let handler: RpcExceptionsHandler; - beforeEach(() => { - handler = new RpcExceptionsHandler(); - handlerMock = sinon.mock(handler); - routerProxy = new RpcProxy(); - }); - - describe('create', () => { + beforeEach(() => { + handler = new RpcExceptionsHandler(); + handlerMock = sinon.mock(handler); + routerProxy = new RpcProxy(); + }); - it('should method return thunk', async () => { - const proxy = await routerProxy.create(async (data) => Observable.of(true), handler); - expect(typeof proxy === 'function').to.be.true; - }); - - it('should method encapsulate callback passed as argument', async () => { - const expectation = handlerMock.expects('handle').once(); - const proxy = routerProxy.create(async (data) => { - throw new RpcException('test'); - }, handler); - await proxy(null); - expectation.verify(); - }); + describe('create', () => { + it('should method return thunk', async () => { + const proxy = await routerProxy.create( + async data => Observable.of(true), + handler + ); + expect(typeof proxy === 'function').to.be.true; + }); + it('should method encapsulate callback passed as argument', async () => { + const expectation = handlerMock.expects('handle').once(); + const proxy = routerProxy.create(async data => { + throw new RpcException('test'); + }, handler); + await proxy(null); + expectation.verify(); }); -}); \ No newline at end of file + }); +}); diff --git a/src/microservices/test/exceptions/rpc-exception.spec.ts b/src/microservices/test/exceptions/rpc-exception.spec.ts index aa8b1eca743..daf278d382a 100644 --- a/src/microservices/test/exceptions/rpc-exception.spec.ts +++ b/src/microservices/test/exceptions/rpc-exception.spec.ts @@ -3,12 +3,12 @@ import { expect } from 'chai'; import { RpcException } from '../../exceptions/rpc-exception'; describe('RpcException', () => { - let instance: RpcException; - const error = 'test'; - beforeEach(() => { - instance = new RpcException(error); - }); - it('should returns error message or object', () => { - expect(instance.getError()).to.be.eql(error); - }); -}); \ No newline at end of file + let instance: RpcException; + const error = 'test'; + beforeEach(() => { + instance = new RpcException(error); + }); + it('should returns error message or object', () => { + expect(instance.getError()).to.be.eql(error); + }); +}); diff --git a/src/microservices/test/exceptions/rpc-exceptions-handler.spec.ts b/src/microservices/test/exceptions/rpc-exceptions-handler.spec.ts index fe8e6a5d893..ee32ce2843a 100644 --- a/src/microservices/test/exceptions/rpc-exceptions-handler.spec.ts +++ b/src/microservices/test/exceptions/rpc-exceptions-handler.spec.ts @@ -7,109 +7,115 @@ import 'rxjs/add/observable/of'; import 'rxjs/add/observable/empty'; describe('RpcExceptionsHandler', () => { - let handler: RpcExceptionsHandler; + let handler: RpcExceptionsHandler; - beforeEach(() => { - handler = new RpcExceptionsHandler(); + beforeEach(() => { + handler = new RpcExceptionsHandler(); + }); + + describe('handle', () => { + it('should method returns expected stream with message when exception is unknown', done => { + const stream$ = handler.handle(new Error()); + stream$ + .catch(err => { + expect(err).to.be.eql({ + status: 'error', + message: 'Internal server error' + }); + done(); + return Observable.empty(); + }) + .subscribe(() => ({})); }); + describe('when exception is instance of WsException', () => { + it('should method emit expected status and json object', done => { + const message = { + custom: 'Unauthorized' + }; + const stream$ = handler.handle(new RpcException(message)); + stream$ + .catch(err => { + expect(err).to.be.eql(message); + done(); + return Observable.empty(); + }) + .subscribe(() => ({})); + }); + it('should method emit expected status and transform message to json', done => { + const message = 'Unauthorized'; - describe('handle', () => { - it('should method returns expected stream with message when exception is unknown', (done) => { - const stream$ = handler.handle(new Error()); - stream$.catch((err) => { - expect(err).to.be.eql({ status: 'error', message: 'Internal server error' }); - done(); - return Observable.empty(); - }).subscribe(() => ({})); - }); - describe('when exception is instance of WsException', () => { - it('should method emit expected status and json object', (done) => { - const message = { - custom: 'Unauthorized', - }; - const stream$ = handler.handle(new RpcException(message)); - stream$.catch((err) => { - expect(err).to.be.eql(message); - done(); - return Observable.empty(); - }).subscribe(() => ({})); - }); - it('should method emit expected status and transform message to json', (done) => { - const message = 'Unauthorized'; + const stream$ = handler.handle(new RpcException(message)); + stream$ + .catch(err => { + expect(err).to.be.eql({ message, status: 'error' }); + done(); + return Observable.empty(); + }) + .subscribe(() => ({})); + }); + }); + describe('when "invokeCustomFilters" returns observable', () => { + const observable$ = Observable.of(true); + beforeEach(() => { + sinon.stub(handler, 'invokeCustomFilters').returns(observable$); + }); + it('should returns observable', () => { + const result = handler.handle(new RpcException('')); + expect(result).to.be.eql(observable$); + }); + }); + }); + describe('setCustomFilters', () => { + const filters = ['test', 'test2']; + it('should set custom filters', () => { + handler.setCustomFilters(filters as any); + expect((handler as any).filters).to.be.eql(filters); + }); + it('should throws exception when passed argument is not an array', () => { + expect(() => handler.setCustomFilters(null)).to.throw; + }); + }); + describe('invokeCustomFilters', () => { + describe('when filters array is empty', () => { + it('should returns identity', () => { + expect(handler.invokeCustomFilters(null)).to.be.null; + }); + }); + describe('when filters array is not empty', () => { + let filters, funcSpy; + class TestException {} - const stream$ = handler.handle(new RpcException(message)); - stream$.catch((err) => { - expect(err).to.be.eql({ message, status: 'error' }); - done(); - return Observable.empty(); - }).subscribe(() => ({})); - }); + beforeEach(() => { + funcSpy = sinon.spy(); + }); + describe('when filter exists in filters array', () => { + beforeEach(() => { + filters = [{ exceptionMetatypes: [TestException], func: funcSpy }]; + (handler as any).filters = filters; }); - describe('when "invokeCustomFilters" returns observable', () => { - const observable$ = Observable.of(true); - beforeEach(() => { - sinon.stub(handler, 'invokeCustomFilters').returns(observable$); - }); - it('should returns observable', () => { - const result = handler.handle(new RpcException('')); - expect(result).to.be.eql(observable$); - }); + it('should call funcSpy', () => { + handler.invokeCustomFilters(new TestException()); + expect(funcSpy.notCalled).to.be.false; }); - }); - describe('setCustomFilters', () => { - const filters = [ 'test', 'test2' ]; - it('should set custom filters', () => { - handler.setCustomFilters(filters as any); - expect((handler as any).filters).to.be.eql(filters); + it('should call funcSpy with exception and response passed as an arguments', () => { + const exception = new TestException(); + handler.invokeCustomFilters(exception); + expect(funcSpy.calledWith(exception)).to.be.true; }); - it('should throws exception when passed argument is not an array', () => { - expect( - () => handler.setCustomFilters(null), - ).to.throw; + it('should returns stream', () => { + expect(handler.invokeCustomFilters(new TestException())).to.be.not + .null; }); - }); - describe('invokeCustomFilters', () => { - describe('when filters array is empty', () => { - it('should returns identity', () => { - expect(handler.invokeCustomFilters(null)).to.be.null; - }); + }); + describe('when filter does not exists in filters array', () => { + it('should not call funcSpy', () => { + handler.invokeCustomFilters(new TestException()); + expect(funcSpy.notCalled).to.be.true; }); - describe('when filters array is not empty', () => { - let filters, funcSpy; - class TestException {} - - beforeEach(() => { - funcSpy = sinon.spy(); - }); - describe('when filter exists in filters array', () => { - beforeEach(() => { - filters = [ - { exceptionMetatypes: [ TestException ], func: funcSpy }, - ]; - (handler as any).filters = filters; - }); - it('should call funcSpy', () => { - handler.invokeCustomFilters(new TestException()); - expect(funcSpy.notCalled).to.be.false; - }); - it('should call funcSpy with exception and response passed as an arguments', () => { - const exception = new TestException(); - handler.invokeCustomFilters(exception); - expect(funcSpy.calledWith(exception)).to.be.true; - }); - it('should returns stream', () => { - expect(handler.invokeCustomFilters(new TestException())).to.be.not.null; - }); - }); - describe('when filter does not exists in filters array', () => { - it('should not call funcSpy', () => { - handler.invokeCustomFilters(new TestException()); - expect(funcSpy.notCalled).to.be.true; - }); - it('should returns null', () => { - expect(handler.invokeCustomFilters(new TestException())).to.be.null; - }); - }); + it('should returns null', () => { + expect(handler.invokeCustomFilters(new TestException())).to.be.null; }); + }); }); -}); \ No newline at end of file + }); +}); diff --git a/src/microservices/test/listeners-controller.spec.ts b/src/microservices/test/listeners-controller.spec.ts index 2af1a0da978..8b76be92978 100644 --- a/src/microservices/test/listeners-controller.spec.ts +++ b/src/microservices/test/listeners-controller.spec.ts @@ -7,33 +7,36 @@ import { ClientsContainer } from '../container'; import { RpcContextCreator } from '../context/rpc-context-creator'; describe('ListenersController', () => { - let instance: ListenersController, - explorer: sinon.SinonMock, - metadataExplorer: ListenerMetadataExplorer, - server, - addSpy: sinon.SinonSpy; + let instance: ListenersController, + explorer: sinon.SinonMock, + metadataExplorer: ListenerMetadataExplorer, + server, + addSpy: sinon.SinonSpy; - before(() => { - metadataExplorer = new ListenerMetadataExplorer(new MetadataScanner()); - explorer = sinon.mock(metadataExplorer); + before(() => { + metadataExplorer = new ListenerMetadataExplorer(new MetadataScanner()); + explorer = sinon.mock(metadataExplorer); + }); + beforeEach(() => { + instance = new ListenersController( + new ClientsContainer(), + sinon.createStubInstance(RpcContextCreator) as any + ); + (instance as any).metadataExplorer = metadataExplorer; + addSpy = sinon.spy(); + server = { + add: addSpy + }; + }); + describe('bindPatternHandlers', () => { + it(`should call add method of server for each pattern handler`, () => { + const handlers = [ + { pattern: 'test', targetCallback: 'tt' }, + { pattern: 'test2', targetCallback: '2' } + ]; + explorer.expects('explore').returns(handlers); + instance.bindPatternHandlers(null, server, ''); + expect(addSpy.calledTwice).to.be.true; }); - beforeEach(() => { - instance = new ListenersController(new ClientsContainer(), sinon.createStubInstance(RpcContextCreator) as any); - (instance as any).metadataExplorer = metadataExplorer; - addSpy = sinon.spy(); - server = { - add: addSpy, - }; - }); - describe('bindPatternHandlers', () => { - it(`should call add method of server for each pattern handler`, () => { - const handlers = [ - { pattern: 'test', targetCallback: 'tt' }, - { pattern: 'test2', targetCallback: '2' }, - ]; - explorer.expects('explore').returns(handlers); - instance.bindPatternHandlers(null, server, ''); - expect(addSpy.calledTwice).to.be.true; - }); - }); -}); \ No newline at end of file + }); +}); diff --git a/src/microservices/test/listeners-metadata-explorer.spec.ts b/src/microservices/test/listeners-metadata-explorer.spec.ts index b123fbaf18a..eed4b47ad67 100644 --- a/src/microservices/test/listeners-metadata-explorer.spec.ts +++ b/src/microservices/test/listeners-metadata-explorer.spec.ts @@ -7,72 +7,88 @@ import { Transport } from '../enums/transport.enum'; import { MetadataScanner } from '../../core/metadata-scanner'; describe('ListenerMetadataExplorer', () => { - const pattern = { pattern: 'test' }; - const secPattern = { role: '2', cmd: 'm' }; - const clientMetadata = {}; - const clientSecMetadata = { transport: Transport.REDIS }; + const pattern = { pattern: 'test' }; + const secPattern = { role: '2', cmd: 'm' }; + const clientMetadata = {}; + const clientSecMetadata = { transport: Transport.REDIS }; - class Test { - @Client(clientMetadata) public client; - @Client(clientSecMetadata) public redisClient; + class Test { + @Client(clientMetadata) public client; + @Client(clientSecMetadata) public redisClient; - get testGet() { return 0; } - set testSet(val) {} + get testGet() { + return 0; + } + set testSet(val) {} - constructor() {} + constructor() {} - @MessagePattern(pattern) - public test() {} + @MessagePattern(pattern) + public test() {} - @MessagePattern(secPattern) - public testSec() {} + @MessagePattern(secPattern) + public testSec() {} - public noPattern() {} - } - let scanner: MetadataScanner; - let instance: ListenerMetadataExplorer; + public noPattern() {} + } + let scanner: MetadataScanner; + let instance: ListenerMetadataExplorer; + beforeEach(() => { + scanner = new MetadataScanner(); + instance = new ListenerMetadataExplorer(scanner); + }); + describe('explore', () => { + let scanFromPrototype: sinon.SinonSpy; beforeEach(() => { - scanner = new MetadataScanner(); - instance = new ListenerMetadataExplorer(scanner); + scanFromPrototype = sinon.spy(scanner, 'scanFromPrototype'); }); - describe('explore', () => { - let scanFromPrototype: sinon.SinonSpy; - beforeEach(() => { - scanFromPrototype = sinon.spy(scanner, 'scanFromPrototype'); - }); - it(`should call "scanFromPrototype" with expected arguments`, () => { - const obj = new Test(); - instance.explore(obj); + it(`should call "scanFromPrototype" with expected arguments`, () => { + const obj = new Test(); + instance.explore(obj); - const { args } = scanFromPrototype.getCall(0); - expect(args[0]).to.be.eql(obj); - expect(args[1]).to.be.eql(Object.getPrototypeOf(obj)); - }); + const { args } = scanFromPrototype.getCall(0); + expect(args[0]).to.be.eql(obj); + expect(args[1]).to.be.eql(Object.getPrototypeOf(obj)); + }); + }); + describe('exploreMethodMetadata', () => { + let test: Test; + beforeEach(() => { + test = new Test(); + }); + it(`should return null when "isPattern" metadata is undefined`, () => { + const metadata = instance.exploreMethodMetadata( + test, + Object.getPrototypeOf(test), + 'noPattern' + ); + expect(metadata).to.eq(null); }); - describe('exploreMethodMetadata', () => { - let test: Test; - beforeEach(() => { - test = new Test(); - }); - it(`should return null when "isPattern" metadata is undefined`, () => { - const metadata = instance.exploreMethodMetadata(test, Object.getPrototypeOf(test), 'noPattern'); - expect(metadata).to.eq(null); - }); - it(`should return pattern properties when "isPattern" metadata is not undefined`, () => { - const metadata = instance.exploreMethodMetadata(test, Object.getPrototypeOf(test), 'test'); - expect(metadata).to.have.keys([ 'targetCallback', 'pattern' ]); - expect(metadata.pattern).to.eql(pattern); - }); + it(`should return pattern properties when "isPattern" metadata is not undefined`, () => { + const metadata = instance.exploreMethodMetadata( + test, + Object.getPrototypeOf(test), + 'test' + ); + expect(metadata).to.have.keys(['targetCallback', 'pattern']); + expect(metadata.pattern).to.eql(pattern); }); - describe('scanForClientHooks', () => { - it(`should returns properties with @Client decorator`, () => { - const obj = new Test(); - const hooks = [ ...instance.scanForClientHooks(obj) ]; + }); + describe('scanForClientHooks', () => { + it(`should returns properties with @Client decorator`, () => { + const obj = new Test(); + const hooks = [...instance.scanForClientHooks(obj)]; - expect(hooks).to.have.length(2); - expect(hooks[0]).to.deep.eq({ property: 'client', metadata: clientMetadata }); - expect(hooks[1]).to.deep.eq({ property: 'redisClient', metadata: clientSecMetadata }); - }); + expect(hooks).to.have.length(2); + expect(hooks[0]).to.deep.eq({ + property: 'client', + metadata: clientMetadata + }); + expect(hooks[1]).to.deep.eq({ + property: 'redisClient', + metadata: clientSecMetadata + }); }); -}); \ No newline at end of file + }); +}); diff --git a/src/microservices/test/server/server-factory.spec.ts b/src/microservices/test/server/server-factory.spec.ts index c9f5b97b5c5..39b8896ece0 100644 --- a/src/microservices/test/server/server-factory.spec.ts +++ b/src/microservices/test/server/server-factory.spec.ts @@ -5,12 +5,15 @@ import { ServerRedis } from '../../server/server-redis'; import { Transport } from '../../enums/transport.enum'; describe('ServerFactory', () => { - describe('create', () => { - it(`should return tcp server by default`, () => { - expect(ServerFactory.create({}) instanceof ServerTCP).to.be.true; - }); - it(`should return redis server if transport is set to redis`, () => { - expect(ServerFactory.create({ transport: Transport.REDIS }) instanceof ServerRedis).to.be.true; - }); + describe('create', () => { + it(`should return tcp server by default`, () => { + expect(ServerFactory.create({}) instanceof ServerTCP).to.be.true; }); -}); \ No newline at end of file + it(`should return redis server if transport is set to redis`, () => { + expect( + ServerFactory.create({ transport: Transport.REDIS }) instanceof + ServerRedis + ).to.be.true; + }); + }); +}); diff --git a/src/microservices/test/server/server-redis.spec.ts b/src/microservices/test/server/server-redis.spec.ts index 479a9049b6f..1ce8769cefd 100644 --- a/src/microservices/test/server/server-redis.spec.ts +++ b/src/microservices/test/server/server-redis.spec.ts @@ -5,151 +5,159 @@ import { ServerRedis } from '../../server/server-redis'; import { Observable } from 'rxjs/Observable'; describe('ServerRedis', () => { - let server: ServerRedis; + let server: ServerRedis; + beforeEach(() => { + server = new ServerRedis({}); + }); + describe('listen', () => { + let createRedisClient; + let onSpy: sinon.SinonSpy; + let client; + beforeEach(() => { - server = new ServerRedis({}); + onSpy = sinon.spy(); + client = { + on: onSpy + }; + createRedisClient = sinon + .stub(server, 'createRedisClient') + .callsFake(() => client); }); - describe('listen', () => { - let createRedisClient; - let onSpy: sinon.SinonSpy; - let client; - - beforeEach(() => { - onSpy = sinon.spy(); - client = { - on: onSpy, - }; - createRedisClient = sinon.stub(server, 'createRedisClient').callsFake(() => client); - }); - it('should bind "error" event to handler', () => { - server.listen(null); - expect(onSpy.getCall(0).args[0]).to.be.equal('error'); - }); - it('should bind "connect" event to handler', () => { - server.listen(null); - expect(onSpy.getCall(2).args[0]).to.be.equal('connect'); - }); - }); - describe('close', () => { - const pub = { quit: sinon.spy() }; - const sub = { quit: sinon.spy() }; - beforeEach(() => { - (server as any).pub = pub; - (server as any).sub = sub; - }); - it('should close pub & sub server', () => { - server.close(); + it('should bind "error" event to handler', () => { + server.listen(null); + expect(onSpy.getCall(0).args[0]).to.be.equal('error'); + }); + it('should bind "connect" event to handler', () => { + server.listen(null); + expect(onSpy.getCall(2).args[0]).to.be.equal('connect'); + }); + }); + describe('close', () => { + const pub = { quit: sinon.spy() }; + const sub = { quit: sinon.spy() }; + beforeEach(() => { + (server as any).pub = pub; + (server as any).sub = sub; + }); + it('should close pub & sub server', () => { + server.close(); - expect(pub.quit.called).to.be.true; - expect(sub.quit.called).to.be.true; - }); - }); - describe('handleConnection', () => { - let onSpy: sinon.SinonSpy, - subscribeSpy: sinon.SinonSpy, - sub; + expect(pub.quit.called).to.be.true; + expect(sub.quit.called).to.be.true; + }); + }); + describe('handleConnection', () => { + let onSpy: sinon.SinonSpy, subscribeSpy: sinon.SinonSpy, sub; - beforeEach(() => { - onSpy = sinon.spy(); - subscribeSpy = sinon.spy(); - sub = { - on: onSpy, - subscribe: subscribeSpy, - }; - }); - it('should bind "message" event to handler', () => { - server.handleConnection(null, sub, null); - expect(onSpy.getCall(0).args[0]).to.be.equal('message') - }); - it('should subscribe each acknowledge patterns', () => { - const pattern = 'test'; - const handler = sinon.spy(); - (server as any).messageHandlers = { - [pattern]: handler, - }; - server.handleConnection(null, sub, null); + beforeEach(() => { + onSpy = sinon.spy(); + subscribeSpy = sinon.spy(); + sub = { + on: onSpy, + subscribe: subscribeSpy + }; + }); + it('should bind "message" event to handler', () => { + server.handleConnection(null, sub, null); + expect(onSpy.getCall(0).args[0]).to.be.equal('message'); + }); + it('should subscribe each acknowledge patterns', () => { + const pattern = 'test'; + const handler = sinon.spy(); + (server as any).messageHandlers = { + [pattern]: handler + }; + server.handleConnection(null, sub, null); - const expectedPattern = 'test_ack'; - expect(subscribeSpy.calledWith(expectedPattern)).to.be.true; - }); - it('should call callback if exists', () => { - const callback = sinon.spy(); - server.handleConnection(callback, sub, null); - expect(callback.calledOnce).to.be.true; - }); - }); - describe('getMessageHandler', () => { - it(`should return function`, () => { - expect(typeof server.getMessageHandler(null)).to.be.eql('function'); - }); - }); - describe('handleMessage', () => { - let getPublisherSpy: sinon.SinonSpy; - const channel = 'test'; - const data = 'test'; + const expectedPattern = 'test_ack'; + expect(subscribeSpy.calledWith(expectedPattern)).to.be.true; + }); + it('should call callback if exists', () => { + const callback = sinon.spy(); + server.handleConnection(callback, sub, null); + expect(callback.calledOnce).to.be.true; + }); + }); + describe('getMessageHandler', () => { + it(`should return function`, () => { + expect(typeof server.getMessageHandler(null)).to.be.eql('function'); + }); + }); + describe('handleMessage', () => { + let getPublisherSpy: sinon.SinonSpy; + const channel = 'test'; + const data = 'test'; - beforeEach(() => { - getPublisherSpy = sinon.spy(); - sinon.stub(server, 'getPublisher').callsFake(() => getPublisherSpy); - sinon.stub(server, 'tryParse').callsFake(() => ({ data })); - }); - it(`should publish NO_PATTERN_MESSAGE if pattern not exists in messageHandlers object`, () => { - server.handleMessage(channel, {}, null); - expect(getPublisherSpy.calledWith({ status: 'error', error: NO_PATTERN_MESSAGE })).to.be.true; - }); - it(`should call handler with expected arguments`, () => { - const handler = sinon.spy(); - (server as any).messageHandlers = { - [channel]: handler, - }; + beforeEach(() => { + getPublisherSpy = sinon.spy(); + sinon.stub(server, 'getPublisher').callsFake(() => getPublisherSpy); + sinon.stub(server, 'tryParse').callsFake(() => ({ data })); + }); + it(`should publish NO_PATTERN_MESSAGE if pattern not exists in messageHandlers object`, () => { + server.handleMessage(channel, {}, null); + expect( + getPublisherSpy.calledWith({ + status: 'error', + error: NO_PATTERN_MESSAGE + }) + ).to.be.true; + }); + it(`should call handler with expected arguments`, () => { + const handler = sinon.spy(); + (server as any).messageHandlers = { + [channel]: handler + }; - server.handleMessage(channel, {}, null); - expect(handler.calledWith(data)).to.be.true; - }); - }); - describe('getPublisher', () => { - let publisherSpy: sinon.SinonSpy; - let pub, publisher; - const pattern = 'test'; + server.handleMessage(channel, {}, null); + expect(handler.calledWith(data)).to.be.true; + }); + }); + describe('getPublisher', () => { + let publisherSpy: sinon.SinonSpy; + let pub, publisher; + const pattern = 'test'; - beforeEach(() => { - publisherSpy = sinon.spy(); - pub = { - publish: publisherSpy, - }; - publisher = server.getPublisher(pub, pattern); - }); - it(`should return function`, () => { - expect(typeof server.getPublisher(null, null)).to.be.eql('function'); - }); - it(`should call "publish" with expected arguments`, () => { - const respond = 'test'; - publisher(respond); - expect(publisherSpy.calledWith(`${pattern}_res`, JSON.stringify(respond))).to.be.true; - }); - }); - describe('tryParse', () => { - it(`should return parsed json`, () => { - const obj = { test: 'test' }; - expect(server.tryParse(obj)).to.deep.equal(JSON.parse(JSON.stringify(obj))); - }); - it(`should not parse argument if it is not an object`, () => { - const content = 'test'; - expect(server.tryParse(content)).to.equal(content); - }); - }); - describe('getAckPatternName', () => { - const test = 'test'; - it(`should append _ack to string`, () => { - const expectedResult = test + '_ack'; - expect(server.getAckQueueName(test)).to.equal(expectedResult); - }); - }); - describe('getResPatternName', () => { - const test = 'test'; - it(`should append _res to string`, () => { - const expectedResult = test + '_res'; - expect(server.getResQueueName(test)).to.equal(expectedResult); - }); - }); -}); \ No newline at end of file + beforeEach(() => { + publisherSpy = sinon.spy(); + pub = { + publish: publisherSpy + }; + publisher = server.getPublisher(pub, pattern); + }); + it(`should return function`, () => { + expect(typeof server.getPublisher(null, null)).to.be.eql('function'); + }); + it(`should call "publish" with expected arguments`, () => { + const respond = 'test'; + publisher(respond); + expect(publisherSpy.calledWith(`${pattern}_res`, JSON.stringify(respond))) + .to.be.true; + }); + }); + describe('tryParse', () => { + it(`should return parsed json`, () => { + const obj = { test: 'test' }; + expect(server.tryParse(obj)).to.deep.equal( + JSON.parse(JSON.stringify(obj)) + ); + }); + it(`should not parse argument if it is not an object`, () => { + const content = 'test'; + expect(server.tryParse(content)).to.equal(content); + }); + }); + describe('getAckPatternName', () => { + const test = 'test'; + it(`should append _ack to string`, () => { + const expectedResult = test + '_ack'; + expect(server.getAckQueueName(test)).to.equal(expectedResult); + }); + }); + describe('getResPatternName', () => { + const test = 'test'; + it(`should append _res to string`, () => { + const expectedResult = test + '_res'; + expect(server.getResQueueName(test)).to.equal(expectedResult); + }); + }); +}); diff --git a/src/microservices/test/server/server-tcp.spec.ts b/src/microservices/test/server/server-tcp.spec.ts index b48ba2176b0..7b2e56c8cfe 100644 --- a/src/microservices/test/server/server-tcp.spec.ts +++ b/src/microservices/test/server/server-tcp.spec.ts @@ -4,66 +4,73 @@ import { ServerTCP } from '../../server/server-tcp'; import { NO_PATTERN_MESSAGE } from '../../constants'; describe('ServerTCP', () => { - let server: ServerTCP; + let server: ServerTCP; + beforeEach(() => { + server = new ServerTCP({}); + }); + + describe('bindHandler', () => { + let getSocketInstance; + const socket = { on: sinon.spy() }; beforeEach(() => { - server = new ServerTCP({}); + getSocketInstance = sinon + .stub(server, 'getSocketInstance') + .callsFake(() => socket); }); - - describe('bindHandler', () => { - let getSocketInstance; - const socket = { on: sinon.spy() }; - beforeEach(() => { - getSocketInstance = sinon.stub(server, 'getSocketInstance').callsFake(() => socket); - }); - it('should bind message event to handler', () => { - server.bindHandler(null); - expect(socket.on.called).to.be.true; - }); + it('should bind message event to handler', () => { + server.bindHandler(null); + expect(socket.on.called).to.be.true; }); - describe('close', () => { - const tcpServer = { close: sinon.spy() }; - beforeEach(() => { - (server as any).server = tcpServer; - }); - it('should close server', () => { - server.close(); - expect(tcpServer.close.called).to.be.true; - }); + }); + describe('close', () => { + const tcpServer = { close: sinon.spy() }; + beforeEach(() => { + (server as any).server = tcpServer; }); - describe('listen', () => { - const serverMock = { listen: sinon.spy() }; - beforeEach(() => { - (server as any).server = serverMock; - }); - it('should call native listen method with expected arguments', () => { - const callback = () => {}; - server.listen(callback); - expect(serverMock.listen.calledWith((server as any).port, callback)).to.be.true; - }); + it('should close server', () => { + server.close(); + expect(tcpServer.close.called).to.be.true; }); - describe('handleMessage', () => { - let socket; - const msg = { - pattern: 'test', - data: 'tests', - }; - beforeEach(() => { - socket = { - sendMessage: sinon.spy(), - }; - }); - it('should send NO_PATTERN_MESSAGE error if key is not exists in handlers object', () => { - server.handleMessage(socket, msg); - expect(socket.sendMessage.calledWith({ status: 'error', error: NO_PATTERN_MESSAGE })).to.be.true; - }); - it('should call handler if exists in handlers object', () => { - const handler = sinon.spy(); - (server as any).messageHandlers = { - [JSON.stringify(msg.pattern)]: handler as any, - }; - server.handleMessage(socket, msg); - expect(handler.calledOnce).to.be.true; - }); + }); + describe('listen', () => { + const serverMock = { listen: sinon.spy() }; + beforeEach(() => { + (server as any).server = serverMock; }); - -}); \ No newline at end of file + it('should call native listen method with expected arguments', () => { + const callback = () => {}; + server.listen(callback); + expect(serverMock.listen.calledWith((server as any).port, callback)).to.be + .true; + }); + }); + describe('handleMessage', () => { + let socket; + const msg = { + pattern: 'test', + data: 'tests' + }; + beforeEach(() => { + socket = { + sendMessage: sinon.spy() + }; + }); + it('should send NO_PATTERN_MESSAGE error if key is not exists in handlers object', () => { + server.handleMessage(socket, msg); + expect( + socket.sendMessage.calledWith({ + status: 'error', + error: NO_PATTERN_MESSAGE + }) + ).to.be.true; + }); + it('should call handler if exists in handlers object', () => { + const handler = sinon.spy(); + (server as any).messageHandlers = { + [JSON.stringify(msg.pattern)]: handler as any + }; + server.handleMessage(socket, msg); + expect(handler.calledOnce).to.be.true; + }); + }); +}); diff --git a/src/microservices/test/server/server.spec.ts b/src/microservices/test/server/server.spec.ts index b617e50bd20..d5993b4beea 100644 --- a/src/microservices/test/server/server.spec.ts +++ b/src/microservices/test/server/server.spec.ts @@ -5,77 +5,87 @@ import { Observable } from 'rxjs/Observable'; import 'rxjs/add/operator/toPromise'; class TestServer extends Server { - public listen(callback: () => void) {} - public close() {} + public listen(callback: () => void) {} + public close() {} } describe('Server', () => { - const server = new TestServer(); - const callback = () => {}, - pattern = { test: 'test' }; + const server = new TestServer(); + const callback = () => {}, + pattern = { test: 'test' }; - describe('add', () => { - it(`should add handler as a stringified pattern key`, () => { - server.add(pattern, callback as any); + describe('add', () => { + it(`should add handler as a stringified pattern key`, () => { + server.add(pattern, callback as any); - const handlers = server.getHandlers(); - expect(handlers[JSON.stringify(pattern)]).to.equal(callback); - }); + const handlers = server.getHandlers(); + expect(handlers[JSON.stringify(pattern)]).to.equal(callback); + }); + }); + describe('send', () => { + let stream$: Observable; + let sendSpy: sinon.SinonSpy; + beforeEach(() => { + stream$ = Observable.of('test'); }); - describe('send', () => { - let stream$: Observable; - let sendSpy: sinon.SinonSpy; + describe('when stream', () => { + beforeEach(() => { + sendSpy = sinon.spy(); + }); + describe('throws exception', () => { beforeEach(() => { - stream$ = Observable.of('test'); + server.send(Observable.throw('test'), sendSpy); + }); + it('should send error', () => { + expect(sendSpy.calledWith({ err: 'test', response: null })).to.be + .true; }); - describe('when stream', () => { - beforeEach(() => { - sendSpy = sinon.spy(); - }); - describe('throws exception', () => { - beforeEach(() => { - server.send(Observable.throw('test'), sendSpy); - }); - it('should send error', () => { - expect(sendSpy.calledWith({ err: 'test', response: null })).to.be.true; - }); - it('should send "complete" event', () => { - expect(sendSpy.calledWith({ disposed: true })).to.be.true; - }); - }); - describe('emits response', () => { - beforeEach(() => { - server.send(stream$, sendSpy); - }); - it('should send response', () => { - expect(sendSpy.calledWith({ err: null, response: 'test' })).to.be.true; - }); - it('should send "complete" event', () => { - expect(sendSpy.calledWith({ disposed: true })).to.be.true; - }); - }); + it('should send "complete" event', () => { + expect(sendSpy.calledWith({ disposed: true })).to.be.true; + }); + }); + describe('emits response', () => { + beforeEach(() => { + server.send(stream$, sendSpy); }); + it('should send response', () => { + expect(sendSpy.calledWith({ err: null, response: 'test' })).to.be + .true; + }); + it('should send "complete" event', () => { + expect(sendSpy.calledWith({ disposed: true })).to.be.true; + }); + }); }); - describe('transformToObservable', () => { - describe('when resultOrDeffered', () => { - describe('is Promise', () => { - it('should returns Observable', async () => { - const value = 100; - expect(await server.transformToObservable(Promise.resolve(value)).toPromise()).to.be.eq(100); - }); - }); - describe('is Observable', () => { - it('should returns Observable', async () => { - const value = 100; - expect(await server.transformToObservable(Observable.of(value)).toPromise()).to.be.eq(100); - }); - }); - describe('is value', () => { - it('should returns Observable', async () => { - const value = 100; - expect(await server.transformToObservable(value).toPromise()).to.be.eq(100); - }); - }); + }); + describe('transformToObservable', () => { + describe('when resultOrDeffered', () => { + describe('is Promise', () => { + it('should returns Observable', async () => { + const value = 100; + expect( + await server + .transformToObservable(Promise.resolve(value)) + .toPromise() + ).to.be.eq(100); + }); + }); + describe('is Observable', () => { + it('should returns Observable', async () => { + const value = 100; + expect( + await server.transformToObservable(Observable.of(value)).toPromise() + ).to.be.eq(100); + }); + }); + describe('is value', () => { + it('should returns Observable', async () => { + const value = 100; + expect( + await server.transformToObservable(value).toPromise() + ).to.be.eq(100); }); + }); }); -}); \ No newline at end of file + }); +}); diff --git a/src/microservices/test/utils/client.decorator.spec.ts b/src/microservices/test/utils/client.decorator.spec.ts index bc09c2e1efa..311a5ac420f 100644 --- a/src/microservices/test/utils/client.decorator.spec.ts +++ b/src/microservices/test/utils/client.decorator.spec.ts @@ -1,20 +1,31 @@ import 'reflect-metadata'; import 'mocha'; import { expect } from 'chai'; -import { CLIENT_METADATA, CLIENT_CONFIGURATION_METADATA } from '../../constants'; +import { + CLIENT_METADATA, + CLIENT_CONFIGURATION_METADATA +} from '../../constants'; import { Client } from './../../utils/client.decorator'; describe('@Client', () => { - const pattern = { role: 'test' }; - class TestComponent { - @Client(pattern as any) - public static instance; - } - it(`should enhance property with metadata`, () => { - const isClient = Reflect.getOwnMetadata(CLIENT_METADATA, TestComponent, 'instance'); - const config = Reflect.getOwnMetadata(CLIENT_CONFIGURATION_METADATA, TestComponent, 'instance'); + const pattern = { role: 'test' }; + class TestComponent { + @Client(pattern as any) + public static instance; + } + it(`should enhance property with metadata`, () => { + const isClient = Reflect.getOwnMetadata( + CLIENT_METADATA, + TestComponent, + 'instance' + ); + const config = Reflect.getOwnMetadata( + CLIENT_CONFIGURATION_METADATA, + TestComponent, + 'instance' + ); - expect(isClient).to.be.true; - expect(config).to.be.eql(pattern); - }); -}); \ No newline at end of file + expect(isClient).to.be.true; + expect(config).to.be.eql(pattern); + }); +}); diff --git a/src/microservices/test/utils/pattern.decorator.spec.ts b/src/microservices/test/utils/pattern.decorator.spec.ts index acdc6ada7c8..dc9757b1de1 100644 --- a/src/microservices/test/utils/pattern.decorator.spec.ts +++ b/src/microservices/test/utils/pattern.decorator.spec.ts @@ -4,13 +4,13 @@ import { PATTERN_METADATA } from '../../constants'; import { MessagePattern } from '../../utils/pattern.decorator'; describe('@MessagePattern', () => { - const pattern = { role: 'test' }; - class TestComponent { - @MessagePattern(pattern) - public static test() {} - } - it(`should enhance method with ${PATTERN_METADATA} metadata`, () => { - const metadata = Reflect.getMetadata(PATTERN_METADATA, TestComponent.test); - expect(metadata).to.be.eql(pattern); - }); -}); \ No newline at end of file + const pattern = { role: 'test' }; + class TestComponent { + @MessagePattern(pattern) + public static test() {} + } + it(`should enhance method with ${PATTERN_METADATA} metadata`, () => { + const metadata = Reflect.getMetadata(PATTERN_METADATA, TestComponent.test); + expect(metadata).to.be.eql(pattern); + }); +}); diff --git a/src/microservices/utils/client.decorator.ts b/src/microservices/utils/client.decorator.ts index bafc741939d..03b2f202b1f 100644 --- a/src/microservices/utils/client.decorator.ts +++ b/src/microservices/utils/client.decorator.ts @@ -13,9 +13,14 @@ import { ClientMetadata } from '../interfaces/client-metadata.interface'; * host?: string; */ export const Client = (metadata?: ClientMetadata) => { - return (target: object, propertyKey: string | symbol): void => { - Reflect.set(target, propertyKey, null); - Reflect.defineMetadata(CLIENT_METADATA, true, target, propertyKey); - Reflect.defineMetadata(CLIENT_CONFIGURATION_METADATA, metadata, target, propertyKey); - }; -}; \ No newline at end of file + return (target: object, propertyKey: string | symbol): void => { + Reflect.set(target, propertyKey, null); + Reflect.defineMetadata(CLIENT_METADATA, true, target, propertyKey); + Reflect.defineMetadata( + CLIENT_CONFIGURATION_METADATA, + metadata, + target, + propertyKey + ); + }; +}; diff --git a/src/microservices/utils/index.ts b/src/microservices/utils/index.ts index 41a61e48432..e357597db85 100644 --- a/src/microservices/utils/index.ts +++ b/src/microservices/utils/index.ts @@ -1,2 +1,2 @@ export * from './client.decorator'; -export * from './pattern.decorator'; \ No newline at end of file +export * from './pattern.decorator'; diff --git a/src/microservices/utils/pattern.decorator.ts b/src/microservices/utils/pattern.decorator.ts index 3a940f80e2a..e306e24af98 100644 --- a/src/microservices/utils/pattern.decorator.ts +++ b/src/microservices/utils/pattern.decorator.ts @@ -5,10 +5,12 @@ import { PatternMetadata } from '../interfaces/pattern-metadata.interface'; /** * Subscribes to the messages, which fulfils chosen pattern. */ -export const MessagePattern = (metadata?: PatternMetadata | string): MethodDecorator => { - return (target, key, descriptor: PropertyDescriptor) => { - Reflect.defineMetadata(PATTERN_METADATA, metadata, descriptor.value); - Reflect.defineMetadata(PATTERN_HANDLER_METADATA, true, descriptor.value); - return descriptor; - }; -}; \ No newline at end of file +export const MessagePattern = ( + metadata?: PatternMetadata | string +): MethodDecorator => { + return (target, key, descriptor: PropertyDescriptor) => { + Reflect.defineMetadata(PATTERN_METADATA, metadata, descriptor.value); + Reflect.defineMetadata(PATTERN_HANDLER_METADATA, true, descriptor.value); + return descriptor; + }; +}; diff --git a/src/testing/index.ts b/src/testing/index.ts index ad0c9d0d622..f781172fd8b 100644 --- a/src/testing/index.ts +++ b/src/testing/index.ts @@ -6,4 +6,4 @@ */ export * from './interfaces'; -export * from './test'; \ No newline at end of file +export * from './test'; diff --git a/src/testing/interfaces/index.ts b/src/testing/interfaces/index.ts index 7ed02963de4..33f61d966c8 100644 --- a/src/testing/interfaces/index.ts +++ b/src/testing/interfaces/index.ts @@ -1,2 +1,2 @@ export * from './override-by-factory-options.interface'; -export * from './override-by.interface'; \ No newline at end of file +export * from './override-by.interface'; diff --git a/src/testing/interfaces/override-by-factory-options.interface.ts b/src/testing/interfaces/override-by-factory-options.interface.ts index f4557c28fb3..6de3261193c 100644 --- a/src/testing/interfaces/override-by-factory-options.interface.ts +++ b/src/testing/interfaces/override-by-factory-options.interface.ts @@ -1,4 +1,4 @@ export interface OverrideByFactoryOptions { - factory: (...args) => any; - inject?: any[]; -} \ No newline at end of file + factory: (...args) => any; + inject?: any[]; +} diff --git a/src/testing/interfaces/override-by.interface.ts b/src/testing/interfaces/override-by.interface.ts index a52a1a00251..f1c949ef750 100644 --- a/src/testing/interfaces/override-by.interface.ts +++ b/src/testing/interfaces/override-by.interface.ts @@ -2,7 +2,7 @@ import { OverrideByFactoryOptions } from './override-by-factory-options.interfac import { TestingModuleBuilder } from '../testing-module.builder'; export interface OverrideBy { - useValue: (value) => TestingModuleBuilder; - useFactory: (options: OverrideByFactoryOptions) => TestingModuleBuilder; - useClass: (metatype) => TestingModuleBuilder; -} \ No newline at end of file + useValue: (value) => TestingModuleBuilder; + useFactory: (options: OverrideByFactoryOptions) => TestingModuleBuilder; + useClass: (metatype) => TestingModuleBuilder; +} diff --git a/src/testing/test.ts b/src/testing/test.ts index 10eb9dd5a24..76f704a1a36 100644 --- a/src/testing/test.ts +++ b/src/testing/test.ts @@ -1,4 +1,7 @@ -import { NestContainer, InstanceWrapper } from '@nestjs/core/injector/container'; +import { + NestContainer, + InstanceWrapper +} from '@nestjs/core/injector/container'; import { ModuleMetadata } from '@nestjs/common/interfaces/modules/module-metadata.interface'; import { Module } from '@nestjs/common/utils/decorators/module.decorator'; import { DependenciesScanner } from '@nestjs/core/scanner'; @@ -10,15 +13,14 @@ import { MetadataScanner } from '@nestjs/core/metadata-scanner'; import { TestingModuleBuilder } from './testing-module.builder'; export class Test { - private static metadataScanner = new MetadataScanner(); + private static metadataScanner = new MetadataScanner(); - public static createTestingModule(metadata: ModuleMetadata) { - this.init(); - return new TestingModuleBuilder(this.metadataScanner, metadata); - } + public static createTestingModule(metadata: ModuleMetadata) { + this.init(); + return new TestingModuleBuilder(this.metadataScanner, metadata); + } - private static init() { - Logger.setMode(NestEnvironment.TEST); - } + private static init() { + Logger.setMode(NestEnvironment.TEST); + } } - diff --git a/src/testing/testing-module.builder.ts b/src/testing/testing-module.builder.ts index 979addbf595..6705da0bd61 100644 --- a/src/testing/testing-module.builder.ts +++ b/src/testing/testing-module.builder.ts @@ -8,69 +8,66 @@ import { ModuleMetadata } from '@nestjs/common/interfaces'; import { TestingModule } from './testing-module'; export class TestingModuleBuilder { - private readonly container = new NestContainer(); - private readonly overloadsMap = new Map(); - private readonly scanner: DependenciesScanner; - private readonly instanceLoader = new InstanceLoader(this.container); - private readonly module: any; + private readonly container = new NestContainer(); + private readonly overloadsMap = new Map(); + private readonly scanner: DependenciesScanner; + private readonly instanceLoader = new InstanceLoader(this.container); + private readonly module: any; - constructor( - metadataScanner: MetadataScanner, - metadata: ModuleMetadata) { + constructor(metadataScanner: MetadataScanner, metadata: ModuleMetadata) { + this.scanner = new DependenciesScanner(this.container, metadataScanner); + this.module = this.createModule(metadata); + this.scanner.scan(this.module); + } - this.scanner = new DependenciesScanner( - this.container, - metadataScanner, - ); - this.module = this.createModule(metadata); - this.scanner.scan(this.module); - } + public overrideGuard(typeOrToken): OverrideBy { + return this.override(typeOrToken, false); + } - public overrideGuard(typeOrToken): OverrideBy { - return this.override(typeOrToken, false); - } + public overrideInterceptor(typeOrToken): OverrideBy { + return this.override(typeOrToken, false); + } - public overrideInterceptor(typeOrToken): OverrideBy { - return this.override(typeOrToken, false); - } + public overrideComponent(typeOrToken): OverrideBy { + return this.override(typeOrToken, true); + } - public overrideComponent(typeOrToken): OverrideBy { - return this.override(typeOrToken, true); - } + public async compile(): Promise { + [...this.overloadsMap.entries()].map(([component, options]) => { + this.container.replace(component, options); + }); + await this.instanceLoader.createInstancesOfDependencies(); - public async compile(): Promise { - [...this.overloadsMap.entries()].map(([component, options]) => { - this.container.replace(component, options); - }); - await this.instanceLoader.createInstancesOfDependencies(); + const modules = this.container.getModules().values(); + const root = modules.next().value; + return new TestingModule(this.container, [], root); + } - const modules = this.container.getModules().values(); - const root = modules.next().value; - return new TestingModule(this.container, [], root); - } + private override(typeOrToken, isComponent: boolean): OverrideBy { + const addOverload = options => { + this.overloadsMap.set(typeOrToken, { + ...options, + isComponent + }); + return this; + }; + return this.createOverrideByBuilder(addOverload); + } - private override(typeOrToken, isComponent: boolean): OverrideBy { - const addOverload = (options) => { - this.overloadsMap.set(typeOrToken, { - ...options, - isComponent, - }); - return this; - }; - return this.createOverrideByBuilder(addOverload); - } + private createOverrideByBuilder( + add: (provider) => TestingModuleBuilder + ): OverrideBy { + return { + useValue: value => add({ useValue: value }), + useFactory: (options: OverrideByFactoryOptions) => + add({ ...options, useFactory: options.factory }), + useClass: metatype => add({ useClass: metatype }) + }; + } - private createOverrideByBuilder(add: (provider) => TestingModuleBuilder): OverrideBy { - return { - useValue: (value) => add({ useValue: value }), - useFactory: (options: OverrideByFactoryOptions) => add({ ...options, useFactory: options.factory }), - useClass: (metatype) => add({ useClass: metatype }), - }; - } - - private createModule(metadata) { - class TestModule {} - Module(metadata)(TestModule); - return TestModule; - } -} \ No newline at end of file + private createModule(metadata) { + class TestModule {} + Module(metadata)(TestModule); + return TestModule; + } +} diff --git a/src/testing/testing-module.ts b/src/testing/testing-module.ts index c64702668d5..7083a5e5545 100644 --- a/src/testing/testing-module.ts +++ b/src/testing/testing-module.ts @@ -6,21 +6,28 @@ import { INestApplication, INestMicroservice } from '@nestjs/common'; import { MicroserviceConfiguration } from '@nestjs/common/interfaces/microservices/microservice-configuration.interface'; import { MicroservicesPackageNotFoundException } from '@nestjs/core/errors/exceptions/microservices-package-not-found.exception'; -const { NestMicroservice } = optional('@nestjs/microservices/nest-microservice') || {} as any; +const { NestMicroservice } = + optional('@nestjs/microservices/nest-microservice') || ({} as any); export class TestingModule extends NestApplicationContext { - constructor(container: NestContainer, scope: NestModuleMetatype[], contextModule) { - super(container, scope, contextModule); - } + constructor( + container: NestContainer, + scope: NestModuleMetatype[], + contextModule + ) { + super(container, scope, contextModule); + } - public createNestApplication(express?): INestApplication { - return new NestApplication(this.container, express); - } + public createNestApplication(express?): INestApplication { + return new NestApplication(this.container, express); + } - public createNestMicroservice(config: MicroserviceConfiguration): INestMicroservice { - if (!NestMicroservice) { - throw new MicroservicesPackageNotFoundException(); - } - return new NestMicroservice(this.container, config); + public createNestMicroservice( + config: MicroserviceConfiguration + ): INestMicroservice { + if (!NestMicroservice) { + throw new MicroservicesPackageNotFoundException(); } -} \ No newline at end of file + return new NestMicroservice(this.container, config); + } +} diff --git a/src/websockets/adapters/io-adapter.ts b/src/websockets/adapters/io-adapter.ts index 7ac201efdba..3358b7a0910 100644 --- a/src/websockets/adapters/io-adapter.ts +++ b/src/websockets/adapters/io-adapter.ts @@ -10,46 +10,47 @@ import 'rxjs/add/operator/filter'; import 'rxjs/add/operator/do'; export class IoAdapter implements WebSocketAdapter { - constructor(private readonly httpServer: Server | null = null) {} + constructor(private readonly httpServer: Server | null = null) {} - public create(port: number) { - return this.createIOServer(port); - } - - public createWithNamespace(port: number, namespace: string, server?) { - return server - ? server.of(namespace) - : this.createIOServer(port).of(namespace); - } - - public createIOServer(port: number) { - if (this.httpServer && port === 0) { - return io.listen(this.httpServer); - } - return io(port); - } + public create(port: number) { + return this.createIOServer(port); + } - public bindClientConnect(server, callback: (...args) => void) { - server.on(CONNECTION_EVENT, callback); - } - - public bindClientDisconnect(client, callback: (...args) => void) { - client.on(DISCONNECT_EVENT, callback); - } - - public bindMessageHandlers( - client, - handlers: MessageMappingProperties[], - process: (data: any) => Observable, - ) { - handlers.forEach(({ message, callback }) => Observable.fromEvent(client, message) - .switchMap((data) => process(callback(data))) - .filter((result) => !!result && result.event) - .subscribe(({ event, data }) => client.emit(event, data)), - ); - } + public createWithNamespace(port: number, namespace: string, server?) { + return server + ? server.of(namespace) + : this.createIOServer(port).of(namespace); + } - public bindMiddleware(server, middleware: (socket, next) => void) { - server.use(middleware); + public createIOServer(port: number) { + if (this.httpServer && port === 0) { + return io.listen(this.httpServer); } -} \ No newline at end of file + return io(port); + } + + public bindClientConnect(server, callback: (...args) => void) { + server.on(CONNECTION_EVENT, callback); + } + + public bindClientDisconnect(client, callback: (...args) => void) { + client.on(DISCONNECT_EVENT, callback); + } + + public bindMessageHandlers( + client, + handlers: MessageMappingProperties[], + process: (data: any) => Observable + ) { + handlers.forEach(({ message, callback }) => + Observable.fromEvent(client, message) + .switchMap(data => process(callback(data))) + .filter(result => !!result && result.event) + .subscribe(({ event, data }) => client.emit(event, data)) + ); + } + + public bindMiddleware(server, middleware: (socket, next) => void) { + server.use(middleware); + } +} diff --git a/src/websockets/constants.ts b/src/websockets/constants.ts index 258ebeaf390..d1cd0598b66 100644 --- a/src/websockets/constants.ts +++ b/src/websockets/constants.ts @@ -7,4 +7,4 @@ export const PORT_METADATA = 'port'; export const GATEWAY_MIDDLEWARES = '__gatewayMiddlewares'; export const CONNECTION_EVENT = 'connection'; -export const DISCONNECT_EVENT = 'disconnect'; \ No newline at end of file +export const DISCONNECT_EVENT = 'disconnect'; diff --git a/src/websockets/container.ts b/src/websockets/container.ts index 8f160cdea2a..b8c46868be3 100644 --- a/src/websockets/container.ts +++ b/src/websockets/container.ts @@ -1,26 +1,31 @@ import { WebSocketServerData, ObservableSocketServer } from './interfaces'; export class SocketsContainer { - private readonly observableServers = new Map(); + private readonly observableServers = new Map< + string, + ObservableSocketServer + >(); - public getAllServers(): Map { - return this.observableServers; - } + public getAllServers(): Map { + return this.observableServers; + } - public getServerByPort(port: number): ObservableSocketServer { - return this.observableServers.get(`${port}`); - } + public getServerByPort(port: number): ObservableSocketServer { + return this.observableServers.get(`${port}`); + } - public addServer(namespace: string, port: number, server: ObservableSocketServer) { - this.observableServers.set( - namespace - ? `${namespace}:${port}` - : `${port}`, - server, - ); - } + public addServer( + namespace: string, + port: number, + server: ObservableSocketServer + ) { + this.observableServers.set( + namespace ? `${namespace}:${port}` : `${port}`, + server + ); + } - public clear() { - this.observableServers.clear(); - } + public clear() { + this.observableServers.clear(); + } } diff --git a/src/websockets/context/exception-filters-context.ts b/src/websockets/context/exception-filters-context.ts index 9d2f05ca8ad..f0ab326dbde 100644 --- a/src/websockets/context/exception-filters-context.ts +++ b/src/websockets/context/exception-filters-context.ts @@ -2,25 +2,39 @@ import 'reflect-metadata'; import iterate from 'iterare'; import { Controller } from '@nestjs/common/interfaces/controllers/controller.interface'; import { Observable } from 'rxjs/Observable'; -import { EXCEPTION_FILTERS_METADATA, FILTER_CATCH_EXCEPTIONS } from '@nestjs/common/constants'; -import { isEmpty, isUndefined, isFunction } from '@nestjs/common/utils/shared.utils'; +import { + EXCEPTION_FILTERS_METADATA, + FILTER_CATCH_EXCEPTIONS +} from '@nestjs/common/constants'; +import { + isEmpty, + isUndefined, + isFunction +} from '@nestjs/common/utils/shared.utils'; import { RpcExceptionFilter } from '@nestjs/common/interfaces/exceptions'; import { Metatype } from '@nestjs/common/interfaces'; import { BaseExceptionFilterContext } from '@nestjs/core/exceptions/base-exception-filter-context'; import { WsExceptionsHandler } from '../exceptions/ws-exceptions-handler'; export class ExceptionFiltersContext extends BaseExceptionFilterContext { - public create(instance: Controller, callback: (client, data) => any): WsExceptionsHandler { - const exceptionHandler = new WsExceptionsHandler(); - const filters = this.createContext(instance, callback, EXCEPTION_FILTERS_METADATA); - if (isEmpty(filters)) { - return exceptionHandler; - } - exceptionHandler.setCustomFilters(filters); - return exceptionHandler; + public create( + instance: Controller, + callback: (client, data) => any + ): WsExceptionsHandler { + const exceptionHandler = new WsExceptionsHandler(); + const filters = this.createContext( + instance, + callback, + EXCEPTION_FILTERS_METADATA + ); + if (isEmpty(filters)) { + return exceptionHandler; } + exceptionHandler.setCustomFilters(filters); + return exceptionHandler; + } - public getGlobalMetadata(): T { - return [] as T; - } -} \ No newline at end of file + public getGlobalMetadata(): T { + return [] as T; + } +} diff --git a/src/websockets/context/ws-context-creator.ts b/src/websockets/context/ws-context-creator.ts index b39c1b07bae..008a29c8e5f 100644 --- a/src/websockets/context/ws-context-creator.ts +++ b/src/websockets/context/ws-context-creator.ts @@ -14,47 +14,71 @@ import { InterceptorsConsumer } from '@nestjs/core/interceptors/interceptors-con import { InterceptorsContextCreator } from '@nestjs/core/interceptors/interceptors-context-creator'; export class WsContextCreator { - constructor( - private readonly wsProxy: WsProxy, - private readonly exceptionFiltersContext: ExceptionFiltersContext, - private readonly pipesCreator: PipesContextCreator, - private readonly pipesConsumer: PipesConsumer, - private readonly guardsContextCreator: GuardsContextCreator, - private readonly guardsConsumer: GuardsConsumer, - private readonly interceptorsContextCreator: InterceptorsContextCreator, - private readonly interceptorsConsumer: InterceptorsConsumer) {} + constructor( + private readonly wsProxy: WsProxy, + private readonly exceptionFiltersContext: ExceptionFiltersContext, + private readonly pipesCreator: PipesContextCreator, + private readonly pipesConsumer: PipesConsumer, + private readonly guardsContextCreator: GuardsContextCreator, + private readonly guardsConsumer: GuardsConsumer, + private readonly interceptorsContextCreator: InterceptorsContextCreator, + private readonly interceptorsConsumer: InterceptorsConsumer + ) {} - public create( - instance: Controller, - callback: (client, data) => void, - module): (client, data) => Promise { + public create( + instance: Controller, + callback: (client, data) => void, + module + ): (client, data) => Promise { + const exceptionHandler = this.exceptionFiltersContext.create( + instance, + callback + ); + const pipes = this.pipesCreator.create(instance, callback); + const guards = this.guardsContextCreator.create(instance, callback, module); + const metatype = this.getDataMetatype(instance, callback); + const interceptors = this.interceptorsContextCreator.create( + instance, + callback, + module + ); - const exceptionHandler = this.exceptionFiltersContext.create(instance, callback); - const pipes = this.pipesCreator.create(instance, callback); - const guards = this.guardsContextCreator.create(instance, callback, module); - const metatype = this.getDataMetatype(instance, callback); - const interceptors = this.interceptorsContextCreator.create(instance, callback, module); + return this.wsProxy.create(async (client, data) => { + const canActivate = await this.guardsConsumer.tryActivate( + guards, + data, + instance, + callback + ); + if (!canActivate) { + throw new WsException(FORBIDDEN_MESSAGE); + } + const result = await this.pipesConsumer.applyPipes( + data, + { metatype }, + pipes + ); + const handler = () => callback.call(instance, client, data); - return this.wsProxy.create(async (client, data) => { - const canActivate = await this.guardsConsumer.tryActivate(guards, data, instance, callback); - if (!canActivate) { - throw new WsException(FORBIDDEN_MESSAGE); - } - const result = await this.pipesConsumer.applyPipes(data, { metatype }, pipes); - const handler = () => callback.call(instance, client, data); + return await this.interceptorsConsumer.intercept( + interceptors, + result, + instance, + callback, + handler + ); + }, exceptionHandler); + } - return await this.interceptorsConsumer.intercept( - interceptors, result, instance, callback, handler, - ); - }, exceptionHandler); - } + public reflectCallbackParamtypes( + instance: Controller, + callback: (...args) => any + ): any[] { + return Reflect.getMetadata(PARAMTYPES_METADATA, instance, callback.name); + } - public reflectCallbackParamtypes(instance: Controller, callback: (...args) => any): any[] { - return Reflect.getMetadata(PARAMTYPES_METADATA, instance, callback.name); - } - - public getDataMetatype(instance, callback) { - const paramtypes = this.reflectCallbackParamtypes(instance, callback); - return paramtypes && paramtypes.length ? paramtypes[1] : null; - } -} \ No newline at end of file + public getDataMetatype(instance, callback) { + const paramtypes = this.reflectCallbackParamtypes(instance, callback); + return paramtypes && paramtypes.length ? paramtypes[1] : null; + } +} diff --git a/src/websockets/context/ws-proxy.ts b/src/websockets/context/ws-proxy.ts index 9935aa3172f..5990d9526ed 100644 --- a/src/websockets/context/ws-proxy.ts +++ b/src/websockets/context/ws-proxy.ts @@ -1,17 +1,16 @@ import { WsExceptionsHandler } from './../exceptions/ws-exceptions-handler'; export class WsProxy { - public create( - targetCallback: (client, data) => Promise, - exceptionsHandler: WsExceptionsHandler): (client, data) => Promise { - - return async (client, data) => { - try { - return await targetCallback(client, data); - } - catch (e) { - exceptionsHandler.handle(e, client); - } - }; - } + public create( + targetCallback: (client, data) => Promise, + exceptionsHandler: WsExceptionsHandler + ): (client, data) => Promise { + return async (client, data) => { + try { + return await targetCallback(client, data); + } catch (e) { + exceptionsHandler.handle(e, client); + } + }; + } } diff --git a/src/websockets/exceptions/invalid-socket-port.exception.ts b/src/websockets/exceptions/invalid-socket-port.exception.ts index 89f223acfe7..31201263a24 100644 --- a/src/websockets/exceptions/invalid-socket-port.exception.ts +++ b/src/websockets/exceptions/invalid-socket-port.exception.ts @@ -1,7 +1,7 @@ import { RuntimeException } from '@nestjs/core/errors/exceptions/runtime.exception'; export class InvalidSocketPortException extends RuntimeException { - constructor(port, type) { - super(`Invalid port (${port}) in Gateway ${type}!`); - } -} \ No newline at end of file + constructor(port, type) { + super(`Invalid port (${port}) in Gateway ${type}!`); + } +} diff --git a/src/websockets/exceptions/ws-exception.ts b/src/websockets/exceptions/ws-exception.ts index 80afa23eb45..f37b0909a07 100644 --- a/src/websockets/exceptions/ws-exception.ts +++ b/src/websockets/exceptions/ws-exception.ts @@ -1,7 +1,7 @@ export class WsException { - constructor(private readonly error: string | object) {} + constructor(private readonly error: string | object) {} - public getError(): string | object { - return this.error; - } + public getError(): string | object { + return this.error; + } } diff --git a/src/websockets/exceptions/ws-exceptions-handler.ts b/src/websockets/exceptions/ws-exceptions-handler.ts index 509db4389c1..279ffc09cdc 100644 --- a/src/websockets/exceptions/ws-exceptions-handler.ts +++ b/src/websockets/exceptions/ws-exceptions-handler.ts @@ -6,41 +6,43 @@ import { InvalidExceptionFilterException } from '@nestjs/core/errors/exceptions/ import { WsException } from '../exceptions/ws-exception'; export class WsExceptionsHandler { - private filters: ExceptionFilterMetadata[] = []; + private filters: ExceptionFilterMetadata[] = []; - public handle(exception: Error | WsException | any, client) { - if (this.invokeCustomFilters(exception, client) || !client.emit) return; + public handle(exception: Error | WsException | any, client) { + if (this.invokeCustomFilters(exception, client) || !client.emit) return; - const status = 'error'; - if (!(exception instanceof WsException)) { - const message = messages.UNKNOWN_EXCEPTION_MESSAGE; - return client.emit('exception', { status, message }); - } - const result = exception.getError(); - const message = isObject(result) ? result : ({ - status, - message: result, - }); - client.emit('exception', message); + const status = 'error'; + if (!(exception instanceof WsException)) { + const message = messages.UNKNOWN_EXCEPTION_MESSAGE; + return client.emit('exception', { status, message }); } + const result = exception.getError(); + const message = isObject(result) + ? result + : { + status, + message: result + }; + client.emit('exception', message); + } - public setCustomFilters(filters: ExceptionFilterMetadata[]) { - if (!Array.isArray(filters)) { - throw new InvalidExceptionFilterException(); - } - this.filters = filters; + public setCustomFilters(filters: ExceptionFilterMetadata[]) { + if (!Array.isArray(filters)) { + throw new InvalidExceptionFilterException(); } + this.filters = filters; + } - public invokeCustomFilters(exception, client): boolean { - if (isEmpty(this.filters)) return false; + public invokeCustomFilters(exception, client): boolean { + if (isEmpty(this.filters)) return false; - const filter = this.filters.find(({ exceptionMetatypes, func }) => { - const hasMetatype = !!exceptionMetatypes.find( - ExceptionMetatype => exception instanceof ExceptionMetatype, - ); - return hasMetatype; - }); - filter && filter.func(exception, client); - return !!filter; - } + const filter = this.filters.find(({ exceptionMetatypes, func }) => { + const hasMetatype = !!exceptionMetatypes.find( + ExceptionMetatype => exception instanceof ExceptionMetatype + ); + return hasMetatype; + }); + filter && filter.func(exception, client); + return !!filter; + } } diff --git a/src/websockets/gateway-metadata-explorer.ts b/src/websockets/gateway-metadata-explorer.ts index 19110859b98..eb997c071b2 100644 --- a/src/websockets/gateway-metadata-explorer.ts +++ b/src/websockets/gateway-metadata-explorer.ts @@ -1,50 +1,64 @@ import { NestGateway } from './interfaces/nest-gateway.interface'; import { isUndefined, isFunction } from '@nestjs/common/utils/shared.utils'; -import { MESSAGE_MAPPING_METADATA, MESSAGE_METADATA, GATEWAY_SERVER_METADATA } from './constants'; +import { + MESSAGE_MAPPING_METADATA, + MESSAGE_METADATA, + GATEWAY_SERVER_METADATA +} from './constants'; import { MetadataScanner } from '@nestjs/core/metadata-scanner'; import { Observable } from 'rxjs/Observable'; export class GatewayMetadataExplorer { - constructor(private readonly metadataScanner: MetadataScanner) {} - - public explore(instance: NestGateway): MessageMappingProperties[] { - const instancePrototype = Object.getPrototypeOf(instance); - return this.metadataScanner.scanFromPrototype( - instance, - instancePrototype, - (method) => this.exploreMethodMetadata(instancePrototype, method), - ); - } + constructor(private readonly metadataScanner: MetadataScanner) {} + + public explore(instance: NestGateway): MessageMappingProperties[] { + const instancePrototype = Object.getPrototypeOf(instance); + return this.metadataScanner.scanFromPrototype< + NestGateway, + MessageMappingProperties + >(instance, instancePrototype, method => + this.exploreMethodMetadata(instancePrototype, method) + ); + } + + public exploreMethodMetadata( + instancePrototype, + methodName: string + ): MessageMappingProperties { + const callback = instancePrototype[methodName]; + const isMessageMapping = Reflect.getMetadata( + MESSAGE_MAPPING_METADATA, + callback + ); - public exploreMethodMetadata(instancePrototype, methodName: string): MessageMappingProperties { - const callback = instancePrototype[methodName]; - const isMessageMapping = Reflect.getMetadata(MESSAGE_MAPPING_METADATA, callback); - - if (isUndefined(isMessageMapping)) { - return null; - } - const message = Reflect.getMetadata(MESSAGE_METADATA, callback); - return { - callback, - message, - }; + if (isUndefined(isMessageMapping)) { + return null; } + const message = Reflect.getMetadata(MESSAGE_METADATA, callback); + return { + callback, + message + }; + } - public *scanForServerHooks(instance: NestGateway): IterableIterator { - for (const propertyKey in instance) { - if (isFunction(propertyKey)) continue; + public *scanForServerHooks(instance: NestGateway): IterableIterator { + for (const propertyKey in instance) { + if (isFunction(propertyKey)) continue; - const property = String(propertyKey); - const isServer = Reflect.getMetadata(GATEWAY_SERVER_METADATA, instance, property); - if (isUndefined(isServer)) continue; + const property = String(propertyKey); + const isServer = Reflect.getMetadata( + GATEWAY_SERVER_METADATA, + instance, + property + ); + if (isUndefined(isServer)) continue; - yield property; - } + yield property; } - + } } export interface MessageMappingProperties { - message: string; - callback: (...args) => Observable | Promise | void; -} \ No newline at end of file + message: string; + callback: (...args) => Observable | Promise | void; +} diff --git a/src/websockets/index.ts b/src/websockets/index.ts index 909bc1706e2..1fd82465a4c 100644 --- a/src/websockets/index.ts +++ b/src/websockets/index.ts @@ -9,4 +9,4 @@ export * from './adapters/io-adapter'; export * from './interfaces'; export * from './exceptions/ws-exception'; export * from './utils'; -export { MessageMappingProperties } from './gateway-metadata-explorer'; \ No newline at end of file +export { MessageMappingProperties } from './gateway-metadata-explorer'; diff --git a/src/websockets/interfaces/gateway-metadata.interface.ts b/src/websockets/interfaces/gateway-metadata.interface.ts index c28b18f9c1a..20eca7ac1cd 100644 --- a/src/websockets/interfaces/gateway-metadata.interface.ts +++ b/src/websockets/interfaces/gateway-metadata.interface.ts @@ -2,7 +2,7 @@ import { Metatype } from '@nestjs/common/interfaces/metatype.interface'; import { GatewayMiddleware } from './gateway-middleware.interface'; export interface GatewayMetadata { - port?: number; - namespace?: string; - middlewares?: Metatype[]; -} \ No newline at end of file + port?: number; + namespace?: string; + middlewares?: Metatype[]; +} diff --git a/src/websockets/interfaces/gateway-middleware.interface.ts b/src/websockets/interfaces/gateway-middleware.interface.ts index 31756e9eb01..7cf923417cf 100644 --- a/src/websockets/interfaces/gateway-middleware.interface.ts +++ b/src/websockets/interfaces/gateway-middleware.interface.ts @@ -1,3 +1,3 @@ export interface GatewayMiddleware { - resolve(): (socket, next) => void; -} \ No newline at end of file + resolve(): (socket, next) => void; +} diff --git a/src/websockets/interfaces/index.ts b/src/websockets/interfaces/index.ts index 22ae3db2a6f..93616cd3c5e 100644 --- a/src/websockets/interfaces/index.ts +++ b/src/websockets/interfaces/index.ts @@ -6,4 +6,4 @@ export * from './on-gateway-init.interface'; export * from './on-gateway-connection.interface'; export * from './on-gateway-disconnect.interface'; export * from './gateway-middleware.interface'; -export * from './ws-response.interface'; \ No newline at end of file +export * from './ws-response.interface'; diff --git a/src/websockets/interfaces/nest-gateway.interface.ts b/src/websockets/interfaces/nest-gateway.interface.ts index 51b96ee1671..07c40bb32d0 100644 --- a/src/websockets/interfaces/nest-gateway.interface.ts +++ b/src/websockets/interfaces/nest-gateway.interface.ts @@ -1,5 +1,5 @@ export interface NestGateway { - afterInit?: (server: any) => void; - handleConnection?: (client: any) => void; - handleDisconnect?: (client: any) => void; + afterInit?: (server: any) => void; + handleConnection?: (client: any) => void; + handleDisconnect?: (client: any) => void; } diff --git a/src/websockets/interfaces/observable-socket-server.interface.ts b/src/websockets/interfaces/observable-socket-server.interface.ts index d63d26db0b5..20ccca719b9 100644 --- a/src/websockets/interfaces/observable-socket-server.interface.ts +++ b/src/websockets/interfaces/observable-socket-server.interface.ts @@ -2,9 +2,8 @@ import { ReplaySubject } from 'rxjs/ReplaySubject'; import { Subject } from 'rxjs/Subject'; export interface ObservableSocketServer { - server: any; - init: ReplaySubject; - connection: Subject; - disconnect: Subject; + server: any; + init: ReplaySubject; + connection: Subject; + disconnect: Subject; } - diff --git a/src/websockets/interfaces/on-gateway-connection.interface.ts b/src/websockets/interfaces/on-gateway-connection.interface.ts index 1e61ffc8f3d..324f7f6b754 100644 --- a/src/websockets/interfaces/on-gateway-connection.interface.ts +++ b/src/websockets/interfaces/on-gateway-connection.interface.ts @@ -1,3 +1,3 @@ export interface OnGatewayConnection { - handleConnection(client: any); + handleConnection(client: any); } diff --git a/src/websockets/interfaces/on-gateway-disconnect.interface.ts b/src/websockets/interfaces/on-gateway-disconnect.interface.ts index 813094d7b92..2c2cc9320c1 100644 --- a/src/websockets/interfaces/on-gateway-disconnect.interface.ts +++ b/src/websockets/interfaces/on-gateway-disconnect.interface.ts @@ -1,3 +1,3 @@ export interface OnGatewayDisconnect { - handleDisconnect(client: any); + handleDisconnect(client: any); } diff --git a/src/websockets/interfaces/on-gateway-init.interface.ts b/src/websockets/interfaces/on-gateway-init.interface.ts index 10acd4b51c2..d0e5d9be6ab 100644 --- a/src/websockets/interfaces/on-gateway-init.interface.ts +++ b/src/websockets/interfaces/on-gateway-init.interface.ts @@ -1,3 +1,3 @@ export interface OnGatewayInit { - afterInit(server: any); + afterInit(server: any); } diff --git a/src/websockets/interfaces/web-socket-server.interface.ts b/src/websockets/interfaces/web-socket-server.interface.ts index cfaa6414cbb..eacd80be493 100644 --- a/src/websockets/interfaces/web-socket-server.interface.ts +++ b/src/websockets/interfaces/web-socket-server.interface.ts @@ -1,4 +1,4 @@ export interface WebSocketServerData { - port: number; - namespace: string; + port: number; + namespace: string; } diff --git a/src/websockets/interfaces/ws-response.interface.ts b/src/websockets/interfaces/ws-response.interface.ts index 325ae40242d..2df913fbd9b 100644 --- a/src/websockets/interfaces/ws-response.interface.ts +++ b/src/websockets/interfaces/ws-response.interface.ts @@ -1,4 +1,4 @@ export interface WsResponse { event: string; data: T; -} \ No newline at end of file +} diff --git a/src/websockets/middlewares-injector.ts b/src/websockets/middlewares-injector.ts index 42462fda482..57774b1777a 100644 --- a/src/websockets/middlewares-injector.ts +++ b/src/websockets/middlewares-injector.ts @@ -1,58 +1,78 @@ import 'reflect-metadata'; import iterate from 'iterare'; -import { NestContainer, InstanceWrapper } from '@nestjs/core/injector/container'; +import { + NestContainer, + InstanceWrapper +} from '@nestjs/core/injector/container'; import { NestGateway } from './index'; import { GATEWAY_MIDDLEWARES } from './constants'; import { UnknownModuleException } from '@nestjs/core/errors/exceptions/unknown-module.exception'; import { Injectable } from '@nestjs/common/interfaces/injectable.interface'; import { RuntimeException } from '@nestjs/core/errors/exceptions/runtime.exception'; import { GatewayMiddleware } from './interfaces/gateway-middleware.interface'; -import { isUndefined, isFunction, isNil } from '@nestjs/common/utils/shared.utils'; +import { + isUndefined, + isFunction, + isNil +} from '@nestjs/common/utils/shared.utils'; import { ApplicationConfig } from '@nestjs/core/application-config'; export class MiddlewaresInjector { - constructor( - private readonly container: NestContainer, - private readonly config: ApplicationConfig) {} + constructor( + private readonly container: NestContainer, + private readonly config: ApplicationConfig + ) {} - public inject(server, instance: NestGateway, module: string) { - const adapter = this.config.getIoAdapter(); - if (!adapter.bindMiddleware) { - return; - } - const opaqueTokens = this.reflectMiddlewaresTokens(instance); - const modules = this.container.getModules(); - if (!modules.has(module)) { - throw new UnknownModuleException(); - } - const { components } = modules.get(module); - this.applyMiddlewares(server, components, opaqueTokens); + public inject(server, instance: NestGateway, module: string) { + const adapter = this.config.getIoAdapter(); + if (!adapter.bindMiddleware) { + return; } - - public reflectMiddlewaresTokens(instance: NestGateway): any[] { - const prototype = Object.getPrototypeOf(instance); - return Reflect.getMetadata(GATEWAY_MIDDLEWARES, prototype.constructor) || []; + const opaqueTokens = this.reflectMiddlewaresTokens(instance); + const modules = this.container.getModules(); + if (!modules.has(module)) { + throw new UnknownModuleException(); } + const { components } = modules.get(module); + this.applyMiddlewares(server, components, opaqueTokens); + } - public applyMiddlewares(server, components: Map>, tokens: any[]) { - const adapter = this.config.getIoAdapter(); - iterate(tokens).map(token => this.bindMiddleware(token.name, components)) - .filter(middleware => !isNil(middleware)) - .forEach(middleware => adapter.bindMiddleware(server, middleware)); - } + public reflectMiddlewaresTokens(instance: NestGateway): any[] { + const prototype = Object.getPrototypeOf(instance); + return ( + Reflect.getMetadata(GATEWAY_MIDDLEWARES, prototype.constructor) || [] + ); + } - public bindMiddleware(token: string, components: Map>) { - if (!components.has(token)) { - throw new RuntimeException(); - } - const { instance } = components.get(token); - if (!this.isGatewayMiddleware(instance)) return null; + public applyMiddlewares( + server, + components: Map>, + tokens: any[] + ) { + const adapter = this.config.getIoAdapter(); + iterate(tokens) + .map(token => this.bindMiddleware(token.name, components)) + .filter(middleware => !isNil(middleware)) + .forEach(middleware => adapter.bindMiddleware(server, middleware)); + } - const middleware = instance.resolve(); - return isFunction(middleware) ? middleware.bind(instance) : null; + public bindMiddleware( + token: string, + components: Map> + ) { + if (!components.has(token)) { + throw new RuntimeException(); } + const { instance } = components.get(token); + if (!this.isGatewayMiddleware(instance)) return null; - public isGatewayMiddleware(middleware: object): middleware is GatewayMiddleware { - return !isUndefined((middleware as GatewayMiddleware).resolve); - } -} \ No newline at end of file + const middleware = instance.resolve(); + return isFunction(middleware) ? middleware.bind(instance) : null; + } + + public isGatewayMiddleware( + middleware: object + ): middleware is GatewayMiddleware { + return !isUndefined((middleware as GatewayMiddleware).resolve); + } +} diff --git a/src/websockets/observable-socket.ts b/src/websockets/observable-socket.ts index d97eecb7a46..d8f5136d867 100644 --- a/src/websockets/observable-socket.ts +++ b/src/websockets/observable-socket.ts @@ -3,12 +3,12 @@ import { ReplaySubject } from 'rxjs/ReplaySubject'; import { ObservableSocketServer } from './interfaces/observable-socket-server.interface'; export class ObservableSocket { - public static create(server): ObservableSocketServer { - return { - init: new ReplaySubject(), - connection: new Subject(), - disconnect: new Subject(), - server, - }; - } -} \ No newline at end of file + public static create(server): ObservableSocketServer { + return { + init: new ReplaySubject(), + connection: new Subject(), + disconnect: new Subject(), + server + }; + } +} diff --git a/src/websockets/socket-module.ts b/src/websockets/socket-module.ts index e7182f86af2..91a50dcd7fd 100644 --- a/src/websockets/socket-module.ts +++ b/src/websockets/socket-module.ts @@ -1,5 +1,8 @@ import 'reflect-metadata'; -import { NestContainer, InstanceWrapper } from '@nestjs/core/injector/container'; +import { + NestContainer, + InstanceWrapper +} from '@nestjs/core/injector/container'; import { NestGateway } from './interfaces/nest-gateway.interface'; import { SocketsContainer } from './container'; import { WebSocketsController } from './web-sockets-controller'; @@ -18,54 +21,66 @@ import { InterceptorsContextCreator } from '@nestjs/core/interceptors/intercepto import { InterceptorsConsumer } from '@nestjs/core/interceptors/interceptors-consumer'; export class SocketModule { - private socketsContainer = new SocketsContainer(); - private webSocketsController: WebSocketsController; + private socketsContainer = new SocketsContainer(); + private webSocketsController: WebSocketsController; - public setup(container, config) { - this.webSocketsController = new WebSocketsController( - new SocketServerProvider(this.socketsContainer, config), container, config, - this.getContextCreator(container), - ); - const modules = container.getModules(); - modules.forEach(({ components }, moduleName) => this.hookGatewaysIntoServers(components, moduleName)); - } + public setup(container, config) { + this.webSocketsController = new WebSocketsController( + new SocketServerProvider(this.socketsContainer, config), + container, + config, + this.getContextCreator(container) + ); + const modules = container.getModules(); + modules.forEach(({ components }, moduleName) => + this.hookGatewaysIntoServers(components, moduleName) + ); + } - public hookGatewaysIntoServers(components: Map>, moduleName: string) { - components.forEach((wrapper) => this.hookGatewayIntoServer(wrapper, moduleName)); - } + public hookGatewaysIntoServers( + components: Map>, + moduleName: string + ) { + components.forEach(wrapper => + this.hookGatewayIntoServer(wrapper, moduleName) + ); + } - public hookGatewayIntoServer(wrapper: InstanceWrapper, moduleName: string) { - const { instance, metatype, isNotMetatype } = wrapper; - if (isNotMetatype) { - return; - } - const metadataKeys = Reflect.getMetadataKeys(metatype); - if (metadataKeys.indexOf(GATEWAY_METADATA) < 0) { - return; - } - this.webSocketsController.hookGatewayIntoServer( - instance as NestGateway, - metatype, - moduleName, - ); + public hookGatewayIntoServer( + wrapper: InstanceWrapper, + moduleName: string + ) { + const { instance, metatype, isNotMetatype } = wrapper; + if (isNotMetatype) { + return; } - - public close() { - const servers = this.socketsContainer.getAllServers(); - servers.forEach(({ server }) => server.close()); - this.socketsContainer.clear(); + const metadataKeys = Reflect.getMetadataKeys(metatype); + if (metadataKeys.indexOf(GATEWAY_METADATA) < 0) { + return; } + this.webSocketsController.hookGatewayIntoServer( + instance as NestGateway, + metatype, + moduleName + ); + } - private getContextCreator(container): WsContextCreator { - return new WsContextCreator( - new WsProxy(), - new ExceptionFiltersContext(), - new PipesContextCreator(), - new PipesConsumer(), - new GuardsContextCreator(container), - new GuardsConsumer(), - new InterceptorsContextCreator(container), - new InterceptorsConsumer(), - ); - } -} \ No newline at end of file + public close() { + const servers = this.socketsContainer.getAllServers(); + servers.forEach(({ server }) => server.close()); + this.socketsContainer.clear(); + } + + private getContextCreator(container): WsContextCreator { + return new WsContextCreator( + new WsProxy(), + new ExceptionFiltersContext(), + new PipesContextCreator(), + new PipesConsumer(), + new GuardsContextCreator(container), + new GuardsConsumer(), + new InterceptorsContextCreator(container), + new InterceptorsConsumer() + ); + } +} diff --git a/src/websockets/socket-server-provider.ts b/src/websockets/socket-server-provider.ts index 269e72238c5..56ba63df1e3 100644 --- a/src/websockets/socket-server-provider.ts +++ b/src/websockets/socket-server-provider.ts @@ -5,44 +5,63 @@ import { validatePath } from '@nestjs/common/utils/shared.utils'; import { ApplicationConfig } from '@nestjs/core/application-config'; export class SocketServerProvider { - constructor( - private readonly socketsContainer: SocketsContainer, - private readonly applicationConfig: ApplicationConfig) {} - - public scanForSocketServer(namespace: string, port: number): ObservableSocketServer { - const observableServer = this.socketsContainer.getServerByPort(port); - return observableServer - ? this.createWithNamespace(namespace, port, observableServer) - : this.createSocketServer(namespace, port); - } + constructor( + private readonly socketsContainer: SocketsContainer, + private readonly applicationConfig: ApplicationConfig + ) {} - private createSocketServer(namespace: string, port: number): ObservableSocketServer { - const adapter = this.applicationConfig.getIoAdapter(); - const server = adapter.create(port); - const observableSocket = ObservableSocket.create(server); + public scanForSocketServer( + namespace: string, + port: number + ): ObservableSocketServer { + const observableServer = this.socketsContainer.getServerByPort(port); + return observableServer + ? this.createWithNamespace(namespace, port, observableServer) + : this.createSocketServer(namespace, port); + } - this.socketsContainer.addServer(null, port, observableSocket); - return this.createWithNamespace(namespace, port, observableSocket); - } + private createSocketServer( + namespace: string, + port: number + ): ObservableSocketServer { + const adapter = this.applicationConfig.getIoAdapter(); + const server = adapter.create(port); + const observableSocket = ObservableSocket.create(server); - private createWithNamespace(namespace: string, port: number, observableSocket: ObservableSocketServer): ObservableSocketServer { - const adapter = this.applicationConfig.getIoAdapter(); - if (!namespace || !adapter.createWithNamespace) { - return observableSocket; - } - const namespaceServer = this.getServerOfNamespace(namespace, port, observableSocket.server); - const observableNamespaceSocket = ObservableSocket.create(namespaceServer); - this.socketsContainer.addServer(namespace, port, observableNamespaceSocket); + this.socketsContainer.addServer(null, port, observableSocket); + return this.createWithNamespace(namespace, port, observableSocket); + } - return observableNamespaceSocket; + private createWithNamespace( + namespace: string, + port: number, + observableSocket: ObservableSocketServer + ): ObservableSocketServer { + const adapter = this.applicationConfig.getIoAdapter(); + if (!namespace || !adapter.createWithNamespace) { + return observableSocket; } + const namespaceServer = this.getServerOfNamespace( + namespace, + port, + observableSocket.server + ); + const observableNamespaceSocket = ObservableSocket.create(namespaceServer); + this.socketsContainer.addServer(namespace, port, observableNamespaceSocket); - private getServerOfNamespace(namespace: string, port: number, server) { - const adapter = this.applicationConfig.getIoAdapter(); - return adapter.createWithNamespace(port, this.validateNamespace(namespace), server); - } + return observableNamespaceSocket; + } - private validateNamespace(namespace: string): string { - return validatePath(namespace); - } -} \ No newline at end of file + private getServerOfNamespace(namespace: string, port: number, server) { + const adapter = this.applicationConfig.getIoAdapter(); + return adapter.createWithNamespace( + port, + this.validateNamespace(namespace), + server + ); + } + + private validateNamespace(namespace: string): string { + return validatePath(namespace); + } +} diff --git a/src/websockets/test/container.spec.ts b/src/websockets/test/container.spec.ts index 947c6a41bc4..c5b2655558c 100644 --- a/src/websockets/test/container.spec.ts +++ b/src/websockets/test/container.spec.ts @@ -3,33 +3,32 @@ import { expect } from 'chai'; import { SocketsContainer } from '../container'; describe('SocketsContainer', () => { - const namespace = 'test'; - const port = 30; + const namespace = 'test'; + const port = 30; - let instance: SocketsContainer; - let getSpy: sinon.SinonSpy, - setSpy: sinon.SinonSpy; + let instance: SocketsContainer; + let getSpy: sinon.SinonSpy, setSpy: sinon.SinonSpy; - beforeEach(() => { - setSpy = sinon.spy(); - getSpy = sinon.spy(); - instance = new SocketsContainer(); - (instance)['observableServers'] = { - get: getSpy, - set: setSpy - }; + beforeEach(() => { + setSpy = sinon.spy(); + getSpy = sinon.spy(); + instance = new SocketsContainer(); + (instance)['observableServers'] = { + get: getSpy, + set: setSpy + }; + }); + describe('getSocketServer', () => { + it(`should call "observableServers" get method with expected arguments`, () => { + instance.getServerByPort(port); + expect(getSpy.calledWith({ namespace, port })); }); - describe('getSocketServer', () => { - it(`should call "observableServers" get method with expected arguments`, () => { - instance.getServerByPort(port); - expect(getSpy.calledWith({ namespace, port })); - }); + }); + describe('storeObservableServer', () => { + it(`should call "observableServers" set method with expected arguments`, () => { + const server = {}; + instance.addServer(namespace, port, server); + expect(setSpy.calledWith({ namespace, port }, server)); }); - describe('storeObservableServer', () => { - it(`should call "observableServers" set method with expected arguments`, () => { - const server = {}; - instance.addServer(namespace, port, server); - expect(setSpy.calledWith({ namespace, port }, server)); - }); - }); -}); \ No newline at end of file + }); +}); diff --git a/src/websockets/test/context/exception-filters.context.spec.ts b/src/websockets/test/context/exception-filters.context.spec.ts index a0b78724ad2..c286787dead 100644 --- a/src/websockets/test/context/exception-filters.context.spec.ts +++ b/src/websockets/test/context/exception-filters.context.spec.ts @@ -5,38 +5,44 @@ import { Catch } from '../../../common/decorators/core/catch.decorator'; import { ExceptionFiltersContext } from './../../context/exception-filters-context'; describe('ExceptionFiltersContext', () => { - let moduleName: string; - let exceptionFilter: ExceptionFiltersContext; + let moduleName: string; + let exceptionFilter: ExceptionFiltersContext; - class CustomException {} - @Catch(CustomException) - class ExceptionFilter { - public catch(exc, res) {} - } + class CustomException {} + @Catch(CustomException) + class ExceptionFilter { + public catch(exc, res) {} + } - beforeEach(() => { - moduleName = 'Test'; - exceptionFilter = new ExceptionFiltersContext(); + beforeEach(() => { + moduleName = 'Test'; + exceptionFilter = new ExceptionFiltersContext(); + }); + describe('create', () => { + describe('when filters metadata is empty', () => { + class EmptyMetadata {} + beforeEach(() => { + sinon.stub(exceptionFilter, 'createContext').returns([]); + }); + it('should returns plain ExceptionHandler object', () => { + const filter = exceptionFilter.create( + new EmptyMetadata(), + () => ({} as any) + ); + expect((filter as any).filters).to.be.empty; + }); }); - describe('create', () => { - describe('when filters metadata is empty', () => { - class EmptyMetadata {} - beforeEach(() => { - sinon.stub(exceptionFilter, 'createContext').returns([]); - }); - it('should returns plain ExceptionHandler object', () => { - const filter = exceptionFilter.create(new EmptyMetadata(), () => ({}) as any); - expect((filter as any).filters).to.be.empty; - }); - }); - describe('when filters metadata is not empty', () => { - @UseFilters(new ExceptionFilter()) - class WithMetadata {} + describe('when filters metadata is not empty', () => { + @UseFilters(new ExceptionFilter()) + class WithMetadata {} - it('should returns ExceptionHandler object with exception filters', () => { - const filter = exceptionFilter.create(new WithMetadata(), () => ({}) as any); - expect((filter as any).filters).to.not.be.empty; - }); - }); + it('should returns ExceptionHandler object with exception filters', () => { + const filter = exceptionFilter.create( + new WithMetadata(), + () => ({} as any) + ); + expect((filter as any).filters).to.not.be.empty; + }); }); -}); \ No newline at end of file + }); +}); diff --git a/src/websockets/test/context/ws-context-creator.spec.ts b/src/websockets/test/context/ws-context-creator.spec.ts index b02a55855f3..16254b6fb56 100644 --- a/src/websockets/test/context/ws-context-creator.spec.ts +++ b/src/websockets/test/context/ws-context-creator.spec.ts @@ -18,117 +18,142 @@ import { InterceptorsContextCreator } from '../../../core/interceptors/intercept import { InterceptorsConsumer } from '../../../core/interceptors/interceptors-consumer'; @Guard() -class TestGuard { canActivate: () => true; } +class TestGuard { + canActivate: () => true; +} @Pipe() class TestPipe { - transform(val) { - return val; - } + transform(val) { + return val; + } } describe('WsContextCreator', () => { - let contextCreator: WsContextCreator; - let wsProxy: WsProxy; - let exceptionFiltersContext: ExceptionFiltersContext; - let pipesCreator: PipesContextCreator; - let pipesConsumer: PipesConsumer; - let guardsContextCreator: GuardsContextCreator; - let guardsConsumer: GuardsConsumer; - let instance: Test; - let module: string; + let contextCreator: WsContextCreator; + let wsProxy: WsProxy; + let exceptionFiltersContext: ExceptionFiltersContext; + let pipesCreator: PipesContextCreator; + let pipesConsumer: PipesConsumer; + let guardsContextCreator: GuardsContextCreator; + let guardsConsumer: GuardsConsumer; + let instance: Test; + let module: string; - @UseGuards(TestGuard) - @Component() - class Test { - @UsePipes(new TestPipe()) - test(client: string, data: number) { - return Observable.of(false); - } + @UseGuards(TestGuard) + @Component() + class Test { + @UsePipes(new TestPipe()) + test(client: string, data: number) { + return Observable.of(false); } + } - beforeEach(() => { - wsProxy = new WsProxy(); - exceptionFiltersContext = new ExceptionFiltersContext(); - pipesCreator = new PipesContextCreator(); - pipesConsumer = new PipesConsumer(); - guardsContextCreator = new GuardsContextCreator(new NestContainer()); - guardsConsumer = new GuardsConsumer(); - contextCreator = new WsContextCreator( - wsProxy, exceptionFiltersContext, pipesCreator as any, - pipesConsumer as any, guardsContextCreator as any, guardsConsumer as any, - new InterceptorsContextCreator(new NestContainer()) as any, new InterceptorsConsumer(), - ); + beforeEach(() => { + wsProxy = new WsProxy(); + exceptionFiltersContext = new ExceptionFiltersContext(); + pipesCreator = new PipesContextCreator(); + pipesConsumer = new PipesConsumer(); + guardsContextCreator = new GuardsContextCreator(new NestContainer()); + guardsConsumer = new GuardsConsumer(); + contextCreator = new WsContextCreator( + wsProxy, + exceptionFiltersContext, + pipesCreator as any, + pipesConsumer as any, + guardsContextCreator as any, + guardsConsumer as any, + new InterceptorsContextCreator(new NestContainer()) as any, + new InterceptorsConsumer() + ); - instance = new Test(); - module = 'test'; + instance = new Test(); + module = 'test'; + }); + describe('create', () => { + it('should create exception handler', () => { + const handlerCreateSpy = sinon.spy(exceptionFiltersContext, 'create'); + contextCreator.create(instance, instance.test, module); + expect(handlerCreateSpy.calledWith(instance, instance.test)).to.be.true; }); - describe('create', () => { - it('should create exception handler', () => { - const handlerCreateSpy = sinon.spy(exceptionFiltersContext, 'create'); - contextCreator.create(instance, instance.test, module); - expect(handlerCreateSpy.calledWith(instance, instance.test)).to.be.true; - }); - it('should create pipes context', () => { - const pipesCreateSpy = sinon.spy(pipesCreator, 'create'); - contextCreator.create(instance, instance.test, module); - expect(pipesCreateSpy.calledWith(instance, instance.test)).to.be.true; - }); - it('should create guards context', () => { - const guardsCreateSpy = sinon.spy(guardsContextCreator, 'create'); - contextCreator.create(instance, instance.test, module); - expect(guardsCreateSpy.calledWith(instance, instance.test, module)).to.be.true; - }); - describe('when proxy called', () => { - it('should call guards consumer `tryActivate`', async () => { - const tryActivateSpy = sinon.spy(guardsConsumer, 'tryActivate'); - const proxy = await contextCreator.create(instance, instance.test, module); - const data = 'test'; - await proxy(null, data); + it('should create pipes context', () => { + const pipesCreateSpy = sinon.spy(pipesCreator, 'create'); + contextCreator.create(instance, instance.test, module); + expect(pipesCreateSpy.calledWith(instance, instance.test)).to.be.true; + }); + it('should create guards context', () => { + const guardsCreateSpy = sinon.spy(guardsContextCreator, 'create'); + contextCreator.create(instance, instance.test, module); + expect(guardsCreateSpy.calledWith(instance, instance.test, module)).to.be + .true; + }); + describe('when proxy called', () => { + it('should call guards consumer `tryActivate`', async () => { + const tryActivateSpy = sinon.spy(guardsConsumer, 'tryActivate'); + const proxy = await contextCreator.create( + instance, + instance.test, + module + ); + const data = 'test'; + await proxy(null, data); - expect(tryActivateSpy.called).to.be.true; - }); - describe('when can activate', () => { - it('should call pipes consumer `applyPipes`', async () => { - const applyPipesSpy = sinon.spy(pipesConsumer, 'applyPipes'); - const proxy = await contextCreator.create(instance, instance.test, module); - const data = 'test'; - await proxy(null, data); + expect(tryActivateSpy.called).to.be.true; + }); + describe('when can activate', () => { + it('should call pipes consumer `applyPipes`', async () => { + const applyPipesSpy = sinon.spy(pipesConsumer, 'applyPipes'); + const proxy = await contextCreator.create( + instance, + instance.test, + module + ); + const data = 'test'; + await proxy(null, data); - expect(applyPipesSpy.called).to.be.true; - }); - }); - describe('when can not activate', () => { - it('should throws forbidden exception', async () => { - const tryActivateStub = sinon.stub(guardsConsumer, 'tryActivate').returns(false); - const proxy = await contextCreator.create(instance, instance.test, module); - const data = 'test'; + expect(applyPipesSpy.called).to.be.true; + }); + }); + describe('when can not activate', () => { + it('should throws forbidden exception', async () => { + const tryActivateStub = sinon + .stub(guardsConsumer, 'tryActivate') + .returns(false); + const proxy = await contextCreator.create( + instance, + instance.test, + module + ); + const data = 'test'; - expect(proxy(null, data)).to.eventually.rejectedWith(WsException); - }); - }); + expect(proxy(null, data)).to.eventually.rejectedWith(WsException); }); + }); }); + }); - describe('reflectCallbackParamtypes', () => { - it('should returns paramtypes array', () => { - const paramtypes = contextCreator.reflectCallbackParamtypes(instance, instance.test); - expect(paramtypes).to.be.eql([String, Number]); - }); + describe('reflectCallbackParamtypes', () => { + it('should returns paramtypes array', () => { + const paramtypes = contextCreator.reflectCallbackParamtypes( + instance, + instance.test + ); + expect(paramtypes).to.be.eql([String, Number]); }); + }); - describe('getDataMetatype', () => { - describe('when paramtypes are reflected', () => { - it('should returns data paramtype', () => { - const type = contextCreator.getDataMetatype(instance, instance.test); - expect(type).to.be.eql(Number); - }); - }); - describe('when paramtypes are not reflected', () => { - it('should returns null', () => { - const type = contextCreator.getDataMetatype(instance, () => ({})); - expect(type).to.be.null; - }); - }); + describe('getDataMetatype', () => { + describe('when paramtypes are reflected', () => { + it('should returns data paramtype', () => { + const type = contextCreator.getDataMetatype(instance, instance.test); + expect(type).to.be.eql(Number); + }); + }); + describe('when paramtypes are not reflected', () => { + it('should returns null', () => { + const type = contextCreator.getDataMetatype(instance, () => ({})); + expect(type).to.be.null; + }); }); -}); \ No newline at end of file + }); +}); diff --git a/src/websockets/test/context/ws-proxy.spec.ts b/src/websockets/test/context/ws-proxy.spec.ts index feead480e7e..a6151ba7e36 100644 --- a/src/websockets/test/context/ws-proxy.spec.ts +++ b/src/websockets/test/context/ws-proxy.spec.ts @@ -1,35 +1,34 @@ import * as sinon from 'sinon'; import { expect } from 'chai'; -import { WsProxy} from './../../context/ws-proxy'; +import { WsProxy } from './../../context/ws-proxy'; import { WsExceptionsHandler } from '../../exceptions/ws-exceptions-handler'; import { WsException } from '../../exceptions/ws-exception'; describe('WsProxy', () => { - let routerProxy: WsProxy; - let handlerMock: sinon.SinonMock; - let handler: WsExceptionsHandler; + let routerProxy: WsProxy; + let handlerMock: sinon.SinonMock; + let handler: WsExceptionsHandler; - beforeEach(() => { - handler = new WsExceptionsHandler(); - handlerMock = sinon.mock(handler); - routerProxy = new WsProxy(); - }); - - describe('create', () => { + beforeEach(() => { + handler = new WsExceptionsHandler(); + handlerMock = sinon.mock(handler); + routerProxy = new WsProxy(); + }); - it('should method return thunk', async () => { - const proxy = await routerProxy.create(async (client, data) => {}, handler); - expect(typeof proxy === 'function').to.be.true; - }); - - it('should method encapsulate callback passed as argument', async () => { - const expectation = handlerMock.expects('handle').once(); - const proxy = routerProxy.create(async (client, data) => { - throw new WsException('test'); - }, handler); - await proxy(null, null); - expectation.verify(); - }); + describe('create', () => { + it('should method return thunk', async () => { + const proxy = await routerProxy.create(async (client, data) => {}, + handler); + expect(typeof proxy === 'function').to.be.true; + }); + it('should method encapsulate callback passed as argument', async () => { + const expectation = handlerMock.expects('handle').once(); + const proxy = routerProxy.create(async (client, data) => { + throw new WsException('test'); + }, handler); + await proxy(null, null); + expectation.verify(); }); -}); \ No newline at end of file + }); +}); diff --git a/src/websockets/test/exceptions/ws-exception.spec.ts b/src/websockets/test/exceptions/ws-exception.spec.ts index a872389317f..a00d30d5ec9 100644 --- a/src/websockets/test/exceptions/ws-exception.spec.ts +++ b/src/websockets/test/exceptions/ws-exception.spec.ts @@ -3,12 +3,12 @@ import { expect } from 'chai'; import { WsException } from '../../exceptions/ws-exception'; describe('WsException', () => { - let instance: WsException; - const error = 'test'; - beforeEach(() => { - instance = new WsException(error); - }); - it('should returns error message or object', () => { - expect(instance.getError()).to.be.eql(error); - }); -}); \ No newline at end of file + let instance: WsException; + const error = 'test'; + beforeEach(() => { + instance = new WsException(error); + }); + it('should returns error message or object', () => { + expect(instance.getError()).to.be.eql(error); + }); +}); diff --git a/src/websockets/test/exceptions/ws-exceptions-handler.spec.ts b/src/websockets/test/exceptions/ws-exceptions-handler.spec.ts index a32e1a65e8e..5808facffa4 100644 --- a/src/websockets/test/exceptions/ws-exceptions-handler.spec.ts +++ b/src/websockets/test/exceptions/ws-exceptions-handler.spec.ts @@ -4,108 +4,109 @@ import { WsExceptionsHandler } from './../../exceptions/ws-exceptions-handler'; import { WsException } from './../../exceptions/ws-exception'; describe('WsExceptionsHandler', () => { - let handler: WsExceptionsHandler; - let emitStub: sinon.SinonStub; - let client; + let handler: WsExceptionsHandler; + let emitStub: sinon.SinonStub; + let client; - beforeEach(() => { - handler = new WsExceptionsHandler(); - emitStub = sinon.stub(); - client = { - emit: emitStub, - }; - client.emit.returns(client); + beforeEach(() => { + handler = new WsExceptionsHandler(); + emitStub = sinon.stub(); + client = { + emit: emitStub + }; + client.emit.returns(client); + }); + + describe('handle', () => { + it('should method emit expected status code message when exception is unknown', () => { + handler.handle(new Error(), client); + expect( + emitStub.calledWith('exception', { + status: 'error', + message: 'Internal server error' + }) + ).to.be.true; }); + describe('when exception is instance of WsException', () => { + it('should method emit expected status and json object', () => { + const message = { + custom: 'Unauthorized' + }; + handler.handle(new WsException(message), client); + expect(emitStub.calledWith('exception', message)).to.be.true; + }); + it('should method emit expected status and transform message to json', () => { + const message = 'Unauthorized'; - describe('handle', () => { - it('should method emit expected status code message when exception is unknown', () => { - handler.handle(new Error(), client); - expect(emitStub.calledWith( - 'exception', - { status: 'error', message: 'Internal server error' }, - )).to.be.true; - }); - describe('when exception is instance of WsException', () => { - it('should method emit expected status and json object', () => { - const message = { - custom: 'Unauthorized', - }; - handler.handle(new WsException(message), client); - expect(emitStub.calledWith('exception', message)).to.be.true; - }); - it('should method emit expected status and transform message to json', () => { - const message = 'Unauthorized'; + handler.handle(new WsException(message), client); + expect(emitStub.calledWith('exception', { message, status: 'error' })) + .to.be.true; + }); + }); + describe('when "invokeCustomFilters" returns true', () => { + beforeEach(() => { + sinon.stub(handler, 'invokeCustomFilters').returns(true); + }); + it('should not call `emit`', () => { + handler.handle(new WsException(''), client); + expect(emitStub.notCalled).to.be.true; + }); + }); + }); + describe('setCustomFilters', () => { + const filters = ['test', 'test2']; + it('should set custom filters', () => { + handler.setCustomFilters(filters as any); + expect((handler as any).filters).to.be.eql(filters); + }); + it('should throws exception when passed argument is not an array', () => { + expect(() => handler.setCustomFilters(null)).to.throw; + }); + }); + describe('invokeCustomFilters', () => { + describe('when filters array is empty', () => { + it('should returns false', () => { + expect(handler.invokeCustomFilters(null, null)).to.be.false; + }); + }); + describe('when filters array is not empty', () => { + let filters, funcSpy; + class TestException {} - handler.handle(new WsException(message), client); - expect(emitStub.calledWith('exception', { message, status: 'error' })).to.be.true; - }); + beforeEach(() => { + funcSpy = sinon.spy(); + }); + describe('when filter exists in filters array', () => { + beforeEach(() => { + filters = [{ exceptionMetatypes: [TestException], func: funcSpy }]; + (handler as any).filters = filters; }); - describe('when "invokeCustomFilters" returns true', () => { - beforeEach(() => { - sinon.stub(handler, 'invokeCustomFilters').returns(true); - }); - it('should not call `emit`', () => { - handler.handle(new WsException(''), client); - expect(emitStub.notCalled).to.be.true; - }); + it('should call funcSpy', () => { + handler.invokeCustomFilters(new TestException(), null); + expect(funcSpy.notCalled).to.be.false; }); - }); - describe('setCustomFilters', () => { - const filters = [ 'test', 'test2' ]; - it('should set custom filters', () => { - handler.setCustomFilters(filters as any); - expect((handler as any).filters).to.be.eql(filters); + it('should call funcSpy with exception and response passed as an arguments', () => { + const exception = new TestException(); + const res = { foo: 'bar' }; + + handler.invokeCustomFilters(exception, res); + expect(funcSpy.calledWith(exception, res)).to.be.true; }); - it('should throws exception when passed argument is not an array', () => { - expect( - () => handler.setCustomFilters(null), - ).to.throw; + it('should returns true', () => { + expect(handler.invokeCustomFilters(new TestException(), null)).to.be + .true; }); - }); - describe('invokeCustomFilters', () => { - describe('when filters array is empty', () => { - it('should returns false', () => { - expect(handler.invokeCustomFilters(null, null)).to.be.false; - }); + }); + describe('when filter does not exists in filters array', () => { + it('should not call funcSpy', () => { + handler.invokeCustomFilters(new TestException(), null); + expect(funcSpy.notCalled).to.be.true; }); - describe('when filters array is not empty', () => { - let filters, funcSpy; - class TestException {} - - beforeEach(() => { - funcSpy = sinon.spy(); - }); - describe('when filter exists in filters array', () => { - beforeEach(() => { - filters = [ - { exceptionMetatypes: [ TestException ], func: funcSpy }, - ]; - (handler as any).filters = filters; - }); - it('should call funcSpy', () => { - handler.invokeCustomFilters(new TestException(), null); - expect(funcSpy.notCalled).to.be.false; - }); - it('should call funcSpy with exception and response passed as an arguments', () => { - const exception = new TestException(); - const res = { foo: 'bar' }; - - handler.invokeCustomFilters(exception, res); - expect(funcSpy.calledWith(exception, res)).to.be.true; - }); - it('should returns true', () => { - expect(handler.invokeCustomFilters(new TestException(), null)).to.be.true; - }); - }); - describe('when filter does not exists in filters array', () => { - it('should not call funcSpy', () => { - handler.invokeCustomFilters(new TestException(), null); - expect(funcSpy.notCalled).to.be.true; - }); - it('should returns false', () => { - expect(handler.invokeCustomFilters(new TestException(), null)).to.be.false; - }); - }); + it('should returns false', () => { + expect(handler.invokeCustomFilters(new TestException(), null)).to.be + .false; }); + }); }); -}); \ No newline at end of file + }); +}); diff --git a/src/websockets/test/gateway-metadata-explorer.spec.ts b/src/websockets/test/gateway-metadata-explorer.spec.ts index f02455408d6..7f80c86e8fe 100644 --- a/src/websockets/test/gateway-metadata-explorer.spec.ts +++ b/src/websockets/test/gateway-metadata-explorer.spec.ts @@ -7,70 +7,72 @@ import { GatewayMetadataExplorer } from '../gateway-metadata-explorer'; import { MetadataScanner } from '../../core/metadata-scanner'; describe('GatewayMetadataExplorer', () => { - const message = 'test'; - const secMessage = 'test2'; + const message = 'test'; + const secMessage = 'test2'; - @WebSocketGateway() - class Test { - @WebSocketServer() public server; - @WebSocketServer() public anotherServer; + @WebSocketGateway() + class Test { + @WebSocketServer() public server; + @WebSocketServer() public anotherServer; - get testGet() { return 0; } - set testSet(val) {} + get testGet() { + return 0; + } + set testSet(val) {} - constructor() {} + constructor() {} - @SubscribeMessage({ value: message }) - public test() {} + @SubscribeMessage({ value: message }) + public test() {} - @SubscribeMessage({ value: secMessage }) - public testSec() {} + @SubscribeMessage({ value: secMessage }) + public testSec() {} - public noMessage() {} - } - let instance: GatewayMetadataExplorer; - let scanner: MetadataScanner; + public noMessage() {} + } + let instance: GatewayMetadataExplorer; + let scanner: MetadataScanner; + beforeEach(() => { + scanner = new MetadataScanner(); + instance = new GatewayMetadataExplorer(scanner); + }); + describe('explore', () => { + let scanFromPrototype: sinon.SinonSpy; beforeEach(() => { - scanner = new MetadataScanner(); - instance = new GatewayMetadataExplorer(scanner); + scanFromPrototype = sinon.spy(scanner, 'scanFromPrototype'); }); - describe('explore', () => { - let scanFromPrototype: sinon.SinonSpy; - beforeEach(() => { - scanFromPrototype = sinon.spy(scanner, 'scanFromPrototype'); - }); - it(`should call "scanFromPrototype" with expected arguments`, () => { - const obj = new Test(); - instance.explore(obj as any); + it(`should call "scanFromPrototype" with expected arguments`, () => { + const obj = new Test(); + instance.explore(obj as any); - const [ argObj, argProto ] = scanFromPrototype.getCall(0).args; - expect(argObj).to.be.eql(obj); - expect(argProto).to.be.eql(Object.getPrototypeOf(obj)); - }); + const [argObj, argProto] = scanFromPrototype.getCall(0).args; + expect(argObj).to.be.eql(obj); + expect(argProto).to.be.eql(Object.getPrototypeOf(obj)); + }); + }); + describe('exploreMethodMetadata', () => { + let test: Test; + beforeEach(() => { + test = new Test(); + }); + it(`should return null when "isMessageMapping" metadata is undefined`, () => { + const metadata = instance.exploreMethodMetadata(test, 'noMessage'); + expect(metadata).to.eq(null); }); - describe('exploreMethodMetadata', () => { - let test: Test; - beforeEach(() => { - test = new Test(); - }); - it(`should return null when "isMessageMapping" metadata is undefined`, () => { - const metadata = instance.exploreMethodMetadata(test, 'noMessage'); - expect(metadata).to.eq(null); - }); - it(`should return message mapping properties when "isMessageMapping" metadata is not undefined`, () => { - const metadata = instance.exploreMethodMetadata(test, 'test'); - expect(metadata).to.have.keys([ 'callback', 'message' ]); - expect(metadata.message).to.eql(message); - }); + it(`should return message mapping properties when "isMessageMapping" metadata is not undefined`, () => { + const metadata = instance.exploreMethodMetadata(test, 'test'); + expect(metadata).to.have.keys(['callback', 'message']); + expect(metadata.message).to.eql(message); }); - describe('scanForServerHooks', () => { - it(`should returns properties with @Client decorator`, () => { - const obj = new Test(); - const servers = [ ...instance.scanForServerHooks(obj as any) ]; + }); + describe('scanForServerHooks', () => { + it(`should returns properties with @Client decorator`, () => { + const obj = new Test(); + const servers = [...instance.scanForServerHooks(obj as any)]; - expect(servers).to.have.length(2); - expect(servers).to.deep.eq([ 'server', 'anotherServer' ]); - }); + expect(servers).to.have.length(2); + expect(servers).to.deep.eq(['server', 'anotherServer']); }); -}); \ No newline at end of file + }); +}); diff --git a/src/websockets/test/middlewares-injector.spec.ts b/src/websockets/test/middlewares-injector.spec.ts index a64c0370709..2fb5ee09018 100644 --- a/src/websockets/test/middlewares-injector.spec.ts +++ b/src/websockets/test/middlewares-injector.spec.ts @@ -7,118 +7,125 @@ import { RuntimeException } from '../../core/errors/exceptions/runtime.exception import { ApplicationConfig } from '@nestjs/core/application-config'; describe('MiddlewaresInjector', () => { - let injector: MiddlewaresInjector; - let container; - let modules; + let injector: MiddlewaresInjector; + let container; + let modules; + + beforeEach(() => { + modules = new Map(); + container = { + getModules: () => modules + }; + injector = new MiddlewaresInjector( + container as any, + new ApplicationConfig(new IoAdapter()) + ); + }); + describe('inject', () => { + const tokens = [1, 2, 3]; beforeEach(() => { - modules = new Map(); - container = { - getModules: () => modules, - }; - injector = new MiddlewaresInjector(container as any, new ApplicationConfig(new IoAdapter())); + sinon.stub(injector, 'reflectMiddlewaresTokens').returns(tokens); }); - describe('inject', () => { - const tokens = [1, 2, 3]; - - beforeEach(() => { - sinon.stub(injector, 'reflectMiddlewaresTokens').returns(tokens); - }); - it('should throws exception when module is not known', () => { - sinon.stub(modules, 'has').returns(false); - expect( - () => injector.inject(null, null, ''), - ).to.throws(Error); - }); - it('should call "applyMiddlewares" with expected arguments', () => { - const components = {}; + it('should throws exception when module is not known', () => { + sinon.stub(modules, 'has').returns(false); + expect(() => injector.inject(null, null, '')).to.throws(Error); + }); + it('should call "applyMiddlewares" with expected arguments', () => { + const components = {}; - sinon.stub(modules, 'has').returns(true); - sinon.stub(modules, 'get').returns({components}); + sinon.stub(modules, 'has').returns(true); + sinon.stub(modules, 'get').returns({ components }); - const stub: sinon.SinonStub = sinon.stub(injector, 'applyMiddlewares'); - const server = {}; + const stub: sinon.SinonStub = sinon.stub(injector, 'applyMiddlewares'); + const server = {}; - injector.inject(server, null, ''); - expect(stub.calledWith(server, components, tokens)).to.be.true; - }); + injector.inject(server, null, ''); + expect(stub.calledWith(server, components, tokens)).to.be.true; }); - describe('reflectMiddlewaresTokens', () => { - const middlewares: any = [1, 2, 3]; - @WebSocketGateway({ - middlewares, - }) - class Test {} - it('should returns expected list of middlewares', () => { - expect( - injector.reflectMiddlewaresTokens(new Test()), - ).to.be.equal(middlewares); - }); + }); + describe('reflectMiddlewaresTokens', () => { + const middlewares: any = [1, 2, 3]; + @WebSocketGateway({ + middlewares + }) + class Test {} + it('should returns expected list of middlewares', () => { + expect(injector.reflectMiddlewaresTokens(new Test())).to.be.equal( + middlewares + ); }); - describe('applyMiddlewares', () => { - let server: { use: sinon.SinonSpy }; - const setAsName = name => ({ name }); - const tokens = [1, null, 'test', undefined]; + }); + describe('applyMiddlewares', () => { + let server: { use: sinon.SinonSpy }; + const setAsName = name => ({ name }); + const tokens = [1, null, 'test', undefined]; - beforeEach(() => { - server = { - use: sinon.spy(), - }; - sinon.stub(injector, 'bindMiddleware').callsFake(a => a); - }); - it('should apply expected middlewares', () => { - injector.applyMiddlewares(server, null, tokens.map(setAsName) as any); - expect(server.use.callCount).to.be.eql(2); - expect(server.use.calledWith(1)).to.be.true; - }); + beforeEach(() => { + server = { + use: sinon.spy() + }; + sinon.stub(injector, 'bindMiddleware').callsFake(a => a); }); - describe('bindMiddleware', () => { - let stub: sinon.SinonStub; - const components = new Map(); - it('should throws exception when middleware does not exists in collection', () => { - stub = sinon.stub(components, 'has').returns(false); - expect( - () => injector.bindMiddleware('', components), - ).to.throws(Error); - }); - describe('when components collection "has" method returns true', () => { - let getStub: sinon.SinonStub; - before(() => { - getStub = sinon.stub(components, 'get'); - }); - beforeEach(() => { - stub.returns(true); - }); - it('should returns null when object is not a gateway middleware', () => { - const instance = {}; - getStub.returns({instance}); - expect(injector.bindMiddleware('', components)).to.be.null; - }); - it('should returns null when result of "object.resolve()" operation is not a function', () => { - const instance = { resolve() { return ({}); }}; - getStub.returns({instance}); + it('should apply expected middlewares', () => { + injector.applyMiddlewares(server, null, tokens.map(setAsName) as any); + expect(server.use.callCount).to.be.eql(2); + expect(server.use.calledWith(1)).to.be.true; + }); + }); + describe('bindMiddleware', () => { + let stub: sinon.SinonStub; + const components = new Map(); + it('should throws exception when middleware does not exists in collection', () => { + stub = sinon.stub(components, 'has').returns(false); + expect(() => injector.bindMiddleware('', components)).to.throws(Error); + }); + describe('when components collection "has" method returns true', () => { + let getStub: sinon.SinonStub; + before(() => { + getStub = sinon.stub(components, 'get'); + }); + beforeEach(() => { + stub.returns(true); + }); + it('should returns null when object is not a gateway middleware', () => { + const instance = {}; + getStub.returns({ instance }); + expect(injector.bindMiddleware('', components)).to.be.null; + }); + it('should returns null when result of "object.resolve()" operation is not a function', () => { + const instance = { + resolve() { + return {}; + } + }; + getStub.returns({ instance }); - expect(injector.bindMiddleware('', components)).to.be.null; - }); - it('should returns function', () => { - const instance = { resolve() { return () => ({}); }}; - getStub.returns({instance}); + expect(injector.bindMiddleware('', components)).to.be.null; + }); + it('should returns function', () => { + const instance = { + resolve() { + return () => ({}); + } + }; + getStub.returns({ instance }); - expect(injector.bindMiddleware('', components)).to.be.a('function'); - }); - }); + expect(injector.bindMiddleware('', components)).to.be.a('function'); + }); + }); + }); + describe('isGatewayMiddleware', () => { + class ValidGateway { + public resolve() { + return (...args) => ({}); + } + } + it('should returns false when object is not a gateway middleware', () => { + expect(injector.isGatewayMiddleware(new ValidGateway())).to.be.true; }); - describe('isGatewayMiddleware', () => { - class ValidGateway { - public resolve() { - return (...args) => ({}); - } - } - it('should returns false when object is not a gateway middleware', () => { - expect(injector.isGatewayMiddleware(new ValidGateway())).to.be.true; - }); - it('should returns true when object is not a gateway middleware', () => { - expect(injector.isGatewayMiddleware({})).to.be.false; - }); + it('should returns true when object is not a gateway middleware', () => { + expect(injector.isGatewayMiddleware({})).to.be.false; }); -}); \ No newline at end of file + }); +}); diff --git a/src/websockets/test/observable-socket.spec.ts b/src/websockets/test/observable-socket.spec.ts index 741c5d59c75..e024b4eae46 100644 --- a/src/websockets/test/observable-socket.spec.ts +++ b/src/websockets/test/observable-socket.spec.ts @@ -4,16 +4,16 @@ import { ReplaySubject } from 'rxjs/ReplaySubject'; import { Subject } from 'rxjs/Subject'; describe('ObservableSocket', () => { - describe('create', () => { - it(`should return expected observable socket object`, () => { - const server = { test: 'test' }; - const result = ObservableSocket.create(server); + describe('create', () => { + it(`should return expected observable socket object`, () => { + const server = { test: 'test' }; + const result = ObservableSocket.create(server); - expect(result).to.have.keys('init', 'connection', 'disconnect', 'server'); - expect(result.init instanceof ReplaySubject).to.be.true; - expect(result.connection instanceof Subject).to.be.true; - expect(result.disconnect instanceof Subject).to.be.true; - expect(result.server).to.be.eql(server); - }); + expect(result).to.have.keys('init', 'connection', 'disconnect', 'server'); + expect(result.init instanceof ReplaySubject).to.be.true; + expect(result.connection instanceof Subject).to.be.true; + expect(result.disconnect instanceof Subject).to.be.true; + expect(result.server).to.be.eql(server); }); -}); \ No newline at end of file + }); +}); diff --git a/src/websockets/test/socket-server-provider.spec.ts b/src/websockets/test/socket-server-provider.spec.ts index daae025aea3..db768032f14 100644 --- a/src/websockets/test/socket-server-provider.spec.ts +++ b/src/websockets/test/socket-server-provider.spec.ts @@ -6,40 +6,42 @@ import { ApplicationConfig } from '@nestjs/core/application-config'; import { IoAdapter } from '@nestjs/websockets/adapters/io-adapter'; describe('SocketServerProvider', () => { - let instance: SocketServerProvider; - let socketsContainer: SocketsContainer, - mockContainer: sinon.SinonMock; + let instance: SocketServerProvider; + let socketsContainer: SocketsContainer, mockContainer: sinon.SinonMock; + + beforeEach(() => { + socketsContainer = new SocketsContainer(); + mockContainer = sinon.mock(socketsContainer); + instance = new SocketServerProvider( + socketsContainer, + new ApplicationConfig(new IoAdapter()) + ); + }); + describe('scanForSocketServer', () => { + let createSocketServerSpy: sinon.SinonSpy; + const namespace = 'test'; + const port = 30; beforeEach(() => { - socketsContainer = new SocketsContainer(); - mockContainer = sinon.mock(socketsContainer); - instance = new SocketServerProvider(socketsContainer, new ApplicationConfig(new IoAdapter())); + createSocketServerSpy = sinon.spy(instance, 'createSocketServer'); }); - describe('scanForSocketServer', () => { - let createSocketServerSpy: sinon.SinonSpy; - const namespace = 'test'; - const port = 30; - - beforeEach(() => { - createSocketServerSpy = sinon.spy(instance, 'createSocketServer'); - }); - afterEach(() => { - mockContainer.restore(); - }); - it(`should returns stored server`, () => { - const server = { test: 'test' }; - mockContainer.expects('getServerByPort').returns(server); + afterEach(() => { + mockContainer.restore(); + }); + it(`should returns stored server`, () => { + const server = { test: 'test' }; + mockContainer.expects('getServerByPort').returns(server); - const result = instance.scanForSocketServer(null, port); + const result = instance.scanForSocketServer(null, port); - expect(createSocketServerSpy.called).to.be.false; - expect(result).to.eq(server); - }); - it(`should call "createSocketServer" when server is not stored already`, () => { - mockContainer.expects('getServerByPort').returns(null); + expect(createSocketServerSpy.called).to.be.false; + expect(result).to.eq(server); + }); + it(`should call "createSocketServer" when server is not stored already`, () => { + mockContainer.expects('getServerByPort').returns(null); - instance.scanForSocketServer(namespace, port); - expect(createSocketServerSpy.called).to.be.true; - }); + instance.scanForSocketServer(namespace, port); + expect(createSocketServerSpy.called).to.be.true; }); -}); \ No newline at end of file + }); +}); diff --git a/src/websockets/test/utils/gateway-server.decorator.spec.ts b/src/websockets/test/utils/gateway-server.decorator.spec.ts index 7ec75154431..562988bf0f7 100644 --- a/src/websockets/test/utils/gateway-server.decorator.spec.ts +++ b/src/websockets/test/utils/gateway-server.decorator.spec.ts @@ -1,19 +1,22 @@ import 'reflect-metadata'; -import { expect } from 'chai' +import { expect } from 'chai'; import { WebSocketServer } from '../../utils/gateway-server.decorator'; import { GATEWAY_SERVER_METADATA } from '../../constants'; describe('@WebSocketServer', () => { - class TestGateway { - @WebSocketServer() - static server; - } + class TestGateway { + @WebSocketServer() static server; + } - it('should decorate server property with expected metadata', () => { - const isServer = Reflect.getOwnMetadata(GATEWAY_SERVER_METADATA, TestGateway, 'server'); - expect(isServer).to.be.eql(true); - }); - it('should set property value to null by default', () => { - expect(TestGateway.server).to.be.eql(null); - }); -}); \ No newline at end of file + it('should decorate server property with expected metadata', () => { + const isServer = Reflect.getOwnMetadata( + GATEWAY_SERVER_METADATA, + TestGateway, + 'server' + ); + expect(isServer).to.be.eql(true); + }); + it('should set property value to null by default', () => { + expect(TestGateway.server).to.be.eql(null); + }); +}); diff --git a/src/websockets/test/utils/socket-gateway.decorator.spec.ts b/src/websockets/test/utils/socket-gateway.decorator.spec.ts index 56b6c796e10..6b5fff8c8be 100644 --- a/src/websockets/test/utils/socket-gateway.decorator.spec.ts +++ b/src/websockets/test/utils/socket-gateway.decorator.spec.ts @@ -3,18 +3,16 @@ import { expect } from 'chai'; import { WebSocketGateway } from '../../utils/socket-gateway.decorator'; describe('@WebSocketGateway', () => { + @WebSocketGateway({ port: 80, namespace: '/' }) + class TestGateway {} - @WebSocketGateway({ port: 80, namespace: '/' }) - class TestGateway {} + it('should decorate transport with expected metadata', () => { + const isGateway = Reflect.getMetadata('__isGateway', TestGateway); + const port = Reflect.getMetadata('port', TestGateway); + const namespace = Reflect.getMetadata('namespace', TestGateway); - it('should decorate transport with expected metadata', () => { - const isGateway = Reflect.getMetadata('__isGateway', TestGateway); - const port = Reflect.getMetadata('port', TestGateway); - const namespace = Reflect.getMetadata('namespace', TestGateway); - - expect(isGateway).to.be.eql(true); - expect(port).to.be.eql(80); - expect(namespace).to.be.eql('/'); - }); - -}); \ No newline at end of file + expect(isGateway).to.be.eql(true); + expect(port).to.be.eql(80); + expect(namespace).to.be.eql('/'); + }); +}); diff --git a/src/websockets/test/utils/subscribe-message.decorator.spec.ts b/src/websockets/test/utils/subscribe-message.decorator.spec.ts index 11ac25d98cc..01aa9df91d9 100644 --- a/src/websockets/test/utils/subscribe-message.decorator.spec.ts +++ b/src/websockets/test/utils/subscribe-message.decorator.spec.ts @@ -3,18 +3,19 @@ import { expect } from 'chai'; import { SubscribeMessage } from '../../utils/subscribe-message.decorator'; describe('@SubscribeMessage', () => { + class TestGateway { + @SubscribeMessage({ value: 'filter' }) + static fn() {} + } - class TestGateway { - @SubscribeMessage({ value: 'filter' }) - static fn() {} - } + it('should decorate transport with expected metadata', () => { + const isMessageMapping = Reflect.getMetadata( + '__isMessageMapping', + TestGateway.fn + ); + const message = Reflect.getMetadata('message', TestGateway.fn); - it('should decorate transport with expected metadata', () => { - const isMessageMapping = Reflect.getMetadata('__isMessageMapping', TestGateway.fn); - const message = Reflect.getMetadata('message', TestGateway.fn); - - expect(isMessageMapping).to.be.true; - expect(message).to.be.eql('filter'); - }); - -}); \ No newline at end of file + expect(isMessageMapping).to.be.true; + expect(message).to.be.eql('filter'); + }); +}); diff --git a/src/websockets/test/web-sockets-controller.spec.ts b/src/websockets/test/web-sockets-controller.spec.ts index b2422450520..77ed709c813 100644 --- a/src/websockets/test/web-sockets-controller.spec.ts +++ b/src/websockets/test/web-sockets-controller.spec.ts @@ -8,309 +8,335 @@ import { GatewayMetadataExplorer } from '../gateway-metadata-explorer'; import { MetadataScanner } from '../../core/metadata-scanner'; import { ApplicationConfig } from '@nestjs/core/application-config'; import { WsContextCreator } from '../context/ws-context-creator'; -import { Observable } from "rxjs/Observable"; -import { IoAdapter } from "../index"; +import { Observable } from 'rxjs/Observable'; +import { IoAdapter } from '../index'; describe('WebSocketsController', () => { - let instance: WebSocketsController; - let provider: SocketServerProvider, - config: ApplicationConfig, - mockProvider: sinon.SinonMock; + let instance: WebSocketsController; + let provider: SocketServerProvider, + config: ApplicationConfig, + mockProvider: sinon.SinonMock; - const port = 90, namespace = '/'; - @WebSocketGateway({ port, namespace }) - class Test { + const port = 90, + namespace = '/'; + @WebSocketGateway({ port, namespace }) + class Test {} - } + beforeEach(() => { + config = new ApplicationConfig(new IoAdapter()); + provider = new SocketServerProvider(null, config); + mockProvider = sinon.mock(provider); + instance = new WebSocketsController( + provider, + null, + config, + sinon.createStubInstance(WsContextCreator) + ); + }); + describe('hookGatewayIntoServer', () => { + let subscribeObservableServer: sinon.SinonSpy; - beforeEach(() => { - config = new ApplicationConfig(new IoAdapter()); - provider = new SocketServerProvider(null, config); - mockProvider = sinon.mock(provider); - instance = new WebSocketsController(provider, null, config, sinon.createStubInstance(WsContextCreator)); - }); - describe('hookGatewayIntoServer', () => { - let subscribeObservableServer: sinon.SinonSpy; - - @WebSocketGateway({ port: 'test' } as any) - class InvalidGateway {} + @WebSocketGateway({ port: 'test' } as any) + class InvalidGateway {} - @WebSocketGateway() - class DefaultGateway {} + @WebSocketGateway() + class DefaultGateway {} - beforeEach(() => { - subscribeObservableServer = sinon.spy(); - (instance as any).subscribeObservableServer = subscribeObservableServer; - }); - it('should throws "InvalidSocketPortException" when port is not a number', () => { - expect( - () => instance.hookGatewayIntoServer(new InvalidGateway(), InvalidGateway, ''), - ).throws(InvalidSocketPortException); - }); - it('should call "subscribeObservableServer" with default values when metadata is empty', () => { - const gateway = new DefaultGateway(); - instance.hookGatewayIntoServer(gateway, DefaultGateway, ''); - expect(subscribeObservableServer.calledWith(gateway, '', 0)).to.be.true; - }); - it('should call "subscribeObservableServer" when metadata is valid', () => { - const gateway = new Test(); - instance.hookGatewayIntoServer(gateway, Test, ''); - expect(subscribeObservableServer.calledWith(gateway, namespace, port)).to.be.true; - }); + beforeEach(() => { + subscribeObservableServer = sinon.spy(); + (instance as any).subscribeObservableServer = subscribeObservableServer; + }); + it('should throws "InvalidSocketPortException" when port is not a number', () => { + expect(() => + instance.hookGatewayIntoServer(new InvalidGateway(), InvalidGateway, '') + ).throws(InvalidSocketPortException); }); - describe('subscribeObservableServer', () => { - let explorer: GatewayMetadataExplorer, - mockExplorer: sinon.SinonMock, - gateway, handlers, server, - hookServerToProperties: sinon.SinonSpy, - subscribeEvents: sinon.SinonSpy; + it('should call "subscribeObservableServer" with default values when metadata is empty', () => { + const gateway = new DefaultGateway(); + instance.hookGatewayIntoServer(gateway, DefaultGateway, ''); + expect(subscribeObservableServer.calledWith(gateway, '', 0)).to.be.true; + }); + it('should call "subscribeObservableServer" when metadata is valid', () => { + const gateway = new Test(); + instance.hookGatewayIntoServer(gateway, Test, ''); + expect(subscribeObservableServer.calledWith(gateway, namespace, port)).to + .be.true; + }); + }); + describe('subscribeObservableServer', () => { + let explorer: GatewayMetadataExplorer, + mockExplorer: sinon.SinonMock, + gateway, + handlers, + server, + hookServerToProperties: sinon.SinonSpy, + subscribeEvents: sinon.SinonSpy; - beforeEach(() => { - gateway = new Test(); - explorer = new GatewayMetadataExplorer(new MetadataScanner()); - mockExplorer = sinon.mock(explorer); - (instance as any).metadataExplorer = explorer; + beforeEach(() => { + gateway = new Test(); + explorer = new GatewayMetadataExplorer(new MetadataScanner()); + mockExplorer = sinon.mock(explorer); + (instance as any).metadataExplorer = explorer; - handlers = [ 'test' ]; - server = { server: 'test' }; + handlers = ['test']; + server = { server: 'test' }; - mockExplorer.expects('explore').returns(handlers); - mockProvider.expects('scanForSocketServer').returns(server); + mockExplorer.expects('explore').returns(handlers); + mockProvider.expects('scanForSocketServer').returns(server); - hookServerToProperties = sinon.spy(); - subscribeEvents = sinon.spy(); + hookServerToProperties = sinon.spy(); + subscribeEvents = sinon.spy(); - (instance as any).hookServerToProperties = hookServerToProperties; - (instance as any).subscribeEvents = subscribeEvents; + (instance as any).hookServerToProperties = hookServerToProperties; + (instance as any).subscribeEvents = subscribeEvents; - sinon.stub(instance, 'injectMiddlewares').returns(0); - }); - it('should call "hookServerToProperties" with expected arguments', () => { - instance.subscribeObservableServer(gateway, namespace, port, ''); - expect(hookServerToProperties.calledWith(gateway, server.server)); - }); - it('should call "subscribeEvents" with expected arguments', () => { - instance.subscribeObservableServer(gateway, namespace, port, ''); - expect(subscribeEvents.calledWith(gateway, handlers, server)); - }); + sinon.stub(instance, 'injectMiddlewares').returns(0); + }); + it('should call "hookServerToProperties" with expected arguments', () => { + instance.subscribeObservableServer(gateway, namespace, port, ''); + expect(hookServerToProperties.calledWith(gateway, server.server)); + }); + it('should call "subscribeEvents" with expected arguments', () => { + instance.subscribeObservableServer(gateway, namespace, port, ''); + expect(subscribeEvents.calledWith(gateway, handlers, server)); }); - describe('subscribeEvents', () => { - const gateway = new Test(); + }); + describe('subscribeEvents', () => { + const gateway = new Test(); - let handlers; - let server, - subscribeConnectionEvent: sinon.SinonSpy, - subscribeDisconnectEvent: sinon.SinonSpy, - nextSpy: sinon.SinonSpy, - onSpy: sinon.SinonSpy, - subscribeInitEvent: sinon.SinonSpy, - getConnectionHandler: sinon.SinonSpy; + let handlers; + let server, + subscribeConnectionEvent: sinon.SinonSpy, + subscribeDisconnectEvent: sinon.SinonSpy, + nextSpy: sinon.SinonSpy, + onSpy: sinon.SinonSpy, + subscribeInitEvent: sinon.SinonSpy, + getConnectionHandler: sinon.SinonSpy; - beforeEach(() => { - nextSpy = sinon.spy(); - onSpy = sinon.spy(); - subscribeInitEvent = sinon.spy(); - getConnectionHandler = sinon.spy(); - subscribeConnectionEvent = sinon.spy(); - subscribeDisconnectEvent = sinon.spy(); + beforeEach(() => { + nextSpy = sinon.spy(); + onSpy = sinon.spy(); + subscribeInitEvent = sinon.spy(); + getConnectionHandler = sinon.spy(); + subscribeConnectionEvent = sinon.spy(); + subscribeDisconnectEvent = sinon.spy(); - handlers = [ 'test' ]; - server = { - server: { - on: onSpy - }, - init: { - next: nextSpy, - }, - disconnect: {}, - connection: {}, - }; + handlers = ['test']; + server = { + server: { + on: onSpy + }, + init: { + next: nextSpy + }, + disconnect: {}, + connection: {} + }; - (instance as any).subscribeInitEvent = subscribeInitEvent; - (instance as any).getConnectionHandler = getConnectionHandler; - (instance as any).subscribeConnectionEvent = subscribeConnectionEvent; - (instance as any).subscribeDisconnectEvent = subscribeDisconnectEvent; - }); + (instance as any).subscribeInitEvent = subscribeInitEvent; + (instance as any).getConnectionHandler = getConnectionHandler; + (instance as any).subscribeConnectionEvent = subscribeConnectionEvent; + (instance as any).subscribeDisconnectEvent = subscribeDisconnectEvent; + }); - it('should call "next" method of server object with expected argument', () => { - instance.subscribeEvents(gateway, handlers, server as any); - expect(nextSpy.calledWith(server.server)).to.be.true; - }); - it('should call "subscribeConnectionEvent" with expected arguments', () => { - instance.subscribeEvents(gateway, handlers, server as any); - expect(subscribeConnectionEvent.calledWith(gateway, server.connection)).to.be.true; - }); - it('should call "subscribeDisconnectEvent" with expected arguments', () => { - instance.subscribeEvents(gateway, handlers, server as any); - expect(subscribeDisconnectEvent.calledWith(gateway, server.disconnect)).to.be.true; - }); - it('should call "subscribeInitEvent" with expected arguments', () => { - instance.subscribeEvents(gateway, handlers, server as any); - expect(subscribeInitEvent.calledWith(gateway, server.init)).to.be.true; - }); - it('should bind connection handler to server', () => { - instance.subscribeEvents(gateway, handlers, server as any); - expect(onSpy.calledWith('connection', getConnectionHandler())).to.be.true; - }); - it('should call "getConnectionHandler" with expected arguments', () => { - instance.subscribeEvents(gateway, handlers, server as any); - expect(getConnectionHandler.calledWith( - instance, - gateway, - handlers, - server.disconnect, - server.connection, - )).to.be.true; - }); + it('should call "next" method of server object with expected argument', () => { + instance.subscribeEvents(gateway, handlers, server as any); + expect(nextSpy.calledWith(server.server)).to.be.true; + }); + it('should call "subscribeConnectionEvent" with expected arguments', () => { + instance.subscribeEvents(gateway, handlers, server as any); + expect(subscribeConnectionEvent.calledWith(gateway, server.connection)).to + .be.true; + }); + it('should call "subscribeDisconnectEvent" with expected arguments', () => { + instance.subscribeEvents(gateway, handlers, server as any); + expect(subscribeDisconnectEvent.calledWith(gateway, server.disconnect)).to + .be.true; + }); + it('should call "subscribeInitEvent" with expected arguments', () => { + instance.subscribeEvents(gateway, handlers, server as any); + expect(subscribeInitEvent.calledWith(gateway, server.init)).to.be.true; }); - describe('getConnectionHandler', () => { - const gateway = new Test(); + it('should bind connection handler to server', () => { + instance.subscribeEvents(gateway, handlers, server as any); + expect(onSpy.calledWith('connection', getConnectionHandler())).to.be.true; + }); + it('should call "getConnectionHandler" with expected arguments', () => { + instance.subscribeEvents(gateway, handlers, server as any); + expect( + getConnectionHandler.calledWith( + instance, + gateway, + handlers, + server.disconnect, + server.connection + ) + ).to.be.true; + }); + }); + describe('getConnectionHandler', () => { + const gateway = new Test(); - let handlers, fn; - let connection, client, - nextSpy: sinon.SinonSpy, - onSpy: sinon.SinonSpy, - subscribeMessages: sinon.SinonSpy, - subscribeDisconnectEvent: sinon.SinonSpy, - subscribeConnectionEvent: sinon.SinonSpy; + let handlers, fn; + let connection, + client, + nextSpy: sinon.SinonSpy, + onSpy: sinon.SinonSpy, + subscribeMessages: sinon.SinonSpy, + subscribeDisconnectEvent: sinon.SinonSpy, + subscribeConnectionEvent: sinon.SinonSpy; - beforeEach(() => { - nextSpy = sinon.spy(); - onSpy = sinon.spy(); - subscribeMessages = sinon.spy(); - subscribeDisconnectEvent = sinon.spy(); - subscribeConnectionEvent = sinon.spy(); + beforeEach(() => { + nextSpy = sinon.spy(); + onSpy = sinon.spy(); + subscribeMessages = sinon.spy(); + subscribeDisconnectEvent = sinon.spy(); + subscribeConnectionEvent = sinon.spy(); - handlers = [ 'test' ]; - connection = { - next: nextSpy, - }; - client = { - on: onSpy, - }; - (instance as any).subscribeDisconnectEvent = subscribeDisconnectEvent; - (instance as any).subscribeConnectionEvent = subscribeConnectionEvent; - (instance as any).subscribeMessages = subscribeMessages; + handlers = ['test']; + connection = { + next: nextSpy + }; + client = { + on: onSpy + }; + (instance as any).subscribeDisconnectEvent = subscribeDisconnectEvent; + (instance as any).subscribeConnectionEvent = subscribeConnectionEvent; + (instance as any).subscribeMessages = subscribeMessages; - fn = instance.getConnectionHandler(instance, gateway, handlers, null, connection); - fn(client); - }); + fn = instance.getConnectionHandler( + instance, + gateway, + handlers, + null, + connection + ); + fn(client); + }); - it('should returns function', () => { - expect(instance.getConnectionHandler(null, null, null, null, null)).to.be.a('function'); - }); - it('should call "next" method of connection object with expected argument', () => { - expect(nextSpy.calledWith(client)).to.be.true; - }); - it('should call "subscribeMessages" with expected arguments', () => { - expect(subscribeMessages.calledWith(handlers, client, gateway)).to.be.true; - }); - it('should call "on" method of client object with expected arguments', () => { - expect(onSpy.called).to.be.true; - }); + it('should returns function', () => { + expect( + instance.getConnectionHandler(null, null, null, null, null) + ).to.be.a('function'); + }); + it('should call "next" method of connection object with expected argument', () => { + expect(nextSpy.calledWith(client)).to.be.true; + }); + it('should call "subscribeMessages" with expected arguments', () => { + expect(subscribeMessages.calledWith(handlers, client, gateway)).to.be + .true; + }); + it('should call "on" method of client object with expected arguments', () => { + expect(onSpy.called).to.be.true; }); - describe('subscribeInitEvent', () => { - const gateway = new Test(); - let event, subscribe: sinon.SinonSpy; + }); + describe('subscribeInitEvent', () => { + const gateway = new Test(); + let event, subscribe: sinon.SinonSpy; - beforeEach(() => { - subscribe = sinon.spy(); - event = { subscribe }; - }); - it('should not call subscribe method when "afterInit" method not exists', () => { - instance.subscribeInitEvent(gateway, event); - expect(subscribe.called).to.be.false; - }); - it('should call subscribe method of event object with expected arguments when "afterInit" exists', () => { - (gateway as any).afterInit = () => {}; - instance.subscribeInitEvent(gateway, event); - expect(subscribe.called).to.be.true; - }); + beforeEach(() => { + subscribe = sinon.spy(); + event = { subscribe }; }); - describe('subscribeConnectionEvent', () => { - const gateway = new Test(); - let event, subscribe: sinon.SinonSpy; + it('should not call subscribe method when "afterInit" method not exists', () => { + instance.subscribeInitEvent(gateway, event); + expect(subscribe.called).to.be.false; + }); + it('should call subscribe method of event object with expected arguments when "afterInit" exists', () => { + (gateway as any).afterInit = () => {}; + instance.subscribeInitEvent(gateway, event); + expect(subscribe.called).to.be.true; + }); + }); + describe('subscribeConnectionEvent', () => { + const gateway = new Test(); + let event, subscribe: sinon.SinonSpy; - beforeEach(() => { - subscribe = sinon.spy(); - event = { subscribe }; - }); - it('should not call subscribe method when "handleConnection" method not exists', () => { - instance.subscribeConnectionEvent(gateway, event); - expect(subscribe.called).to.be.false; - }); - it('should call subscribe method of event object with expected arguments when "handleConnection" exists', () => { - (gateway as any).handleConnection = () => {}; - instance.subscribeConnectionEvent(gateway, event); - expect(subscribe.called).to.be.true; - }); + beforeEach(() => { + subscribe = sinon.spy(); + event = { subscribe }; + }); + it('should not call subscribe method when "handleConnection" method not exists', () => { + instance.subscribeConnectionEvent(gateway, event); + expect(subscribe.called).to.be.false; + }); + it('should call subscribe method of event object with expected arguments when "handleConnection" exists', () => { + (gateway as any).handleConnection = () => {}; + instance.subscribeConnectionEvent(gateway, event); + expect(subscribe.called).to.be.true; }); - describe('subscribeDisconnectEvent', () => { - const gateway = new Test(); - let event, subscribe: sinon.SinonSpy; + }); + describe('subscribeDisconnectEvent', () => { + const gateway = new Test(); + let event, subscribe: sinon.SinonSpy; - beforeEach(() => { - subscribe = sinon.spy(); - event = { subscribe }; - }); - it('should not call subscribe method when "handleDisconnect" method not exists', () => { - instance.subscribeDisconnectEvent(gateway, event); - expect(subscribe.called).to.be.false; - }); - it('should call subscribe method of event object with expected arguments when "handleDisconnect" exists', () => { - (gateway as any).handleDisconnect = () => {}; - instance.subscribeDisconnectEvent(gateway, event); - expect(subscribe.called).to.be.true; - }); + beforeEach(() => { + subscribe = sinon.spy(); + event = { subscribe }; }); - describe('subscribeMessages', () => { - const gateway = new Test(); + it('should not call subscribe method when "handleDisconnect" method not exists', () => { + instance.subscribeDisconnectEvent(gateway, event); + expect(subscribe.called).to.be.false; + }); + it('should call subscribe method of event object with expected arguments when "handleDisconnect" exists', () => { + (gateway as any).handleDisconnect = () => {}; + instance.subscribeDisconnectEvent(gateway, event); + expect(subscribe.called).to.be.true; + }); + }); + describe('subscribeMessages', () => { + const gateway = new Test(); - let client, handlers, - onSpy: sinon.SinonSpy; + let client, handlers, onSpy: sinon.SinonSpy; - beforeEach(() => { - onSpy = sinon.spy(); - client = { on: onSpy, off: onSpy }; + beforeEach(() => { + onSpy = sinon.spy(); + client = { on: onSpy, off: onSpy }; - handlers = [ - { message: 'test', callback: { bind: () => 'testCallback' }}, - { message: 'test2', callback: { bind: () => 'testCallback2' }}, - ]; - }); - it('should bind each handler to client', () => { - instance.subscribeMessages(handlers, client, gateway); - expect(onSpy.calledTwice).to.be.true; - }); + handlers = [ + { message: 'test', callback: { bind: () => 'testCallback' } }, + { message: 'test2', callback: { bind: () => 'testCallback2' } } + ]; + }); + it('should bind each handler to client', () => { + instance.subscribeMessages(handlers, client, gateway); + expect(onSpy.calledTwice).to.be.true; }); - describe('pickResult', () => { - describe('when defferedResult contains value which', () => { - describe('is a Promise', () => { - it('should returns Promise', async () => { - const value = 100; - expect( - await (await instance.pickResult(Promise.resolve(Promise.resolve(value)))).toPromise() - ).to.be.eq(100); - }); - }); + }); + describe('pickResult', () => { + describe('when defferedResult contains value which', () => { + describe('is a Promise', () => { + it('should returns Promise', async () => { + const value = 100; + expect( + await (await instance.pickResult( + Promise.resolve(Promise.resolve(value)) + )).toPromise() + ).to.be.eq(100); + }); + }); - describe('is an Observable', () => { - it('should returns Promise', async () => { - const value = 100; - expect( - await (await instance.pickResult(Promise.resolve(Observable.of(value)))).toPromise() - ).to.be.eq(100); - }); - }); + describe('is an Observable', () => { + it('should returns Promise', async () => { + const value = 100; + expect( + await (await instance.pickResult( + Promise.resolve(Observable.of(value)) + )).toPromise() + ).to.be.eq(100); + }); + }); - describe('is a value', () => { - it('should returns Promise', async () => { - const value = 100; - expect( - await (await instance.pickResult(Promise.resolve(value))).toPromise() - ).to.be.eq(100); - }); - }); + describe('is a value', () => { + it('should returns Promise', async () => { + const value = 100; + expect( + await (await instance.pickResult( + Promise.resolve(value) + )).toPromise() + ).to.be.eq(100); }); + }); }); -}); \ No newline at end of file + }); +}); diff --git a/src/websockets/utils/gateway-server.decorator.ts b/src/websockets/utils/gateway-server.decorator.ts index dd7f34b0fd1..f68cebcc7dc 100644 --- a/src/websockets/utils/gateway-server.decorator.ts +++ b/src/websockets/utils/gateway-server.decorator.ts @@ -5,8 +5,8 @@ import { GATEWAY_SERVER_METADATA } from '../constants'; * Attaches the native Web Socket Server to the given property. */ export const WebSocketServer = (): PropertyDecorator => { - return (target: object, propertyKey: string | symbol) => { - Reflect.set(target, propertyKey, null); - Reflect.defineMetadata(GATEWAY_SERVER_METADATA, true, target, propertyKey); - }; -}; \ No newline at end of file + return (target: object, propertyKey: string | symbol) => { + Reflect.set(target, propertyKey, null); + Reflect.defineMetadata(GATEWAY_SERVER_METADATA, true, target, propertyKey); + }; +}; diff --git a/src/websockets/utils/index.ts b/src/websockets/utils/index.ts index 86b177c6a84..367ddd05d76 100644 --- a/src/websockets/utils/index.ts +++ b/src/websockets/utils/index.ts @@ -1,3 +1,3 @@ export * from './socket-gateway.decorator'; export * from './subscribe-message.decorator'; -export * from './gateway-server.decorator'; \ No newline at end of file +export * from './gateway-server.decorator'; diff --git a/src/websockets/utils/socket-gateway.decorator.ts b/src/websockets/utils/socket-gateway.decorator.ts index dde2de006bc..054ee89e1ae 100644 --- a/src/websockets/utils/socket-gateway.decorator.ts +++ b/src/websockets/utils/socket-gateway.decorator.ts @@ -1,20 +1,27 @@ import 'reflect-metadata'; import { GatewayMetadata } from '../interfaces'; -import { PORT_METADATA, NAMESPACE_METADATA, GATEWAY_METADATA, GATEWAY_MIDDLEWARES } from '../constants'; +import { + PORT_METADATA, + NAMESPACE_METADATA, + GATEWAY_METADATA, + GATEWAY_MIDDLEWARES +} from '../constants'; /** * Defines the Gateway. The gateway can inject dependencies through constructor. * Those dependencies should belongs to the same module. Gateway is listening on the specified port. */ -export const WebSocketGateway = (metadataOrPort?: GatewayMetadata | number): ClassDecorator => { - if (Number.isInteger(metadataOrPort as number)) { - metadataOrPort = { port: metadataOrPort } as any; - } - const metadata: GatewayMetadata = metadataOrPort as GatewayMetadata || {}; - return (target: object) => { - Reflect.defineMetadata(GATEWAY_METADATA, true, target); - Reflect.defineMetadata(NAMESPACE_METADATA, metadata.namespace, target); - Reflect.defineMetadata(PORT_METADATA, metadata.port, target); - Reflect.defineMetadata(GATEWAY_MIDDLEWARES, metadata.middlewares, target); - }; -}; \ No newline at end of file +export const WebSocketGateway = ( + metadataOrPort?: GatewayMetadata | number +): ClassDecorator => { + if (Number.isInteger(metadataOrPort as number)) { + metadataOrPort = { port: metadataOrPort } as any; + } + const metadata: GatewayMetadata = (metadataOrPort as GatewayMetadata) || {}; + return (target: object) => { + Reflect.defineMetadata(GATEWAY_METADATA, true, target); + Reflect.defineMetadata(NAMESPACE_METADATA, metadata.namespace, target); + Reflect.defineMetadata(PORT_METADATA, metadata.port, target); + Reflect.defineMetadata(GATEWAY_MIDDLEWARES, metadata.middlewares, target); + }; +}; diff --git a/src/websockets/utils/subscribe-message.decorator.ts b/src/websockets/utils/subscribe-message.decorator.ts index ab9aae71cf1..ce6083dd055 100644 --- a/src/websockets/utils/subscribe-message.decorator.ts +++ b/src/websockets/utils/subscribe-message.decorator.ts @@ -5,13 +5,15 @@ import { isObject, isUndefined } from '@nestjs/common/utils/shared.utils'; /** * Subscribes to the messages, which fulfils chosen pattern. */ -export const SubscribeMessage = (message?: { value: string } | string): MethodDecorator => { - let metadata = isObject(message) ? message.value : message; - metadata = isUndefined(metadata) ? '' : metadata; +export const SubscribeMessage = ( + message?: { value: string } | string +): MethodDecorator => { + let metadata = isObject(message) ? message.value : message; + metadata = isUndefined(metadata) ? '' : metadata; - return (target, key, descriptor: PropertyDescriptor) => { - Reflect.defineMetadata(MESSAGE_MAPPING_METADATA, true, descriptor.value); - Reflect.defineMetadata(MESSAGE_METADATA, metadata, descriptor.value); - return descriptor; - }; -}; \ No newline at end of file + return (target, key, descriptor: PropertyDescriptor) => { + Reflect.defineMetadata(MESSAGE_MAPPING_METADATA, true, descriptor.value); + Reflect.defineMetadata(MESSAGE_METADATA, metadata, descriptor.value); + return descriptor; + }; +}; diff --git a/src/websockets/web-sockets-controller.ts b/src/websockets/web-sockets-controller.ts index 508122ac725..e03c0cca5ec 100644 --- a/src/websockets/web-sockets-controller.ts +++ b/src/websockets/web-sockets-controller.ts @@ -3,7 +3,10 @@ import { NestGateway } from './interfaces/nest-gateway.interface'; import { Injectable } from '@nestjs/common/interfaces/injectable.interface'; import { ObservableSocketServer } from './interfaces/observable-socket-server.interface'; import { InvalidSocketPortException } from './exceptions/invalid-socket-port.exception'; -import { GatewayMetadataExplorer, MessageMappingProperties } from './gateway-metadata-explorer'; +import { + GatewayMetadataExplorer, + MessageMappingProperties +} from './gateway-metadata-explorer'; import { Subject } from 'rxjs/Subject'; import { SocketServerProvider } from './socket-server-provider'; import { NAMESPACE_METADATA, PORT_METADATA } from './constants'; @@ -19,124 +22,153 @@ import 'rxjs/add/observable/of'; import 'rxjs/add/operator/switchMap'; export class WebSocketsController { - private readonly metadataExplorer = new GatewayMetadataExplorer(new MetadataScanner()); - private readonly middlewaresInjector: MiddlewaresInjector; - - constructor( - private readonly socketServerProvider: SocketServerProvider, - private readonly container: NestContainer, - private readonly config: ApplicationConfig, - private readonly contextCreator: WsContextCreator, - ) { - this.middlewaresInjector = new MiddlewaresInjector(container, config); + private readonly metadataExplorer = new GatewayMetadataExplorer( + new MetadataScanner() + ); + private readonly middlewaresInjector: MiddlewaresInjector; + + constructor( + private readonly socketServerProvider: SocketServerProvider, + private readonly container: NestContainer, + private readonly config: ApplicationConfig, + private readonly contextCreator: WsContextCreator + ) { + this.middlewaresInjector = new MiddlewaresInjector(container, config); + } + + public hookGatewayIntoServer( + instance: NestGateway, + metatype: Metatype, + module: string + ) { + const namespace = Reflect.getMetadata(NAMESPACE_METADATA, metatype) || ''; + const port = Reflect.getMetadata(PORT_METADATA, metatype) || 0; + + if (!Number.isInteger(port)) { + throw new InvalidSocketPortException(port, metatype); } - - public hookGatewayIntoServer(instance: NestGateway, metatype: Metatype, module: string) { - const namespace = Reflect.getMetadata(NAMESPACE_METADATA, metatype) || ''; - const port = Reflect.getMetadata(PORT_METADATA, metatype) || 0; - - if (!Number.isInteger(port)) { - throw new InvalidSocketPortException(port, metatype); - } - this.subscribeObservableServer(instance, namespace, port, module); - } - - public subscribeObservableServer(instance: NestGateway, namespace: string, port: number, module: string) { - const plainMessageHandlers = this.metadataExplorer.explore(instance); - const messageHandlers = plainMessageHandlers.map(({ callback, message }) => ({ - message, - callback: this.contextCreator.create(instance, callback, module), - })); - const observableServer = this.socketServerProvider.scanForSocketServer(namespace, port); - - this.injectMiddlewares(observableServer, instance, module); - this.hookServerToProperties(instance, observableServer.server); - this.subscribeEvents(instance, messageHandlers, observableServer); + this.subscribeObservableServer(instance, namespace, port, module); + } + + public subscribeObservableServer( + instance: NestGateway, + namespace: string, + port: number, + module: string + ) { + const plainMessageHandlers = this.metadataExplorer.explore(instance); + const messageHandlers = plainMessageHandlers.map( + ({ callback, message }) => ({ + message, + callback: this.contextCreator.create(instance, callback, module) + }) + ); + const observableServer = this.socketServerProvider.scanForSocketServer( + namespace, + port + ); + + this.injectMiddlewares(observableServer, instance, module); + this.hookServerToProperties(instance, observableServer.server); + this.subscribeEvents(instance, messageHandlers, observableServer); + } + + public injectMiddlewares({ server }, instance: NestGateway, module: string) { + this.middlewaresInjector.inject(server, instance, module); + } + + public subscribeEvents( + instance: NestGateway, + messageHandlers: MessageMappingProperties[], + observableServer: ObservableSocketServer + ) { + const { init, disconnect, connection, server } = observableServer; + const adapter = this.config.getIoAdapter(); + + this.subscribeInitEvent(instance, init); + this.subscribeConnectionEvent(instance, connection); + this.subscribeDisconnectEvent(instance, disconnect); + init.next(server); + + const handler = this.getConnectionHandler( + this, + instance, + messageHandlers, + disconnect, + connection + ); + adapter.bindClientConnect(server, handler); + } + + public getConnectionHandler( + context: WebSocketsController, + instance: NestGateway, + messageHandlers: MessageMappingProperties[], + disconnect: Subject, + connection: Subject + ) { + const adapter = this.config.getIoAdapter(); + return client => { + connection.next(client); + context.subscribeMessages(messageHandlers, client, instance); + + const disconnectHook = adapter.bindClientDisconnect; + disconnectHook && + disconnectHook.call(adapter, client, socket => disconnect.next(client)); + }; + } + + public subscribeInitEvent(instance: NestGateway, event: Subject) { + if (instance.afterInit) { + event.subscribe(instance.afterInit.bind(instance)); } + } - public injectMiddlewares({ server }, instance: NestGateway, module: string) { - this.middlewaresInjector.inject(server, instance, module); + public subscribeConnectionEvent(instance: NestGateway, event: Subject) { + if (instance.handleConnection) { + event.subscribe(instance.handleConnection.bind(instance)); } + } - public subscribeEvents( - instance: NestGateway, - messageHandlers: MessageMappingProperties[], - observableServer: ObservableSocketServer, - ) { - const { init, disconnect, connection, server } = observableServer; - const adapter = this.config.getIoAdapter(); - - this.subscribeInitEvent(instance, init); - this.subscribeConnectionEvent(instance, connection); - this.subscribeDisconnectEvent(instance, disconnect); - init.next(server); - - const handler = this.getConnectionHandler(this, instance, messageHandlers, disconnect, connection); - adapter.bindClientConnect(server, handler); + public subscribeDisconnectEvent(instance: NestGateway, event: Subject) { + if (instance.handleDisconnect) { + event.subscribe(instance.handleDisconnect.bind(instance)); } - - public getConnectionHandler( - context: WebSocketsController, - instance: NestGateway, - messageHandlers: MessageMappingProperties[], - disconnect: Subject, - connection: Subject, - ) { - const adapter = this.config.getIoAdapter(); - return (client) => { - connection.next(client); - context.subscribeMessages(messageHandlers, client, instance); - - const disconnectHook = adapter.bindClientDisconnect; - disconnectHook && disconnectHook.call(adapter, client, socket => disconnect.next(client)); - }; - } - - public subscribeInitEvent(instance: NestGateway, event: Subject) { - if (instance.afterInit) { - event.subscribe(instance.afterInit.bind(instance)); - } + } + + public subscribeMessages( + messageHandlers: MessageMappingProperties[], + client, + instance: NestGateway + ) { + const adapter = this.config.getIoAdapter(); + const handlers = messageHandlers.map(({ callback, message }) => ({ + message, + callback: callback.bind(instance, client) + })); + adapter.bindMessageHandlers(client, handlers, data => + Observable.fromPromise(this.pickResult(data)).switchMap(stream => stream) + ); + } + + public async pickResult( + defferedResult: Promise + ): Promise> { + const result = await defferedResult; + if (result instanceof Observable) { + return result; } - - public subscribeConnectionEvent(instance: NestGateway, event: Subject) { - if (instance.handleConnection) { - event.subscribe(instance.handleConnection.bind(instance)); - } + if (result instanceof Promise) { + return Observable.fromPromise(result); } - - public subscribeDisconnectEvent(instance: NestGateway, event: Subject) { - if (instance.handleDisconnect) { - event.subscribe(instance.handleDisconnect.bind(instance)); - } - } - - public subscribeMessages(messageHandlers: MessageMappingProperties[], client, instance: NestGateway) { - const adapter = this.config.getIoAdapter(); - const handlers = messageHandlers.map(({ callback, message }) => ({ - message, - callback: callback.bind(instance, client), - })); - adapter.bindMessageHandlers( - client, handlers, - (data) => Observable.fromPromise(this.pickResult(data)) - .switchMap((stream) => stream), - ); - } - - public async pickResult(defferedResult: Promise): Promise> { - const result = await defferedResult; - if (result instanceof Observable) { - return result; - } - if (result instanceof Promise) { - return Observable.fromPromise(result); - } - return Observable.of(result); - } - - private hookServerToProperties(instance: NestGateway, server) { - for (const propertyKey of this.metadataExplorer.scanForServerHooks(instance)) { - Reflect.set(instance, propertyKey, server); - } + return Observable.of(result); + } + + private hookServerToProperties(instance: NestGateway, server) { + for (const propertyKey of this.metadataExplorer.scanForServerHooks( + instance + )) { + Reflect.set(instance, propertyKey, server); } -} \ No newline at end of file + } +}