@tsed/common 7.0.0-alpha.1 → 7.0.0-beta.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (409) hide show
  1. package/lib/cjs/builder/PlatformBuilder.js +275 -0
  2. package/lib/cjs/builder/PlatformBuilder.js.map +1 -0
  3. package/lib/cjs/builder/PlatformControllerBuilder.js +85 -0
  4. package/lib/cjs/builder/PlatformControllerBuilder.js.map +1 -0
  5. package/lib/cjs/config/index.js +7 -0
  6. package/lib/cjs/config/index.js.map +1 -0
  7. package/lib/cjs/config/interfaces/ConverterSettings.js +3 -0
  8. package/lib/cjs/config/interfaces/ConverterSettings.js.map +1 -0
  9. package/lib/cjs/config/interfaces/EndpointDirectoriesSettings.js +3 -0
  10. package/lib/cjs/config/interfaces/EndpointDirectoriesSettings.js.map +1 -0
  11. package/lib/cjs/config/interfaces/PlatformLoggerSettings.js +3 -0
  12. package/lib/cjs/config/interfaces/PlatformLoggerSettings.js.map +1 -0
  13. package/lib/cjs/config/interfaces/PlatformMulterSettings.js +3 -0
  14. package/lib/cjs/config/interfaces/PlatformMulterSettings.js.map +1 -0
  15. package/lib/cjs/config/interfaces/PlatformStaticsSettings.js +3 -0
  16. package/lib/cjs/config/interfaces/PlatformStaticsSettings.js.map +1 -0
  17. package/lib/cjs/config/interfaces/index.js +8 -0
  18. package/lib/cjs/config/interfaces/index.js.map +1 -0
  19. package/lib/cjs/config/services/PlatformConfiguration.js +181 -0
  20. package/lib/cjs/config/services/PlatformConfiguration.js.map +1 -0
  21. package/lib/cjs/constants/routerOptions.js +5 -0
  22. package/lib/cjs/constants/routerOptions.js.map +1 -0
  23. package/lib/cjs/decorators/httpServer.js +32 -0
  24. package/lib/cjs/decorators/httpServer.js.map +1 -0
  25. package/lib/cjs/decorators/httpsServer.js +32 -0
  26. package/lib/cjs/decorators/httpsServer.js.map +1 -0
  27. package/lib/cjs/decorators/index.js +26 -0
  28. package/lib/cjs/decorators/index.js.map +1 -0
  29. package/lib/cjs/decorators/method/acceptMime.js +28 -0
  30. package/lib/cjs/decorators/method/acceptMime.js.map +1 -0
  31. package/lib/cjs/decorators/multer/index.js +7 -0
  32. package/lib/cjs/decorators/multer/index.js.map +1 -0
  33. package/lib/cjs/decorators/multer/multerFileSize.js +35 -0
  34. package/lib/cjs/decorators/multer/multerFileSize.js.map +1 -0
  35. package/lib/cjs/decorators/multer/multerOptions.js +52 -0
  36. package/lib/cjs/decorators/multer/multerOptions.js.map +1 -0
  37. package/lib/cjs/decorators/multer/multipartFile.js +78 -0
  38. package/lib/cjs/decorators/multer/multipartFile.js.map +1 -0
  39. package/lib/cjs/decorators/params/error.js +20 -0
  40. package/lib/cjs/decorators/params/error.js.map +1 -0
  41. package/lib/cjs/decorators/params/next.js +21 -0
  42. package/lib/cjs/decorators/params/next.js.map +1 -0
  43. package/lib/cjs/decorators/params/request.js +39 -0
  44. package/lib/cjs/decorators/params/request.js.map +1 -0
  45. package/lib/cjs/decorators/params/response.js +33 -0
  46. package/lib/cjs/decorators/params/response.js.map +1 -0
  47. package/lib/cjs/domain/AnyToPromiseWithCtx.js +27 -0
  48. package/lib/cjs/domain/AnyToPromiseWithCtx.js.map +1 -0
  49. package/lib/cjs/domain/ControllerProvider.js +51 -0
  50. package/lib/cjs/domain/ControllerProvider.js.map +1 -0
  51. package/lib/cjs/domain/EndpointMetadata.js +70 -0
  52. package/lib/cjs/domain/EndpointMetadata.js.map +1 -0
  53. package/lib/cjs/domain/HandlerMetadata.js +57 -0
  54. package/lib/cjs/domain/HandlerMetadata.js.map +1 -0
  55. package/lib/cjs/domain/PlatformContext.js +92 -0
  56. package/lib/cjs/domain/PlatformContext.js.map +1 -0
  57. package/lib/cjs/domain/PlatformRouteDetails.js +24 -0
  58. package/lib/cjs/domain/PlatformRouteDetails.js.map +1 -0
  59. package/lib/cjs/domain/index.js +10 -0
  60. package/lib/cjs/domain/index.js.map +1 -0
  61. package/lib/cjs/index.js +34 -0
  62. package/lib/cjs/index.js.map +1 -0
  63. package/lib/cjs/interfaces/AfterInit.js +3 -0
  64. package/lib/cjs/interfaces/AfterInit.js.map +1 -0
  65. package/lib/cjs/interfaces/AfterListen.js +3 -0
  66. package/lib/cjs/interfaces/AfterListen.js.map +1 -0
  67. package/lib/cjs/interfaces/AfterRoutesInit.js +3 -0
  68. package/lib/cjs/interfaces/AfterRoutesInit.js.map +1 -0
  69. package/lib/cjs/interfaces/BeforeInit.js +3 -0
  70. package/lib/cjs/interfaces/BeforeInit.js.map +1 -0
  71. package/lib/cjs/interfaces/BeforeListen.js +3 -0
  72. package/lib/cjs/interfaces/BeforeListen.js.map +1 -0
  73. package/lib/cjs/interfaces/BeforeRoutesInit.js +3 -0
  74. package/lib/cjs/interfaces/BeforeRoutesInit.js.map +1 -0
  75. package/lib/cjs/interfaces/HandlerType.js +17 -0
  76. package/lib/cjs/interfaces/HandlerType.js.map +1 -0
  77. package/lib/cjs/interfaces/IncomingEvent.js +3 -0
  78. package/lib/cjs/interfaces/IncomingEvent.js.map +1 -0
  79. package/lib/cjs/interfaces/OnReady.js +3 -0
  80. package/lib/cjs/interfaces/OnReady.js.map +1 -0
  81. package/lib/cjs/interfaces/OnRequest.js +3 -0
  82. package/lib/cjs/interfaces/OnRequest.js.map +1 -0
  83. package/lib/cjs/interfaces/OnResponse.js +3 -0
  84. package/lib/cjs/interfaces/OnResponse.js.map +1 -0
  85. package/lib/cjs/interfaces/OnRoutesInit.js +3 -0
  86. package/lib/cjs/interfaces/OnRoutesInit.js.map +1 -0
  87. package/lib/cjs/interfaces/PathType.js +3 -0
  88. package/lib/cjs/interfaces/PathType.js.map +1 -0
  89. package/lib/cjs/interfaces/PlatformAdapter.js +3 -0
  90. package/lib/cjs/interfaces/PlatformAdapter.js.map +1 -0
  91. package/lib/cjs/interfaces/PlatformRouteOptions.js +3 -0
  92. package/lib/cjs/interfaces/PlatformRouteOptions.js.map +1 -0
  93. package/lib/cjs/interfaces/ResponseErrorObject.js +3 -0
  94. package/lib/cjs/interfaces/ResponseErrorObject.js.map +1 -0
  95. package/lib/cjs/interfaces/Route.js +3 -0
  96. package/lib/cjs/interfaces/Route.js.map +1 -0
  97. package/lib/cjs/interfaces/index.js +21 -0
  98. package/lib/cjs/interfaces/index.js.map +1 -0
  99. package/lib/cjs/middlewares/PlatformAcceptMimesMiddleware.js +37 -0
  100. package/lib/cjs/middlewares/PlatformAcceptMimesMiddleware.js.map +1 -0
  101. package/lib/cjs/middlewares/PlatformMulterMiddleware.js +55 -0
  102. package/lib/cjs/middlewares/PlatformMulterMiddleware.js.map +1 -0
  103. package/lib/cjs/middlewares/__mock__/FakeCtrl.js +12 -0
  104. package/lib/cjs/middlewares/__mock__/FakeCtrl.js.map +1 -0
  105. package/lib/cjs/middlewares/bindEndpointMiddleware.js +13 -0
  106. package/lib/cjs/middlewares/bindEndpointMiddleware.js.map +1 -0
  107. package/lib/cjs/middlewares/index.js +7 -0
  108. package/lib/cjs/middlewares/index.js.map +1 -0
  109. package/lib/cjs/services/FakeRawDriver.js +26 -0
  110. package/lib/cjs/services/FakeRawDriver.js.map +1 -0
  111. package/lib/cjs/services/Platform.js +107 -0
  112. package/lib/cjs/services/Platform.js.map +1 -0
  113. package/lib/cjs/services/PlatformApplication.js +34 -0
  114. package/lib/cjs/services/PlatformApplication.js.map +1 -0
  115. package/lib/cjs/services/PlatformHandler.js +233 -0
  116. package/lib/cjs/services/PlatformHandler.js.map +1 -0
  117. package/lib/cjs/services/PlatformMiddlewaresChain.js +34 -0
  118. package/lib/cjs/services/PlatformMiddlewaresChain.js.map +1 -0
  119. package/lib/cjs/services/PlatformRequest.js +138 -0
  120. package/lib/cjs/services/PlatformRequest.js.map +1 -0
  121. package/lib/cjs/services/PlatformResponse.js +271 -0
  122. package/lib/cjs/services/PlatformResponse.js.map +1 -0
  123. package/lib/cjs/services/PlatformRouter.js +126 -0
  124. package/lib/cjs/services/PlatformRouter.js.map +1 -0
  125. package/lib/cjs/services/PlatformTest.js +166 -0
  126. package/lib/cjs/services/PlatformTest.js.map +1 -0
  127. package/lib/cjs/services/index.js +12 -0
  128. package/lib/cjs/services/index.js.map +1 -0
  129. package/lib/cjs/utils/createContext.js +38 -0
  130. package/lib/cjs/utils/createContext.js.map +1 -0
  131. package/lib/cjs/utils/createHandlerMetadata.js +49 -0
  132. package/lib/cjs/utils/createHandlerMetadata.js.map +1 -0
  133. package/lib/cjs/utils/createHttpServer.js +34 -0
  134. package/lib/cjs/utils/createHttpServer.js.map +1 -0
  135. package/lib/cjs/utils/createHttpsServer.js +34 -0
  136. package/lib/cjs/utils/createHttpsServer.js.map +1 -0
  137. package/lib/cjs/utils/createInjector.js +38 -0
  138. package/lib/cjs/utils/createInjector.js.map +1 -0
  139. package/lib/cjs/utils/getConfiguration.js +42 -0
  140. package/lib/cjs/utils/getConfiguration.js.map +1 -0
  141. package/lib/cjs/utils/getStaticsOptions.js +21 -0
  142. package/lib/cjs/utils/getStaticsOptions.js.map +1 -0
  143. package/lib/cjs/utils/index.js +11 -0
  144. package/lib/cjs/utils/index.js.map +1 -0
  145. package/lib/cjs/utils/listenServer.js +21 -0
  146. package/lib/cjs/utils/listenServer.js.map +1 -0
  147. package/lib/cjs/utils/mapReturnedResponse.js +15 -0
  148. package/lib/cjs/utils/mapReturnedResponse.js.map +1 -0
  149. package/lib/cjs/utils/printRoutes.js +36 -0
  150. package/lib/cjs/utils/printRoutes.js.map +1 -0
  151. package/lib/cjs/utils/setResponseHeaders.js +35 -0
  152. package/lib/cjs/utils/setResponseHeaders.js.map +1 -0
  153. package/lib/cjs/utils/useCtxHandler.js +15 -0
  154. package/lib/cjs/utils/useCtxHandler.js.map +1 -0
  155. package/lib/esm/builder/PlatformBuilder.js +271 -0
  156. package/lib/esm/builder/PlatformBuilder.js.map +1 -0
  157. package/lib/esm/builder/PlatformControllerBuilder.js +79 -0
  158. package/lib/esm/builder/PlatformControllerBuilder.js.map +1 -0
  159. package/lib/esm/config/index.js +4 -0
  160. package/lib/esm/config/index.js.map +1 -0
  161. package/lib/esm/config/interfaces/ConverterSettings.js +2 -0
  162. package/lib/esm/config/interfaces/ConverterSettings.js.map +1 -0
  163. package/lib/esm/config/interfaces/EndpointDirectoriesSettings.js +2 -0
  164. package/lib/esm/config/interfaces/EndpointDirectoriesSettings.js.map +1 -0
  165. package/lib/esm/config/interfaces/PlatformLoggerSettings.js +2 -0
  166. package/lib/esm/config/interfaces/PlatformLoggerSettings.js.map +1 -0
  167. package/lib/esm/config/interfaces/PlatformMulterSettings.js +2 -0
  168. package/lib/esm/config/interfaces/PlatformMulterSettings.js.map +1 -0
  169. package/lib/esm/config/interfaces/PlatformStaticsSettings.js +2 -0
  170. package/lib/esm/config/interfaces/PlatformStaticsSettings.js.map +1 -0
  171. package/lib/esm/config/interfaces/index.js +5 -0
  172. package/lib/esm/config/interfaces/index.js.map +1 -0
  173. package/lib/esm/config/services/PlatformConfiguration.js +178 -0
  174. package/lib/esm/config/services/PlatformConfiguration.js.map +1 -0
  175. package/lib/esm/constants/routerOptions.js +2 -0
  176. package/lib/esm/constants/routerOptions.js.map +1 -0
  177. package/lib/esm/decorators/httpServer.js +28 -0
  178. package/lib/esm/decorators/httpServer.js.map +1 -0
  179. package/lib/esm/decorators/httpsServer.js +28 -0
  180. package/lib/esm/decorators/httpsServer.js.map +1 -0
  181. package/lib/esm/decorators/index.js +14 -0
  182. package/lib/esm/decorators/index.js.map +1 -0
  183. package/lib/esm/decorators/method/acceptMime.js +24 -0
  184. package/lib/esm/decorators/method/acceptMime.js.map +1 -0
  185. package/lib/esm/decorators/multer/index.js +4 -0
  186. package/lib/esm/decorators/multer/index.js.map +1 -0
  187. package/lib/esm/decorators/multer/multerFileSize.js +31 -0
  188. package/lib/esm/decorators/multer/multerFileSize.js.map +1 -0
  189. package/lib/esm/decorators/multer/multerOptions.js +48 -0
  190. package/lib/esm/decorators/multer/multerOptions.js.map +1 -0
  191. package/lib/esm/decorators/multer/multipartFile.js +74 -0
  192. package/lib/esm/decorators/multer/multipartFile.js.map +1 -0
  193. package/lib/esm/decorators/params/error.js +16 -0
  194. package/lib/esm/decorators/params/error.js.map +1 -0
  195. package/lib/esm/decorators/params/next.js +17 -0
  196. package/lib/esm/decorators/params/next.js.map +1 -0
  197. package/lib/esm/decorators/params/request.js +34 -0
  198. package/lib/esm/decorators/params/request.js.map +1 -0
  199. package/lib/esm/decorators/params/response.js +28 -0
  200. package/lib/esm/decorators/params/response.js.map +1 -0
  201. package/lib/esm/domain/AnyToPromiseWithCtx.js +23 -0
  202. package/lib/esm/domain/AnyToPromiseWithCtx.js.map +1 -0
  203. package/lib/esm/domain/ControllerProvider.js +47 -0
  204. package/lib/esm/domain/ControllerProvider.js.map +1 -0
  205. package/lib/esm/domain/EndpointMetadata.js +67 -0
  206. package/lib/esm/domain/EndpointMetadata.js.map +1 -0
  207. package/lib/esm/domain/HandlerMetadata.js +53 -0
  208. package/lib/esm/domain/HandlerMetadata.js.map +1 -0
  209. package/lib/esm/domain/PlatformContext.js +88 -0
  210. package/lib/esm/domain/PlatformContext.js.map +1 -0
  211. package/lib/esm/domain/PlatformRouteDetails.js +20 -0
  212. package/lib/esm/domain/PlatformRouteDetails.js.map +1 -0
  213. package/lib/esm/domain/index.js +7 -0
  214. package/lib/esm/domain/index.js.map +1 -0
  215. package/lib/esm/index.js +28 -0
  216. package/lib/esm/index.js.map +1 -0
  217. package/lib/esm/interfaces/AfterInit.js +2 -0
  218. package/lib/esm/interfaces/AfterInit.js.map +1 -0
  219. package/lib/esm/interfaces/AfterListen.js +2 -0
  220. package/lib/esm/interfaces/AfterListen.js.map +1 -0
  221. package/lib/esm/interfaces/AfterRoutesInit.js +2 -0
  222. package/lib/esm/interfaces/AfterRoutesInit.js.map +1 -0
  223. package/lib/esm/interfaces/BeforeInit.js +2 -0
  224. package/lib/esm/interfaces/BeforeInit.js.map +1 -0
  225. package/lib/esm/interfaces/BeforeListen.js +2 -0
  226. package/lib/esm/interfaces/BeforeListen.js.map +1 -0
  227. package/lib/esm/interfaces/BeforeRoutesInit.js +2 -0
  228. package/lib/esm/interfaces/BeforeRoutesInit.js.map +1 -0
  229. package/lib/esm/interfaces/HandlerType.js +14 -0
  230. package/lib/esm/interfaces/HandlerType.js.map +1 -0
  231. package/lib/esm/interfaces/IncomingEvent.js +2 -0
  232. package/lib/esm/interfaces/IncomingEvent.js.map +1 -0
  233. package/lib/esm/interfaces/OnReady.js +2 -0
  234. package/lib/esm/interfaces/OnReady.js.map +1 -0
  235. package/lib/esm/interfaces/OnRequest.js +2 -0
  236. package/lib/esm/interfaces/OnRequest.js.map +1 -0
  237. package/lib/esm/interfaces/OnResponse.js +2 -0
  238. package/lib/esm/interfaces/OnResponse.js.map +1 -0
  239. package/lib/esm/interfaces/OnRoutesInit.js +2 -0
  240. package/lib/esm/interfaces/OnRoutesInit.js.map +1 -0
  241. package/lib/esm/interfaces/PathType.js +2 -0
  242. package/lib/esm/interfaces/PathType.js.map +1 -0
  243. package/lib/esm/interfaces/PlatformAdapter.js +2 -0
  244. package/lib/esm/interfaces/PlatformAdapter.js.map +1 -0
  245. package/lib/esm/interfaces/PlatformRouteOptions.js +2 -0
  246. package/lib/esm/interfaces/PlatformRouteOptions.js.map +1 -0
  247. package/lib/esm/interfaces/ResponseErrorObject.js +2 -0
  248. package/lib/esm/interfaces/ResponseErrorObject.js.map +1 -0
  249. package/lib/esm/interfaces/Route.js +2 -0
  250. package/lib/esm/interfaces/Route.js.map +1 -0
  251. package/lib/esm/interfaces/index.js +18 -0
  252. package/lib/esm/interfaces/index.js.map +1 -0
  253. package/lib/esm/middlewares/PlatformAcceptMimesMiddleware.js +34 -0
  254. package/lib/esm/middlewares/PlatformAcceptMimesMiddleware.js.map +1 -0
  255. package/lib/esm/middlewares/PlatformMulterMiddleware.js +52 -0
  256. package/lib/esm/middlewares/PlatformMulterMiddleware.js.map +1 -0
  257. package/lib/esm/middlewares/__mock__/FakeCtrl.js +9 -0
  258. package/lib/esm/middlewares/__mock__/FakeCtrl.js.map +1 -0
  259. package/lib/esm/middlewares/bindEndpointMiddleware.js +9 -0
  260. package/lib/esm/middlewares/bindEndpointMiddleware.js.map +1 -0
  261. package/lib/esm/middlewares/index.js +4 -0
  262. package/lib/esm/middlewares/index.js.map +1 -0
  263. package/lib/esm/services/FakeRawDriver.js +22 -0
  264. package/lib/esm/services/FakeRawDriver.js.map +1 -0
  265. package/lib/esm/services/Platform.js +104 -0
  266. package/lib/esm/services/Platform.js.map +1 -0
  267. package/lib/esm/services/PlatformApplication.js +31 -0
  268. package/lib/esm/services/PlatformApplication.js.map +1 -0
  269. package/lib/esm/services/PlatformHandler.js +230 -0
  270. package/lib/esm/services/PlatformHandler.js.map +1 -0
  271. package/lib/esm/services/PlatformMiddlewaresChain.js +31 -0
  272. package/lib/esm/services/PlatformMiddlewaresChain.js.map +1 -0
  273. package/lib/esm/services/PlatformRequest.js +135 -0
  274. package/lib/esm/services/PlatformRequest.js.map +1 -0
  275. package/lib/esm/services/PlatformResponse.js +268 -0
  276. package/lib/esm/services/PlatformResponse.js.map +1 -0
  277. package/lib/esm/services/PlatformRouter.js +123 -0
  278. package/lib/esm/services/PlatformRouter.js.map +1 -0
  279. package/lib/esm/services/PlatformTest.js +162 -0
  280. package/lib/esm/services/PlatformTest.js.map +1 -0
  281. package/lib/esm/services/index.js +9 -0
  282. package/lib/esm/services/index.js.map +1 -0
  283. package/lib/esm/utils/createContext.js +34 -0
  284. package/lib/esm/utils/createContext.js.map +1 -0
  285. package/lib/esm/utils/createHandlerMetadata.js +45 -0
  286. package/lib/esm/utils/createHandlerMetadata.js.map +1 -0
  287. package/lib/esm/utils/createHttpServer.js +29 -0
  288. package/lib/esm/utils/createHttpServer.js.map +1 -0
  289. package/lib/esm/utils/createHttpsServer.js +29 -0
  290. package/lib/esm/utils/createHttpsServer.js.map +1 -0
  291. package/lib/esm/utils/createInjector.js +34 -0
  292. package/lib/esm/utils/createInjector.js.map +1 -0
  293. package/lib/esm/utils/getConfiguration.js +38 -0
  294. package/lib/esm/utils/getConfiguration.js.map +1 -0
  295. package/lib/esm/utils/getStaticsOptions.js +17 -0
  296. package/lib/esm/utils/getStaticsOptions.js.map +1 -0
  297. package/lib/esm/utils/index.js +8 -0
  298. package/lib/esm/utils/index.js.map +1 -0
  299. package/lib/esm/utils/listenServer.js +17 -0
  300. package/lib/esm/utils/listenServer.js.map +1 -0
  301. package/lib/esm/utils/mapReturnedResponse.js +11 -0
  302. package/lib/esm/utils/mapReturnedResponse.js.map +1 -0
  303. package/lib/esm/utils/printRoutes.js +32 -0
  304. package/lib/esm/utils/printRoutes.js.map +1 -0
  305. package/lib/esm/utils/setResponseHeaders.js +31 -0
  306. package/lib/esm/utils/setResponseHeaders.js.map +1 -0
  307. package/lib/esm/utils/useCtxHandler.js +11 -0
  308. package/lib/esm/utils/useCtxHandler.js.map +1 -0
  309. package/lib/{builder → types/builder}/PlatformBuilder.d.ts +25 -30
  310. package/lib/types/builder/PlatformControllerBuilder.d.ts +17 -0
  311. package/lib/{config → types/config}/index.d.ts +0 -0
  312. package/lib/{config → types/config}/interfaces/ConverterSettings.d.ts +0 -0
  313. package/lib/{config → types/config}/interfaces/EndpointDirectoriesSettings.d.ts +0 -0
  314. package/lib/{config → types/config}/interfaces/PlatformLoggerSettings.d.ts +0 -16
  315. package/lib/{config → types/config}/interfaces/PlatformMulterSettings.d.ts +0 -0
  316. package/lib/{config → types/config}/interfaces/PlatformStaticsSettings.d.ts +1 -0
  317. package/lib/{config → types/config}/interfaces/index.d.ts +17 -2
  318. package/lib/{config → types/config}/services/PlatformConfiguration.d.ts +13 -11
  319. package/lib/{constants → types/constants}/routerOptions.d.ts +0 -0
  320. package/lib/{decorators → types/decorators}/httpServer.d.ts +1 -0
  321. package/lib/{decorators → types/decorators}/httpsServer.d.ts +1 -0
  322. package/lib/{decorators → types/decorators}/index.d.ts +1 -5
  323. package/lib/{decorators → types/decorators}/method/acceptMime.d.ts +0 -0
  324. package/lib/{decorators → types/decorators}/multer/index.d.ts +0 -0
  325. package/lib/{decorators → types/decorators}/multer/multerFileSize.d.ts +0 -0
  326. package/lib/{decorators → types/decorators}/multer/multerOptions.d.ts +0 -0
  327. package/lib/{decorators → types/decorators}/multer/multipartFile.d.ts +0 -0
  328. package/lib/{decorators → types/decorators}/params/error.d.ts +0 -0
  329. package/lib/{decorators → types/decorators}/params/next.d.ts +0 -0
  330. package/lib/{decorators → types/decorators}/params/request.d.ts +0 -0
  331. package/lib/{decorators → types/decorators}/params/response.d.ts +0 -0
  332. package/lib/{domain → types/domain}/AnyToPromiseWithCtx.d.ts +0 -0
  333. package/lib/types/domain/ControllerProvider.d.ts +24 -0
  334. package/lib/{domain → types/domain}/EndpointMetadata.d.ts +3 -42
  335. package/lib/{domain → types/domain}/HandlerMetadata.d.ts +2 -2
  336. package/lib/{domain → types/domain}/PlatformContext.d.ts +1 -1
  337. package/lib/{domain → types/domain}/PlatformRouteDetails.d.ts +4 -10
  338. package/lib/{domain → types/domain}/index.d.ts +0 -0
  339. package/lib/{index.d.ts → types/index.d.ts} +2 -3
  340. package/lib/{interfaces → types/interfaces}/AfterInit.d.ts +0 -0
  341. package/lib/{interfaces → types/interfaces}/AfterListen.d.ts +0 -0
  342. package/lib/{interfaces → types/interfaces}/AfterRoutesInit.d.ts +0 -0
  343. package/lib/{interfaces → types/interfaces}/BeforeInit.d.ts +0 -0
  344. package/lib/{interfaces → types/interfaces}/BeforeListen.d.ts +0 -0
  345. package/lib/{interfaces → types/interfaces}/BeforeRoutesInit.d.ts +0 -0
  346. package/lib/{interfaces → types/interfaces}/HandlerType.d.ts +0 -0
  347. package/lib/{interfaces → types/interfaces}/IncomingEvent.d.ts +0 -0
  348. package/lib/{interfaces → types/interfaces}/OnReady.d.ts +0 -0
  349. package/lib/{interfaces → types/interfaces}/OnRequest.d.ts +0 -0
  350. package/lib/{interfaces → types/interfaces}/OnResponse.d.ts +0 -0
  351. package/lib/{interfaces → types/interfaces}/OnRoutesInit.d.ts +0 -0
  352. package/lib/{interfaces → types/interfaces}/PathType.d.ts +0 -0
  353. package/lib/types/interfaces/PlatformAdapter.d.ts +19 -0
  354. package/lib/{interfaces → types/interfaces}/PlatformRouteOptions.d.ts +5 -3
  355. package/lib/{interfaces → types/interfaces}/ResponseErrorObject.d.ts +0 -0
  356. package/lib/{interfaces → types/interfaces}/Route.d.ts +0 -0
  357. package/lib/{interfaces → types/interfaces}/index.d.ts +1 -2
  358. package/lib/{middlewares → types/middlewares}/PlatformAcceptMimesMiddleware.d.ts +0 -0
  359. package/lib/{middlewares → types/middlewares}/PlatformMulterMiddleware.d.ts +0 -0
  360. package/lib/{middlewares/data → types/middlewares/__mock__}/FakeCtrl.d.ts +0 -0
  361. package/lib/{middlewares → types/middlewares}/bindEndpointMiddleware.d.ts +0 -0
  362. package/lib/{middlewares → types/middlewares}/index.d.ts +0 -1
  363. package/lib/{services → types/services}/FakeRawDriver.d.ts +0 -0
  364. package/lib/{services → types/services}/Platform.d.ts +12 -6
  365. package/lib/{services → types/services}/PlatformApplication.d.ts +0 -0
  366. package/lib/{services → types/services}/PlatformHandler.d.ts +3 -8
  367. package/lib/types/services/PlatformMiddlewaresChain.d.ts +6 -0
  368. package/lib/{services → types/services}/PlatformRequest.d.ts +2 -1
  369. package/lib/{services → types/services}/PlatformResponse.d.ts +4 -4
  370. package/lib/{services → types/services}/PlatformRouter.d.ts +4 -3
  371. package/lib/{services → types/services}/PlatformTest.d.ts +7 -6
  372. package/lib/{services → types/services}/index.d.ts +1 -1
  373. package/lib/{utils → types/utils}/createContext.d.ts +0 -0
  374. package/lib/{utils → types/utils}/createHandlerMetadata.d.ts +0 -0
  375. package/lib/types/utils/createHttpServer.d.ts +4 -0
  376. package/lib/types/utils/createHttpsServer.d.ts +4 -0
  377. package/lib/types/utils/createInjector.d.ts +7 -0
  378. package/lib/types/utils/getConfiguration.d.ts +2 -0
  379. package/lib/types/utils/getStaticsOptions.d.ts +5 -0
  380. package/lib/{utils → types/utils}/index.d.ts +0 -1
  381. package/lib/types/utils/listenServer.d.ts +7 -0
  382. package/lib/{utils → types/utils}/mapReturnedResponse.d.ts +0 -0
  383. package/lib/{utils → types/utils}/printRoutes.d.ts +0 -0
  384. package/lib/{utils → types/utils}/setResponseHeaders.d.ts +0 -0
  385. package/lib/{utils → types/utils}/useCtxHandler.d.ts +0 -0
  386. package/package.json +29 -24
  387. package/tsconfig.compile.esm.json +23 -0
  388. package/lib/PlatformModule.d.ts +0 -15
  389. package/lib/builder/PlatformControllerBuilder.d.ts +0 -19
  390. package/lib/decorators/class/controller.d.ts +0 -43
  391. package/lib/decorators/method/endpointFn.d.ts +0 -8
  392. package/lib/decorators/method/location.d.ts +0 -1
  393. package/lib/decorators/method/redirect.d.ts +0 -1
  394. package/lib/decorators/method/route.d.ts +0 -128
  395. package/lib/domain/ControllerProvider.d.ts +0 -54
  396. package/lib/index.js +0 -3990
  397. package/lib/index.js.map +0 -1
  398. package/lib/index.modern.js +0 -3870
  399. package/lib/index.modern.js.map +0 -1
  400. package/lib/interfaces/PlatformRouterMethods.d.ts +0 -10
  401. package/lib/middlewares/PlatformLogMiddleware.d.ts +0 -44
  402. package/lib/registries/ControllerRegistry.d.ts +0 -1
  403. package/lib/services/ConverterService.d.ts +0 -27
  404. package/lib/utils/createHttpServer.d.ts +0 -3
  405. package/lib/utils/createHttpsServer.d.ts +0 -3
  406. package/lib/utils/createInjector.d.ts +0 -2
  407. package/lib/utils/createPlatformApplication.d.ts +0 -2
  408. package/lib/utils/getControllerPath.d.ts +0 -2
  409. package/lib/utils/listenServer.d.ts +0 -10
package/lib/index.js DELETED
@@ -1,3990 +0,0 @@
1
- var di = require('@tsed/di');
2
- var platformParams = require('@tsed/platform-params');
3
- var platformExceptions = require('@tsed/platform-exceptions');
4
- var platformResponseFilter = require('@tsed/platform-response-filter');
5
- var platformCache = require('@tsed/platform-cache');
6
- var platformMiddlewares = require('@tsed/platform-middlewares');
7
- var platformViews = require('@tsed/platform-views');
8
- var componentsScan = require('@tsed/components-scan');
9
- var logger = require('@tsed/logger');
10
- var tslib = require('tslib');
11
- var core = require('@tsed/core');
12
- var perf = require('@tsed/perf');
13
- var exceptions = require('@tsed/exceptions');
14
- var schema = require('@tsed/schema');
15
- var jsonMapper = require('@tsed/json-mapper');
16
- var util = require('util');
17
- var Http = require('http');
18
- var Https = require('https');
19
-
20
- function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
21
-
22
- var Http__default = /*#__PURE__*/_interopDefaultLegacy(Http);
23
- var Https__default = /*#__PURE__*/_interopDefaultLegacy(Https);
24
-
25
- function _extends() {
26
- _extends = Object.assign || function (target) {
27
- for (var i = 1; i < arguments.length; i++) {
28
- var source = arguments[i];
29
-
30
- for (var key in source) {
31
- if (Object.prototype.hasOwnProperty.call(source, key)) {
32
- target[key] = source[key];
33
- }
34
- }
35
- }
36
-
37
- return target;
38
- };
39
-
40
- return _extends.apply(this, arguments);
41
- }
42
-
43
- function _objectWithoutPropertiesLoose(source, excluded) {
44
- if (source == null) return {};
45
- var target = {};
46
- var sourceKeys = Object.keys(source);
47
- var key, i;
48
-
49
- for (i = 0; i < sourceKeys.length; i++) {
50
- key = sourceKeys[i];
51
- if (excluded.indexOf(key) >= 0) continue;
52
- target[key] = source[key];
53
- }
54
-
55
- return target;
56
- }
57
-
58
- var id = 0;
59
-
60
- function _classPrivateFieldLooseKey(name) {
61
- return "__private_" + id++ + "_" + name;
62
- }
63
-
64
- function _classPrivateFieldLooseBase(receiver, privateKey) {
65
- if (!Object.prototype.hasOwnProperty.call(receiver, privateKey)) {
66
- throw new TypeError("attempted to use private field on non-instance");
67
- }
68
-
69
- return receiver;
70
- }
71
-
72
- var PlatformConfiguration_1;
73
- const rootDir = process.cwd();
74
- /**
75
- * `PlatformConfiguration` contains all information about your Server configuration.
76
- */
77
-
78
- exports.PlatformConfiguration = PlatformConfiguration_1 = class PlatformConfiguration extends di.DIConfiguration {
79
- constructor() {
80
- super({
81
- rootDir,
82
- env: process.env.NODE_ENV || core.Env.DEV,
83
- httpPort: 8080,
84
- httpsPort: false,
85
- scopes: {
86
- [di.ProviderType.CONTROLLER]: di.ProviderScope.SINGLETON
87
- },
88
- logger: {
89
- debug: false,
90
- level: "info",
91
- logRequest: true,
92
- jsonIndentation: process.env.NODE_ENV === core.Env.PROD ? 0 : 2
93
- },
94
- errors: {
95
- headerName: "errors"
96
- },
97
- mount: {
98
- "/rest": "${rootDir}/controllers/**/*.ts"
99
- },
100
- exclude: ["**/*.spec.ts", "**/*.spec.js"],
101
- componentsScan: ["${rootDir}/mvc/**/*.ts", "${rootDir}/services/**/*.ts", "${rootDir}/middlewares/**/*.ts"]
102
- });
103
- }
104
-
105
- get version() {
106
- return this.getRaw("version");
107
- }
108
-
109
- set version(v) {
110
- this.setRaw("version", v);
111
- }
112
-
113
- get rootDir() {
114
- return this.getRaw("rootDir");
115
- }
116
-
117
- set rootDir(value) {
118
- this.setRaw("rootDir", value);
119
- }
120
-
121
- get port() {
122
- return this.httpPort;
123
- }
124
-
125
- set port(value) {
126
- this.httpPort = value;
127
- }
128
-
129
- get httpsOptions() {
130
- return this.getRaw("httpsOptions");
131
- }
132
-
133
- set httpsOptions(value) {
134
- this.setRaw("httpsOptions", value);
135
- }
136
-
137
- get httpPort() {
138
- return this.getRaw("httpPort");
139
- }
140
-
141
- set httpPort(value) {
142
- this.setRaw("httpPort", value);
143
- }
144
-
145
- get httpsPort() {
146
- return this.getRaw("httpsPort");
147
- }
148
-
149
- set httpsPort(value) {
150
- this.setRaw("httpsPort", value);
151
- }
152
-
153
- get env() {
154
- return this.getRaw("env");
155
- }
156
-
157
- set env(value) {
158
- this.setRaw("env", value);
159
- }
160
-
161
- get mount() {
162
- return this.get("mount");
163
- }
164
-
165
- set mount(value) {
166
- this.setRaw("mount", value);
167
- }
168
-
169
- get componentsScan() {
170
- return this.resolve(this.getRaw("componentsScan"));
171
- }
172
-
173
- set componentsScan(value) {
174
- this.setRaw("componentsScan", value);
175
- }
176
-
177
- get statics() {
178
- return this.getRaw("statics") || this.getRaw("serveStatic") || {};
179
- }
180
-
181
- set statics(value) {
182
- this.setRaw("statics", value);
183
- }
184
-
185
- get acceptMimes() {
186
- return this.getRaw("acceptMimes");
187
- }
188
-
189
- set acceptMimes(value) {
190
- this.setRaw("acceptMimes", value || []);
191
- }
192
-
193
- get debug() {
194
- return this.logger.level === "debug";
195
- }
196
-
197
- set debug(debug) {
198
- this.logger = _extends({}, this.logger, {
199
- level: debug ? "debug" : "info"
200
- });
201
- }
202
-
203
- get converter() {
204
- return this.get("converter") || {};
205
- }
206
-
207
- set converter(options) {
208
- this.setRaw("converter", options);
209
- }
210
-
211
- get logger() {
212
- return this.get("logger");
213
- }
214
-
215
- set logger(value) {
216
- const logger$1 = _extends({}, this.logger, value);
217
-
218
- logger$1.debug = logger$1.level === "debug";
219
- this.setRaw("logger", logger$1);
220
- this.setRaw("debug", logger$1.debug);
221
-
222
- if (logger$1.format) {
223
- logger.$log.appenders.set("stdout", {
224
- type: "stdout",
225
- levels: ["info", "debug"],
226
- layout: {
227
- type: "pattern",
228
- pattern: logger$1.format
229
- }
230
- });
231
- logger.$log.appenders.set("stderr", {
232
- levels: ["trace", "fatal", "error", "warn"],
233
- type: "stderr",
234
- layout: {
235
- type: "pattern",
236
- pattern: logger$1.format
237
- }
238
- });
239
- }
240
- }
241
-
242
- get exclude() {
243
- return this.get("exclude");
244
- }
245
-
246
- set exclude(exclude) {
247
- this.setRaw("exclude", exclude);
248
- }
249
- /**
250
- *
251
- * @param addressPort
252
- * @returns {{address: string, port: number}}
253
- */
254
-
255
-
256
- static buildAddressAndPort(addressPort) {
257
- let address = "0.0.0.0";
258
- let port = addressPort;
259
-
260
- if (typeof addressPort === "string" && addressPort.indexOf(":") > -1) {
261
- [address, port] = addressPort.split(":");
262
- port = +port;
263
- }
264
-
265
- return {
266
- address,
267
- port: port
268
- };
269
- }
270
- /**
271
- *
272
- * @returns {string|number}
273
- */
274
-
275
-
276
- getHttpPort() {
277
- return PlatformConfiguration_1.buildAddressAndPort(this.getRaw("httpPort"));
278
- }
279
- /**
280
- *
281
- * @param settings
282
- */
283
-
284
-
285
- setHttpPort(settings) {
286
- this.setRaw("httpPort", `${settings.address}:${settings.port}`);
287
- }
288
- /**
289
- *
290
- * @returns {string|number}
291
- */
292
-
293
-
294
- getHttpsPort() {
295
- return PlatformConfiguration_1.buildAddressAndPort(this.getRaw("httpsPort"));
296
- }
297
- /**
298
- *
299
- * @param settings
300
- */
301
-
302
-
303
- setHttpsPort(settings) {
304
- this.setRaw("httpsPort", `${settings.address}:${settings.port}`);
305
- }
306
-
307
- };
308
- exports.PlatformConfiguration = PlatformConfiguration_1 = tslib.__decorate([di.Injectable({
309
- scope: di.ProviderScope.SINGLETON,
310
- global: true
311
- }), tslib.__metadata("design:paramtypes", [])], exports.PlatformConfiguration);
312
-
313
- /**
314
- * @ignore
315
- */
316
- function bindEndpointMiddleware(endpoint) {
317
- return ctx => {
318
- ctx.endpoint = endpoint;
319
- };
320
- }
321
-
322
- var PlatformLogMiddleware_1;
323
- /**
324
- * @middleware
325
- * @platform
326
- */
327
-
328
- exports.PlatformLogMiddleware = PlatformLogMiddleware_1 = class PlatformLogMiddleware {
329
- // tslint:disable-next-line: no-unused-variable
330
- constructor(injector) {
331
- this.settings = injector.settings.logger || {};
332
- this.settings.requestFields = this.settings.requestFields || PlatformLogMiddleware_1.DEFAULT_FIELDS;
333
-
334
- if (this.settings.level !== "off") {
335
- this.$onResponse = this.onLogEnd.bind(this);
336
- }
337
- }
338
- /**
339
- * Handle the request.
340
- */
341
-
342
-
343
- use(ctx) {
344
- this.configureRequest(ctx);
345
- this.onLogStart(ctx);
346
- }
347
- /**
348
- * The separate onLogStart() function will allow developer to overwrite the initial request log.
349
- * @param ctx
350
- */
351
-
352
-
353
- onLogStart(ctx) {
354
- const {
355
- debug,
356
- logRequest,
357
- logStart
358
- } = this.settings;
359
-
360
- if (logStart !== false) {
361
- if (debug) {
362
- ctx.logger.debug({
363
- event: "request.start"
364
- });
365
- } else if (logRequest) {
366
- ctx.logger.info({
367
- event: "request.start"
368
- });
369
- }
370
- }
371
- }
372
- /**
373
- * Called when the `$onResponse` is called by Ts.ED (through Express.end).
374
- */
375
-
376
-
377
- onLogEnd(ctx) {
378
- const {
379
- debug,
380
- logRequest,
381
- logEnd
382
- } = this.settings;
383
-
384
- if (logEnd !== false) {
385
- if (debug) {
386
- ctx.logger.debug({
387
- event: "request.end",
388
- status: ctx.response.statusCode,
389
- data: ctx.data
390
- });
391
- } else if (logRequest) {
392
- ctx.logger.info({
393
- event: "request.end",
394
- status: ctx.response.statusCode
395
- });
396
- }
397
- }
398
-
399
- ctx.logger.flush();
400
- }
401
- /**
402
- * Attach all information that will be necessary to log the request. Attach a new `request.log` object.
403
- */
404
-
405
-
406
- configureRequest(ctx) {
407
- ctx.logger.minimalRequestPicker = obj => _extends({}, this.minimalRequestPicker(ctx), obj);
408
-
409
- ctx.logger.completeRequestPicker = obj => _extends({}, this.requestToObject(ctx), obj);
410
- }
411
- /**
412
- * Return complete request info.
413
- * @returns {Object}
414
- * @param ctx
415
- */
416
-
417
-
418
- requestToObject(ctx) {
419
- const {
420
- request
421
- } = ctx;
422
- return {
423
- method: request.method,
424
- url: request.url,
425
- headers: request.headers,
426
- body: request.body,
427
- query: request.query,
428
- params: request.params
429
- };
430
- }
431
- /**
432
- * Return a filtered request from global configuration.
433
- * @returns {Object}
434
- * @param ctx
435
- */
436
-
437
-
438
- minimalRequestPicker(ctx) {
439
- const {
440
- requestFields
441
- } = this.settings;
442
- const info = this.requestToObject(ctx);
443
- return requestFields.reduce((acc, key) => {
444
- acc[key] = info[key];
445
- return acc;
446
- }, {});
447
- }
448
-
449
- };
450
- exports.PlatformLogMiddleware.DEFAULT_FIELDS = ["reqId", "method", "url", "duration"];
451
-
452
- tslib.__decorate([tslib.__param(0, platformParams.Context()), tslib.__metadata("design:type", Function), tslib.__metadata("design:paramtypes", [Object]), tslib.__metadata("design:returntype", void 0)], exports.PlatformLogMiddleware.prototype, "use", null);
453
-
454
- exports.PlatformLogMiddleware = PlatformLogMiddleware_1 = tslib.__decorate([platformMiddlewares.Middleware(), tslib.__metadata("design:paramtypes", [di.InjectorService])], exports.PlatformLogMiddleware);
455
-
456
- /**
457
- * @ignore
458
- */
459
- const createFakeRawDriver = () => {
460
- // istanbul ignore next
461
- function FakeRawDriver() {} // istanbul ignore next
462
-
463
-
464
- function use() {
465
- return this;
466
- }
467
-
468
- FakeRawDriver.use = use;
469
- FakeRawDriver.all = use;
470
- FakeRawDriver.get = use;
471
- FakeRawDriver.patch = use;
472
- FakeRawDriver.post = use;
473
- FakeRawDriver.put = use;
474
- FakeRawDriver.head = use;
475
- FakeRawDriver.delete = use;
476
- FakeRawDriver.options = use;
477
- return FakeRawDriver;
478
- };
479
-
480
- class AnyToPromiseWithCtx extends core.AnyToPromise {
481
- constructor({
482
- $ctx,
483
- err
484
- }) {
485
- super();
486
- this.$ctx = $ctx;
487
- this.err = err;
488
- }
489
-
490
- isDone() {
491
- const {
492
- $ctx
493
- } = this;
494
-
495
- if (!($ctx != null && $ctx.isDone())) {
496
- if ($ctx != null && $ctx.request.isAborted() || $ctx != null && $ctx.response.isDone()) {
497
- this.destroy();
498
-
499
- if (this.status === core.AnyToPromiseStatus.PENDING) {
500
- this.status = core.AnyToPromiseStatus.RESOLVED;
501
- }
502
- }
503
- }
504
-
505
- return super.isDone();
506
- }
507
-
508
- async call(cb) {
509
- return super.call(() => cb(this));
510
- }
511
-
512
- destroy() {
513
- // @ts-ignore
514
- delete this.$ctx;
515
- }
516
-
517
- isCanceledResponse(process) {
518
- return process === this.$ctx.getResponse();
519
- }
520
-
521
- }
522
-
523
- /**
524
- * @ignore
525
- */
526
- exports.HandlerType = void 0;
527
-
528
- (function (HandlerType) {
529
- HandlerType["CUSTOM"] = "custom";
530
- HandlerType["ENDPOINT"] = "endpoint";
531
- HandlerType["MIDDLEWARE"] = "middleware";
532
- HandlerType["ERR_MIDDLEWARE"] = "err:middleware";
533
- HandlerType["CTX_FN"] = "context";
534
- HandlerType["RAW_FN"] = "raw:middleware";
535
- HandlerType["RAW_ERR_FN"] = "raw:err:middleware";
536
- })(exports.HandlerType || (exports.HandlerType = {}));
537
-
538
- class HandlerMetadata {
539
- constructor(options) {
540
- this.injectable = false;
541
- this.type = exports.HandlerType.RAW_FN;
542
- this.hasNextFunction = false;
543
- const {
544
- target,
545
- token,
546
- propertyKey,
547
- type,
548
- scope,
549
- routeOptions
550
- } = options;
551
- this.type = type || target.type || exports.HandlerType.RAW_FN;
552
- this.scope = scope || di.ProviderScope.SINGLETON;
553
- this.routeOptions = routeOptions || {};
554
- const handler = propertyKey ? target.prototype[propertyKey] : target;
555
-
556
- if (propertyKey) {
557
- this.target = target;
558
- this.token = token;
559
- this.propertyKey = propertyKey;
560
- this.hasNextFunction = this.hasParamType(platformParams.ParamTypes.NEXT_FN);
561
-
562
- if (this.hasParamType(platformParams.ParamTypes.ERR)) {
563
- this.type = exports.HandlerType.ERR_MIDDLEWARE;
564
- }
565
-
566
- this.injectable = platformParams.ParamMetadata.getParams(target, propertyKey).length > 0;
567
- } else {
568
- this.handler = handler;
569
- }
570
-
571
- if (!this.injectable) {
572
- if (handler.length === 4) {
573
- this.type = exports.HandlerType.RAW_ERR_FN;
574
- }
575
-
576
- this.hasNextFunction = handler.length >= 3;
577
- }
578
- }
579
-
580
- get hasErrorParam() {
581
- return this.type === exports.HandlerType.ERR_MIDDLEWARE || this.type === exports.HandlerType.RAW_ERR_FN;
582
- }
583
-
584
- getParams() {
585
- return platformParams.ParamMetadata.getParams(this.target, this.propertyKey) || [];
586
- }
587
-
588
- hasParamType(paramType) {
589
- return this.getParams().findIndex(p => p.paramType === paramType) > -1;
590
- }
591
-
592
- isFinal() {
593
- var _this$routeOptions;
594
-
595
- return ((_this$routeOptions = this.routeOptions) == null ? void 0 : _this$routeOptions.isFinal) || false;
596
- }
597
-
598
- toString() {
599
- return [this.target && core.nameOf(this.target), this.propertyKey].filter(Boolean).join(".");
600
- }
601
-
602
- }
603
-
604
- var EndpointMetadata_1;
605
- /**
606
- * EndpointMetadata contains metadata about a controller and his method.
607
- * Each annotation (@Get, @Body...) attached to a method are stored in a endpoint.
608
- * EndpointMetadata convert this metadata to an array which contain arguments to call an Express method.
609
- *
610
- * Example :
611
- *
612
- * @Controller("/my-path")
613
- * provide MyClass {
614
- *
615
- * @Get("/")
616
- * @Authenticated()
617
- * public myMethod(){}
618
- * }
619
- *
620
- */
621
-
622
- exports.EndpointMetadata = EndpointMetadata_1 = class EndpointMetadata extends schema.JsonEntityStore {
623
- constructor(options) {
624
- super(_extends({
625
- store: core.Store.fromMethod(options.target, options.propertyKey),
626
- descriptor: core.descriptorOf(options.target, options.propertyKey)
627
- }, options)); // LIFECYCLE
628
-
629
- this.beforeMiddlewares = [];
630
- this.middlewares = [];
631
- this.afterMiddlewares = [];
632
- this.statusCode = 200;
633
- const {
634
- beforeMiddlewares = [],
635
- middlewares = [],
636
- afterMiddlewares = []
637
- } = options;
638
- this.after(afterMiddlewares);
639
- this.before(beforeMiddlewares);
640
- this.use(middlewares);
641
- }
642
-
643
- get targetName() {
644
- return core.nameOf(this.token);
645
- }
646
-
647
- get params() {
648
- return Array.from(this.children.values());
649
- }
650
- /**
651
- * Return the JsonOperation
652
- */
653
-
654
-
655
- get operation() {
656
- return this._operation;
657
- }
658
-
659
- get operationPaths() {
660
- return this.operation.operationPaths;
661
- }
662
-
663
- get view() {
664
- return this.store.get("view");
665
- }
666
-
667
- set view(view) {
668
- this.store.set("view", view);
669
- }
670
-
671
- get acceptMimes() {
672
- return this.store.get("acceptMimes", []);
673
- }
674
-
675
- set acceptMimes(mimes) {
676
- this.store.set("acceptMimes", mimes);
677
- }
678
- /**
679
- * Get all endpoints from a given class and his parents.
680
- * @param {Type<any>} target
681
- * @returns {EndpointMetadata[]}
682
- */
683
-
684
-
685
- static getEndpoints(target) {
686
- const operations = schema.getOperationsStores(target);
687
- return Array.from(operations.values()).map(endpoint => {
688
- endpoint = endpoint.clone();
689
- endpoint.token = core.classOf(target);
690
- return endpoint;
691
- });
692
- }
693
- /**
694
- * Get an endpoint.
695
- * @param target
696
- * @param propertyKey
697
- * @param descriptor
698
- */
699
-
700
-
701
- static get(target, propertyKey, descriptor) {
702
- descriptor = descriptor || core.descriptorOf(core.prototypeOf(target), propertyKey);
703
- return schema.JsonEntityStore.from(core.prototypeOf(target), propertyKey, descriptor);
704
- }
705
-
706
- addOperationPath(method, path, options = {}) {
707
- return this.operation.addOperationPath(method, path, options);
708
- }
709
- /**
710
- * Find the a value at the controller level. Let this value be extended or overridden by the endpoint itself.
711
- *
712
- * @param key
713
- * @returns {any}
714
- */
715
-
716
-
717
- get(key) {
718
- const ctrlValue = core.Store.from(this.target).get(key);
719
- return core.deepMerge(ctrlValue, this.store.get(key));
720
- }
721
- /**
722
- * Append middlewares to the beforeMiddlewares list.
723
- * @param args
724
- * @returns {EndpointMetadata}
725
- */
726
-
727
-
728
- before(args) {
729
- this.beforeMiddlewares = this.beforeMiddlewares.concat(args).filter(core.isFunction);
730
- return this;
731
- }
732
- /**
733
- * Append middlewares to the afterMiddlewares list.
734
- * @param args
735
- * @returns {EndpointMetadata}
736
- */
737
-
738
-
739
- after(args) {
740
- this.afterMiddlewares = this.afterMiddlewares.concat(args).filter(core.isFunction);
741
- return this;
742
- }
743
- /**
744
- * Store all arguments collected via Annotation.
745
- * @param args
746
- */
747
-
748
-
749
- use(args) {
750
- this.middlewares = this.middlewares.concat(args).filter(core.isFunction);
751
- return this;
752
- }
753
-
754
- clone() {
755
- const endpoint = new EndpointMetadata_1(_extends({}, this, {
756
- target: this.target,
757
- propertyKey: this.propertyKey,
758
- descriptor: this.descriptor,
759
- store: this.store,
760
- children: this.children
761
- }));
762
- endpoint.collectionType = this.collectionType;
763
- endpoint._type = this._type;
764
- endpoint._operation = this.operation;
765
- endpoint._schema = this._schema;
766
- endpoint.middlewares = [...this.middlewares];
767
- endpoint.afterMiddlewares = [...this.afterMiddlewares];
768
- endpoint.beforeMiddlewares = [...this.beforeMiddlewares];
769
- return endpoint;
770
- }
771
-
772
- };
773
-
774
- tslib.__decorate([core.Enumerable(), tslib.__metadata("design:type", Array)], exports.EndpointMetadata.prototype, "beforeMiddlewares", void 0);
775
-
776
- tslib.__decorate([core.Enumerable(), tslib.__metadata("design:type", Array)], exports.EndpointMetadata.prototype, "middlewares", void 0);
777
-
778
- tslib.__decorate([core.Enumerable(), tslib.__metadata("design:type", Array)], exports.EndpointMetadata.prototype, "afterMiddlewares", void 0);
779
-
780
- tslib.__decorate([core.Enumerable(), tslib.__metadata("design:type", Number)], exports.EndpointMetadata.prototype, "statusCode", void 0);
781
-
782
- exports.EndpointMetadata = EndpointMetadata_1 = tslib.__decorate([schema.JsonEntityComponent(core.DecoratorTypes.METHOD), tslib.__metadata("design:paramtypes", [Object])], exports.EndpointMetadata);
783
-
784
- function isMetadata(input) {
785
- return input instanceof HandlerMetadata;
786
- }
787
- /**
788
- * @ignore
789
- */
790
-
791
-
792
- function createHandlerMetadata(injector, obj, routeOptions = {}) {
793
- if (isMetadata(obj)) {
794
- return obj;
795
- }
796
-
797
- let options;
798
-
799
- if (obj instanceof exports.EndpointMetadata) {
800
- const provider = injector.getProvider(obj.token);
801
- options = {
802
- token: provider.token,
803
- target: provider.useClass,
804
- scope: provider.scope,
805
- type: exports.HandlerType.ENDPOINT,
806
- propertyKey: obj.propertyKey
807
- };
808
- } else {
809
- const provider = injector.getProvider(obj);
810
-
811
- if (provider) {
812
- options = {
813
- token: provider.token,
814
- target: provider.useClass,
815
- scope: provider.scope,
816
- type: exports.HandlerType.MIDDLEWARE,
817
- propertyKey: "use"
818
- };
819
- } else {
820
- options = {
821
- target: obj
822
- };
823
- }
824
- }
825
-
826
- options.routeOptions = routeOptions;
827
- return new HandlerMetadata(options);
828
- }
829
-
830
- function mergeHeaders(specHeaders, headers) {
831
- return Object.entries(specHeaders).reduce((headers, [key, item]) => {
832
- key = key.toLowerCase();
833
- return _extends({}, headers, {
834
- [key]: headers[key] === undefined ? String(item.example) : headers[key]
835
- });
836
- }, headers);
837
- }
838
- /**
839
- * @ignore
840
- */
841
-
842
-
843
- function setResponseHeaders(ctx) {
844
- const {
845
- response,
846
- endpoint
847
- } = ctx;
848
- const {
849
- operation
850
- } = endpoint;
851
-
852
- if (response.isDone()) {
853
- return;
854
- }
855
-
856
- if (!response.hasStatus()) {
857
- // apply status only if the isn't already modified
858
- response.status(operation.getStatus());
859
- }
860
-
861
- const statusCode = response.statusCode;
862
- const headers = operation.getHeadersOf(response.statusCode);
863
- const mergedHeaders = mergeHeaders(headers, response.getHeaders());
864
- response.setHeaders(mergedHeaders);
865
-
866
- if (operation.isRedirection(statusCode)) {
867
- response.redirect(statusCode, String(mergedHeaders["location"]));
868
- }
869
- }
870
-
871
- var _converterSettings;
872
- exports.ConverterService = (_converterSettings = /*#__PURE__*/_classPrivateFieldLooseKey("converterSettings"), class ConverterService {
873
- constructor(injectorService, configuration) {
874
- Object.defineProperty(this, _converterSettings, {
875
- writable: true,
876
- value: void 0
877
- });
878
- this.injectorService = injectorService;
879
- _classPrivateFieldLooseBase(this, _converterSettings)[_converterSettings] = configuration.get("converter") || {};
880
- }
881
-
882
- /**
883
- * Convert instance to plainObject.
884
- *
885
- * @param obj
886
- * @param options
887
- */
888
- serialize(obj, options = {}) {
889
- return jsonMapper.serialize(obj, _extends({
890
- useAlias: true,
891
- additionalProperties: _classPrivateFieldLooseBase(this, _converterSettings)[_converterSettings].additionalProperties === "accept"
892
- }, options));
893
- }
894
- /**
895
- * Convert a plainObject to targetType.
896
- *
897
- * ### Options
898
- *
899
- * - `ignoreCallback`: callback called for each object which will be deserialized. The callback can return a boolean to avoid the default converter behavior.
900
- * - `checkRequiredValue`: Disable the required check condition.
901
- *
902
- * @param obj Object source that will be deserialized
903
- * @param options Mapping options
904
- * @returns {any}
905
- */
906
-
907
-
908
- deserialize(obj, options = {}) {
909
- return jsonMapper.deserialize(obj, _extends({
910
- useAlias: true,
911
- additionalProperties: _classPrivateFieldLooseBase(this, _converterSettings)[_converterSettings].additionalProperties === "accept"
912
- }, options));
913
- }
914
-
915
- });
916
- exports.ConverterService = tslib.__decorate([di.Injectable(), tslib.__param(1, di.Configuration()), tslib.__metadata("design:paramtypes", [di.InjectorService, Object])], exports.ConverterService);
917
-
918
- function shouldBeSent(data) {
919
- return Buffer.isBuffer(data) || core.isBoolean(data) || core.isNumber(data) || core.isString(data) || data === null;
920
- }
921
-
922
- function shouldBeSerialized(data) {
923
- return !(core.isStream(data) || shouldBeSent(data) || data === undefined);
924
- }
925
- /**
926
- * Platform Handler abstraction layer. Wrap original class method to a pure platform handler (Express, Koa, etc...).
927
- * @platform
928
- */
929
-
930
-
931
- exports.PlatformHandler = class PlatformHandler {
932
- constructor(injector, params) {
933
- this.injector = injector;
934
- this.params = params;
935
- }
936
- /**
937
- * Create a native middleware based on the given metadata and return an instance of AnyToPromiseWithCtx
938
- * @param input
939
- * @param options
940
- */
941
-
942
-
943
- createHandler(input, options = {}) {
944
- return this.createRawHandler(createHandlerMetadata(this.injector, input, options));
945
- }
946
- /**
947
- * Create injectable handler from the given provider
948
- * @param provider
949
- * @param propertyKey
950
- */
951
-
952
-
953
- createCustomHandler(provider, propertyKey) {
954
- const handler = this.compileHandler(new HandlerMetadata({
955
- token: provider.provide,
956
- target: provider.useClass,
957
- type: exports.HandlerType.CUSTOM,
958
- scope: provider.scope,
959
- propertyKey
960
- }));
961
- return async ($ctx, next) => handler({
962
- $ctx,
963
- next
964
- });
965
- }
966
- /**
967
- * Send the response to the consumer.
968
- * @param data
969
- * @param ctx
970
- * @protected
971
- */
972
-
973
-
974
- async flush(data, ctx) {
975
- const {
976
- response,
977
- endpoint
978
- } = ctx;
979
-
980
- if (endpoint) {
981
- if (endpoint.view) {
982
- data = await this.render(data, ctx);
983
- } else if (shouldBeSerialized(data)) {
984
- data = this.injector.get(exports.ConverterService).serialize(data, _extends({}, endpoint.getResponseOptions(), {
985
- endpoint: true
986
- }));
987
- }
988
- }
989
-
990
- if (!response.isDone()) {
991
- const responseFilter = this.injector.get(platformResponseFilter.PlatformResponseFilter);
992
- response.body(responseFilter.transform(data, ctx));
993
- }
994
- }
995
-
996
- compileHandler(metadata) {
997
- if (metadata.type === exports.HandlerType.CTX_FN) {
998
- return async scope => {
999
- // @ts-ignore
1000
- return this.onCtxRequest(_extends({}, scope, {
1001
- handler: () => metadata.handler(scope.$ctx),
1002
- metadata
1003
- }));
1004
- };
1005
- }
1006
-
1007
- const promise = this.params.compileHandler({
1008
- token: metadata.token,
1009
- propertyKey: metadata.propertyKey,
1010
- getCustomArgs: metadata.injectable ? undefined : this.getDefaultArgs(metadata)
1011
- });
1012
- return async scope => {
1013
- const handler = await promise; // @ts-ignore
1014
-
1015
- return this.onRequest(_extends({}, scope, {
1016
- handler,
1017
- metadata
1018
- }));
1019
- };
1020
- }
1021
-
1022
- async onCtxRequest(requestOptions) {
1023
- await requestOptions.handler(requestOptions);
1024
- return this.next(requestOptions);
1025
- }
1026
- /**
1027
- * Call handler when a request his handle
1028
- * @param requestOptions
1029
- */
1030
-
1031
-
1032
- async onRequest(requestOptions) {
1033
- const {
1034
- $ctx,
1035
- metadata,
1036
- err,
1037
- handler
1038
- } = requestOptions; // istanbul ignore next
1039
-
1040
- if (!$ctx) {
1041
- logger.$log.error(`Endpoint ${metadata.toString()} is called but the response is already send to your consumer. Check your code and his middlewares please!`);
1042
- return;
1043
- }
1044
-
1045
- const resolver = new AnyToPromiseWithCtx({
1046
- $ctx,
1047
- err
1048
- });
1049
- return this.injector.runInContext($ctx, async () => {
1050
- try {
1051
- const {
1052
- state,
1053
- data,
1054
- status,
1055
- headers
1056
- } = await resolver.call(handler);
1057
-
1058
- if (state === core.AnyToPromiseStatus.RESOLVED) {
1059
- if (status) {
1060
- $ctx.response.status(status);
1061
- }
1062
-
1063
- if (headers) {
1064
- $ctx.response.setHeaders(headers);
1065
- }
1066
-
1067
- if (data !== undefined) {
1068
- $ctx.data = data;
1069
- } // Can be canceled by the handler itself
1070
-
1071
-
1072
- return await this.onSuccess($ctx.data, requestOptions);
1073
- }
1074
- } catch (er) {
1075
- return this.onError(er, requestOptions);
1076
- }
1077
- });
1078
- }
1079
-
1080
- async onError(er, requestOptions) {
1081
- const {
1082
- next,
1083
- $ctx
1084
- } = requestOptions;
1085
- $ctx.data = er;
1086
-
1087
- if (!next) {
1088
- throw er;
1089
- }
1090
-
1091
- return !$ctx.response.isHeadersSent() && next && next(er);
1092
- }
1093
- /**
1094
- * Manage success scenario
1095
- * @param data
1096
- * @param requestOptions
1097
- * @protected
1098
- */
1099
-
1100
-
1101
- async onSuccess(data, requestOptions) {
1102
- const {
1103
- metadata,
1104
- $ctx,
1105
- next
1106
- } = requestOptions; // TODO see this control is necessary
1107
- // istanbul ignore next
1108
-
1109
- if ($ctx.request.isAborted() || $ctx.response.isDone()) {
1110
- return;
1111
- } // set headers each times that an endpoint is called
1112
-
1113
-
1114
- if (metadata.type === exports.HandlerType.ENDPOINT) {
1115
- this.setHeaders($ctx);
1116
- } // call returned middleware
1117
-
1118
-
1119
- if (core.isFunction(data) && !core.isStream(data)) {
1120
- return this.callReturnedMiddleware(data, $ctx, next);
1121
- }
1122
-
1123
- if (metadata.isFinal()) {
1124
- return this.flush(data, $ctx);
1125
- }
1126
-
1127
- return this.next(requestOptions);
1128
- }
1129
- /**
1130
- * Call the returned middleware by the handler.
1131
- * @param middleware
1132
- * @param ctx
1133
- * @param next
1134
- * @protected
1135
- */
1136
-
1137
-
1138
- callReturnedMiddleware(middleware, ctx, next) {
1139
- return middleware(ctx.getRequest(), ctx.getResponse(), next);
1140
- }
1141
- /**
1142
- * Render the view if the endpoint has a configured view.
1143
- * @param data
1144
- * @param ctx
1145
- * @protected
1146
- */
1147
-
1148
-
1149
- async render(data, ctx) {
1150
- return platformViews.renderView(data, ctx);
1151
- }
1152
- /**
1153
- * create Raw handler
1154
- * @param metadata
1155
- */
1156
-
1157
-
1158
- createRawHandler(metadata) {
1159
- if ([exports.HandlerType.RAW_ERR_FN, exports.HandlerType.RAW_FN].includes(metadata.type)) {
1160
- return metadata.handler;
1161
- }
1162
-
1163
- const handler = this.compileHandler(metadata);
1164
- return async (request, response, next) => {
1165
- return handler({
1166
- next,
1167
- $ctx: request.$ctx
1168
- });
1169
- };
1170
- }
1171
- /**
1172
- * Set response headers
1173
- * @param ctx
1174
- * @protected
1175
- */
1176
-
1177
-
1178
- setHeaders(ctx) {
1179
- return setResponseHeaders(ctx);
1180
- }
1181
-
1182
- next(requestOptions) {
1183
- const {
1184
- $ctx,
1185
- next
1186
- } = requestOptions;
1187
- return !$ctx.response.isDone() && next && next();
1188
- }
1189
-
1190
- getDefaultArgs(metadata) {
1191
- return async scope => [metadata.hasErrorParam && scope.err, scope.$ctx.request.request, scope.$ctx.response.response, metadata.hasNextFunction && scope.next].filter(Boolean);
1192
- }
1193
-
1194
- };
1195
- exports.PlatformHandler = tslib.__decorate([di.Injectable({
1196
- scope: di.ProviderScope.SINGLETON
1197
- }), tslib.__metadata("design:paramtypes", [di.InjectorService, platformParams.PlatformParams])], exports.PlatformHandler);
1198
-
1199
- var PlatformRouter_1;
1200
- /**
1201
- * @ignore
1202
- */
1203
-
1204
- const PLATFORM_ROUTER_OPTIONS = Symbol.for("PlatformRouterOptions");
1205
- /**
1206
- * Platform Router abstraction layer.
1207
- * @platform
1208
- */
1209
-
1210
- exports.PlatformRouter = PlatformRouter_1 = class PlatformRouter {
1211
- constructor(platformHandler) {
1212
- this.platformHandler = platformHandler;
1213
- this.rawRouter = this.raw = PlatformRouter_1.createRawRouter();
1214
- }
1215
- /**
1216
- * Create a new instance of PlatformRouter
1217
- * @param injector
1218
- * @param routerOptions
1219
- */
1220
-
1221
-
1222
- static create(injector, routerOptions = {}) {
1223
- const locals = new Map();
1224
- locals.set(PLATFORM_ROUTER_OPTIONS, routerOptions);
1225
- return injector.invoke(PlatformRouter_1, locals);
1226
- }
1227
-
1228
- static createRawRouter() {
1229
- return createFakeRawDriver();
1230
- }
1231
-
1232
- callback() {
1233
- return this.raw;
1234
- }
1235
-
1236
- getRouter() {
1237
- return this.rawRouter;
1238
- }
1239
-
1240
- use(...handlers) {
1241
- // @ts-ignore
1242
- this.getRouter().use(...this.mapHandlers(handlers));
1243
- return this;
1244
- }
1245
-
1246
- addRoute(options) {
1247
- const {
1248
- method,
1249
- path,
1250
- handlers,
1251
- isFinal
1252
- } = options; // @ts-ignore
1253
-
1254
- this.getRouter()[method](path, ...this.mapHandlers(handlers, {
1255
- method,
1256
- path,
1257
- isFinal
1258
- }));
1259
- return this;
1260
- }
1261
-
1262
- all(path, ...handlers) {
1263
- return this.addRoute({
1264
- method: "all",
1265
- path,
1266
- handlers,
1267
- isFinal: true
1268
- });
1269
- }
1270
-
1271
- get(path, ...handlers) {
1272
- return this.addRoute({
1273
- method: "get",
1274
- path,
1275
- handlers,
1276
- isFinal: true
1277
- });
1278
- }
1279
-
1280
- post(path, ...handlers) {
1281
- return this.addRoute({
1282
- method: "post",
1283
- path,
1284
- handlers,
1285
- isFinal: true
1286
- });
1287
- }
1288
-
1289
- put(path, ...handlers) {
1290
- return this.addRoute({
1291
- method: "put",
1292
- path,
1293
- handlers,
1294
- isFinal: true
1295
- });
1296
- }
1297
-
1298
- delete(path, ...handlers) {
1299
- return this.addRoute({
1300
- method: "delete",
1301
- path,
1302
- handlers,
1303
- isFinal: true
1304
- });
1305
- }
1306
-
1307
- patch(path, ...handlers) {
1308
- return this.addRoute({
1309
- method: "patch",
1310
- path,
1311
- handlers,
1312
- isFinal: true
1313
- });
1314
- }
1315
-
1316
- head(path, ...handlers) {
1317
- return this.addRoute({
1318
- method: "head",
1319
- path,
1320
- handlers,
1321
- isFinal: true
1322
- });
1323
- }
1324
-
1325
- options(path, ...handlers) {
1326
- return this.addRoute({
1327
- method: "options",
1328
- path,
1329
- handlers,
1330
- isFinal: true
1331
- });
1332
- }
1333
-
1334
- statics(path, options) {
1335
- return this;
1336
- }
1337
-
1338
- multer(options) {
1339
- const m = require("multer")(options);
1340
-
1341
- const makePromise = (multer, name) => {
1342
- // istanbul ignore next
1343
- if (!multer[name]) return;
1344
- const fn = multer[name];
1345
-
1346
- multer[name] = function apply(...args) {
1347
- const middleware = Reflect.apply(fn, this, args);
1348
- return (req, res) => util.promisify(middleware)(req, res);
1349
- };
1350
- };
1351
-
1352
- makePromise(m, "any");
1353
- makePromise(m, "array");
1354
- makePromise(m, "fields");
1355
- makePromise(m, "none");
1356
- makePromise(m, "single");
1357
- return m;
1358
- }
1359
-
1360
- mapHandlers(handlers, options = {}) {
1361
- return handlers.reduce((list, handler, index) => {
1362
- if (typeof handler === "string") {
1363
- return list.concat(handler);
1364
- }
1365
-
1366
- if (handler instanceof PlatformRouter_1) {
1367
- return list.concat(handler.callback());
1368
- }
1369
-
1370
- return list.concat(this.platformHandler.createHandler(handler, _extends({}, options, {
1371
- isFinal: options.isFinal ? index === handlers.length - 1 : false
1372
- })));
1373
- }, []);
1374
- }
1375
-
1376
- };
1377
-
1378
- tslib.__decorate([di.Inject(), tslib.__metadata("design:type", di.InjectorService)], exports.PlatformRouter.prototype, "injector", void 0);
1379
-
1380
- exports.PlatformRouter = PlatformRouter_1 = tslib.__decorate([di.Injectable({
1381
- scope: di.ProviderScope.INSTANCE
1382
- }), tslib.__metadata("design:paramtypes", [exports.PlatformHandler])], exports.PlatformRouter);
1383
-
1384
- var PlatformApplication_1;
1385
- /**
1386
- * `PlatformApplication` is used to provide all routes collected by annotation `@Controller`.
1387
- *
1388
- * @platform
1389
- */
1390
-
1391
- exports.PlatformApplication = PlatformApplication_1 = class PlatformApplication extends exports.PlatformRouter {
1392
- constructor(platformHandler) {
1393
- super(platformHandler);
1394
- this.rawApp = this.raw = PlatformApplication_1.createRawApp();
1395
- }
1396
-
1397
- static createRawApp() {
1398
- return createFakeRawDriver();
1399
- }
1400
-
1401
- getApp() {
1402
- return this.raw;
1403
- }
1404
-
1405
- };
1406
- exports.PlatformApplication = PlatformApplication_1 = tslib.__decorate([di.Injectable({
1407
- scope: di.ProviderScope.SINGLETON
1408
- }), tslib.__metadata("design:paramtypes", [exports.PlatformHandler])], exports.PlatformApplication);
1409
-
1410
- var PlatformMulterMiddleware_1;
1411
- /**
1412
- * @middleware
1413
- */
1414
-
1415
- exports.PlatformMulterMiddleware = PlatformMulterMiddleware_1 = class PlatformMulterMiddleware {
1416
- async use(ctx) {
1417
- try {
1418
- const {
1419
- fields,
1420
- options = {}
1421
- } = ctx.endpoint.get(PlatformMulterMiddleware_1);
1422
-
1423
- const settings = _extends({}, this.settings, options);
1424
- /* istanbul ignore next */
1425
-
1426
-
1427
- if (settings.storage) {
1428
- delete settings.dest;
1429
- }
1430
-
1431
- const middleware = this.app.multer(settings).fields(this.getFields({
1432
- fields
1433
- }));
1434
- return await middleware(ctx.getRequest(), ctx.getResponse());
1435
- } catch (er) {
1436
- throw er.code ? new exceptions.Exception(er.code, `${er.message} ${er.field || ""}`.trim()) : er;
1437
- }
1438
- }
1439
-
1440
- getFields(conf) {
1441
- return conf.fields.map(({
1442
- name,
1443
- maxCount
1444
- }) => ({
1445
- name,
1446
- maxCount
1447
- }));
1448
- }
1449
-
1450
- };
1451
-
1452
- tslib.__decorate([di.Constant("multer", {}), tslib.__metadata("design:type", Object)], exports.PlatformMulterMiddleware.prototype, "settings", void 0);
1453
-
1454
- tslib.__decorate([di.Inject(), tslib.__metadata("design:type", exports.PlatformApplication)], exports.PlatformMulterMiddleware.prototype, "app", void 0);
1455
-
1456
- tslib.__decorate([tslib.__param(0, platformParams.Context()), tslib.__metadata("design:type", Function), tslib.__metadata("design:paramtypes", [Object]), tslib.__metadata("design:returntype", Promise)], exports.PlatformMulterMiddleware.prototype, "use", null);
1457
-
1458
- exports.PlatformMulterMiddleware = PlatformMulterMiddleware_1 = tslib.__decorate([platformMiddlewares.Middleware()], exports.PlatformMulterMiddleware);
1459
-
1460
- /**
1461
- * @middleware
1462
- * @platform
1463
- */
1464
-
1465
- exports.PlatformAcceptMimesMiddleware = class PlatformAcceptMimesMiddleware {
1466
- use(ctx) {
1467
- const {
1468
- endpoint,
1469
- request
1470
- } = ctx;
1471
- const mimes = core.uniq(((endpoint == null ? void 0 : endpoint.get("acceptMimes")) || []).concat(this.acceptMimes));
1472
-
1473
- if (mimes.length && !request.accepts(mimes)) {
1474
- throw new exceptions.NotAcceptable(mimes.join(", "));
1475
- }
1476
- }
1477
-
1478
- };
1479
-
1480
- tslib.__decorate([di.Constant("acceptMimes", []), tslib.__metadata("design:type", Array)], exports.PlatformAcceptMimesMiddleware.prototype, "acceptMimes", void 0);
1481
-
1482
- tslib.__decorate([tslib.__param(0, platformParams.Context()), tslib.__metadata("design:type", Function), tslib.__metadata("design:paramtypes", [Object]), tslib.__metadata("design:returntype", void 0)], exports.PlatformAcceptMimesMiddleware.prototype, "use", null);
1483
-
1484
- exports.PlatformAcceptMimesMiddleware = tslib.__decorate([platformMiddlewares.Middleware()], exports.PlatformAcceptMimesMiddleware);
1485
-
1486
- /**
1487
- * Create Ts.ED context handler
1488
- * @param fn
1489
- * @ignore
1490
- */
1491
-
1492
- function useCtxHandler(fn) {
1493
- fn.type = exports.HandlerType.CTX_FN;
1494
- return fn;
1495
- }
1496
-
1497
- /**
1498
- * @ignore
1499
- */
1500
-
1501
- function formatMethod(method) {
1502
- return (method === schema.OperationMethods.CUSTOM ? "use" : method || "use").toLowerCase();
1503
- }
1504
- /**
1505
- * @ignore
1506
- */
1507
-
1508
-
1509
- class PlatformControllerBuilder {
1510
- constructor(provider) {
1511
- this.provider = provider;
1512
- }
1513
- /**
1514
- *
1515
- * @returns {any}
1516
- */
1517
-
1518
-
1519
- build(injector) {
1520
- const {
1521
- middlewares: {
1522
- useBefore
1523
- }
1524
- } = this.provider; // Controller lifecycle
1525
-
1526
- this.buildMiddlewares(useBefore) // Controller before-middleware
1527
- .buildEndpoints() // All endpoints and his middlewares
1528
- .buildChildrenCtrls(injector); // Children controllers
1529
-
1530
- return this.provider.getRouter();
1531
- }
1532
-
1533
- buildEndpoints() {
1534
- const {
1535
- endpoints
1536
- } = this.provider;
1537
- const operationPaths = new Map();
1538
-
1539
- const getKey = (method, path) => `${method}-${path}`;
1540
-
1541
- const updateFinalRouteState = key => {
1542
- if (operationPaths.has(key)) {
1543
- operationPaths.get(key).isFinal = false;
1544
- }
1545
- };
1546
-
1547
- const setFinalRoute = (key, operationPath) => {
1548
- operationPaths.set(key, operationPath);
1549
- operationPath.isFinal = true;
1550
- };
1551
-
1552
- endpoints.forEach(({
1553
- operation
1554
- }) => {
1555
- operation == null ? void 0 : operation.operationPaths.forEach(operationPath => {
1556
- if (operationPath.method !== schema.OperationMethods.CUSTOM) {
1557
- const key = getKey(operationPath.method, operationPath.path);
1558
- updateFinalRouteState(key);
1559
- updateFinalRouteState(getKey(schema.OperationMethods.ALL, operationPath.path));
1560
- setFinalRoute(key, operationPath);
1561
- }
1562
- });
1563
- });
1564
- endpoints.forEach(endpoint => {
1565
- this.buildEndpoint(endpoint);
1566
- });
1567
- return this;
1568
- }
1569
-
1570
- buildEndpoint(endpoint) {
1571
- const {
1572
- beforeMiddlewares,
1573
- middlewares: mldwrs,
1574
- afterMiddlewares,
1575
- operation
1576
- } = endpoint;
1577
- const {
1578
- middlewares: {
1579
- use,
1580
- useAfter
1581
- }
1582
- } = this.provider;
1583
- const router = this.provider.getRouter(); // Endpoint lifecycle
1584
-
1585
- let handlers = [];
1586
- const hasFiles = [...endpoint.children.values()].find(item => item.paramType === platformParams.ParamTypes.FILES);
1587
- handlers = handlers.concat(useCtxHandler(bindEndpointMiddleware(endpoint))).concat(exports.PlatformAcceptMimesMiddleware).concat(hasFiles && exports.PlatformMulterMiddleware).concat(use) // Controller use-middlewares
1588
- .concat(beforeMiddlewares) // Endpoint before-middlewares
1589
- // .concat(endpoint.cache && PlatformCacheMiddleware)
1590
- .concat(mldwrs) // Endpoint middlewares
1591
- .concat(endpoint) // Endpoint metadata
1592
- .concat(afterMiddlewares) // Endpoint after-middlewares
1593
- .concat(useAfter) // Controller after middlewares (equivalent to afterEach)
1594
- .filter(item => !!item); // Add handlers to the router
1595
-
1596
- operation == null ? void 0 : operation.operationPaths.forEach(({
1597
- path,
1598
- method,
1599
- isFinal
1600
- }) => {
1601
- router.addRoute({
1602
- method: formatMethod(method),
1603
- path,
1604
- handlers,
1605
- isFinal
1606
- });
1607
- });
1608
-
1609
- if (!(operation != null && operation.operationPaths.size)) {
1610
- router.use(...handlers);
1611
- }
1612
- }
1613
-
1614
- buildChildrenCtrls(injector) {
1615
- const {
1616
- children
1617
- } = this.provider;
1618
- const router = this.provider.getRouter();
1619
- children.forEach(child => {
1620
- const provider = injector.getProvider(child);
1621
- /* istanbul ignore next */
1622
-
1623
- if (!provider) {
1624
- throw new Error("Controller component not found in the ControllerRegistry");
1625
- }
1626
-
1627
- new PlatformControllerBuilder(provider).build(injector);
1628
- router.use(provider.path, provider.getRouter());
1629
- });
1630
- }
1631
-
1632
- buildMiddlewares(middlewares) {
1633
- const router = this.provider.getRouter();
1634
- middlewares.filter(o => typeof o === "function").forEach(middleware => {
1635
- router.use(middleware);
1636
- });
1637
- return this;
1638
- }
1639
-
1640
- }
1641
-
1642
- /**
1643
- * Platform Request abstraction layer.
1644
- * @platform
1645
- */
1646
-
1647
- exports.PlatformRequest = class PlatformRequest {
1648
- constructor({
1649
- request
1650
- }) {
1651
- this.raw = request;
1652
- }
1653
-
1654
- get secure() {
1655
- return this.raw.secure;
1656
- }
1657
-
1658
- get host() {
1659
- return this.get("host");
1660
- }
1661
-
1662
- get protocol() {
1663
- return this.raw.protocol;
1664
- }
1665
- /**
1666
- * Get the url of the request.
1667
- *
1668
- * Is equivalent of `express.response.originalUrl || express.response.url`.
1669
- */
1670
-
1671
-
1672
- get url() {
1673
- return this.raw.originalUrl || this.raw.url;
1674
- }
1675
-
1676
- get headers() {
1677
- return this.raw.headers;
1678
- }
1679
-
1680
- get method() {
1681
- return this.raw.method;
1682
- }
1683
- /**
1684
- * Contains key-value pairs of data submitted in the request body. By default, it is `undefined`, and is populated when you use
1685
- * `body-parsing` middleware such as `express.json()` or `express.urlencoded()`.
1686
- */
1687
-
1688
-
1689
- get body() {
1690
- return this.raw.body;
1691
- }
1692
-
1693
- get rawBody() {
1694
- return this.raw.rawBody;
1695
- }
1696
- /**
1697
- * When using `cookie-parser` middleware, this property is an object that contains cookies sent by the request.
1698
- * If the request contains no cookies, it defaults to `{}`.
1699
- */
1700
-
1701
-
1702
- get cookies() {
1703
- return this.raw.cookies;
1704
- }
1705
- /**
1706
- * This property is an object containing properties mapped to the named route `parameters`.
1707
- * For example, if you have the route `/user/:name`, then the `name` property is available as `req.params.name`.
1708
- * This object defaults to `{}`.
1709
- */
1710
-
1711
-
1712
- get params() {
1713
- return this.raw.params;
1714
- }
1715
- /**
1716
- * This property is an object containing a property for each query string parameter in the route.
1717
- * When query parser is set to disabled, it is an empty object `{}`, otherwise it is the result of the configured query parser.
1718
- */
1719
-
1720
-
1721
- get query() {
1722
- return this.raw.query;
1723
- }
1724
- /**
1725
- * This property is an object containing a property for each session attributes set by any code.
1726
- * It require to install a middleware like express-session to work.
1727
- */
1728
-
1729
-
1730
- get session() {
1731
- return this.raw.session;
1732
- }
1733
-
1734
- get files() {
1735
- return this.raw.files;
1736
- }
1737
- /**
1738
- * Return the original request framework instance
1739
- */
1740
-
1741
-
1742
- get request() {
1743
- return this.getRequest();
1744
- }
1745
- /**
1746
- * Return the original request node.js instance
1747
- */
1748
-
1749
-
1750
- get req() {
1751
- return this.getReq();
1752
- }
1753
- /**
1754
- * Returns the HTTP request header specified by field. The match is case-insensitive.
1755
- *
1756
- * ```typescript
1757
- * request.get('Content-Type') // => "text/plain"
1758
- * ```
1759
- *
1760
- * @param name
1761
- */
1762
-
1763
-
1764
- get(name) {
1765
- return this.raw.get(name);
1766
- }
1767
-
1768
- accepts(mime) {
1769
- // @ts-ignore
1770
- return this.raw.accepts(mime);
1771
- }
1772
-
1773
- isAborted() {
1774
- return this.raw.aborted;
1775
- }
1776
-
1777
- destroy() {
1778
- // @ts-ignore
1779
- delete this.raw; // @ts-ignore
1780
-
1781
- delete this.response;
1782
- }
1783
- /**
1784
- * Return the Framework response object (express, koa, etc...)
1785
- */
1786
-
1787
-
1788
- getRequest() {
1789
- return this.raw;
1790
- }
1791
- /**
1792
- * Return the Node.js response object
1793
- */
1794
-
1795
-
1796
- getReq() {
1797
- return this.raw;
1798
- }
1799
-
1800
- };
1801
- exports.PlatformRequest = tslib.__decorate([di.Injectable(), di.Scope(di.ProviderScope.INSTANCE), tslib.__metadata("design:paramtypes", [Object])], exports.PlatformRequest);
1802
-
1803
- var PlatformResponse_1;
1804
-
1805
- const onFinished = require("on-finished");
1806
- /**
1807
- * Platform Response abstraction layer.
1808
- * @platform
1809
- */
1810
-
1811
-
1812
- exports.PlatformResponse = PlatformResponse_1 = class PlatformResponse {
1813
- constructor({
1814
- response
1815
- }) {
1816
- this.raw = response;
1817
- }
1818
- /**
1819
- * Get the current statusCode
1820
- */
1821
-
1822
-
1823
- get statusCode() {
1824
- return this.raw.statusCode;
1825
- }
1826
- /**
1827
- * An object that contains response local variables scoped to the request, and therefore available only to the view(s) rendered during that request / response cycle (if any). Otherwise, this property is identical to app.locals.
1828
- *
1829
- * This property is useful for exposing request-level information such as the request path name, authenticated user, user settings, and so on.
1830
- */
1831
-
1832
-
1833
- get locals() {
1834
- return this.raw.locals;
1835
- }
1836
- /**
1837
- * Return the original response framework instance
1838
- */
1839
-
1840
-
1841
- get response() {
1842
- return this.getResponse();
1843
- }
1844
- /**
1845
- * Return the original response node.js instance
1846
- */
1847
-
1848
-
1849
- get res() {
1850
- return this.getRes();
1851
- }
1852
-
1853
- static onFinished(res, cb) {
1854
- onFinished(res, cb);
1855
- }
1856
- /**
1857
- * Returns the HTTP response header specified by field. The match is case-insensitive.
1858
- *
1859
- * ```typescript
1860
- * response.get('Content-Type') // => "text/plain"
1861
- * ```
1862
- *
1863
- * @param name
1864
- */
1865
-
1866
-
1867
- get(name) {
1868
- return this.raw.get(name);
1869
- }
1870
-
1871
- getHeaders() {
1872
- return this.raw.getHeaders();
1873
- }
1874
- /**
1875
- * Return the Framework response object (express, koa, etc...)
1876
- */
1877
-
1878
-
1879
- getResponse() {
1880
- return this.raw;
1881
- }
1882
- /**
1883
- * Return the Node.js response object
1884
- */
1885
-
1886
-
1887
- getRes() {
1888
- return this.raw;
1889
- }
1890
-
1891
- hasStatus() {
1892
- return this.statusCode !== 200;
1893
- }
1894
- /**
1895
- * Sets the HTTP status for the response.
1896
- *
1897
- * @param status
1898
- */
1899
-
1900
-
1901
- status(status) {
1902
- this.raw.status(status);
1903
- return this;
1904
- }
1905
- /**
1906
- * Set header `field` to `val`, or pass
1907
- * an object of header fields.
1908
- *
1909
- * Examples:
1910
- * ```typescript
1911
- * response.setHeaders({ Accept: 'text/plain', 'X-API-Key': 'tobi' });
1912
- * ```
1913
- *
1914
- * Aliased as `res.header()`.
1915
- */
1916
-
1917
-
1918
- setHeaders(headers) {
1919
- // apply headers
1920
- Object.entries(headers).forEach(([key, item]) => {
1921
- this.setHeader(key, item);
1922
- });
1923
- return this;
1924
- }
1925
-
1926
- setHeader(key, item) {
1927
- if (key.toLowerCase() === "location") {
1928
- return this.location(String(item));
1929
- }
1930
-
1931
- this.raw.set(key, item);
1932
- return this;
1933
- }
1934
- /**
1935
- * Set `Content-Type` response header with `type` through `mime.lookup()`
1936
- * when it does not contain "/", or set the Content-Type to `type` otherwise.
1937
- *
1938
- * Examples:
1939
- *
1940
- * res.type('.html');
1941
- * res.type('html');
1942
- * res.type('json');
1943
- * res.type('application/json');
1944
- * res.type('png');
1945
- */
1946
-
1947
-
1948
- contentType(contentType) {
1949
- this.raw.contentType(contentType);
1950
- return this;
1951
- }
1952
-
1953
- contentLength(length) {
1954
- this.setHeader("Content-Length", length);
1955
- return this;
1956
- }
1957
-
1958
- getContentLength() {
1959
- if (this.get("Content-Length")) {
1960
- return parseInt(this.get("Content-Length"), 10) || 0;
1961
- }
1962
- }
1963
-
1964
- getContentType() {
1965
- return (this.get("Content-Type") || "").split(";")[0];
1966
- }
1967
- /**
1968
- * Sets the HTTP response Content-Disposition header field to “attachment”.
1969
- * If a filename is given, then it sets the Content-Type based on the extension name via res.type(), and sets the Content-Disposition “filename=” parameter.
1970
- *
1971
- * ```typescript
1972
- * res.attachment()
1973
- * // Content-Disposition: attachment
1974
- *
1975
- * res.attachment('path/to/logo.png')
1976
- * // Content-Disposition: attachment; filename="logo.png"
1977
- * // Content-Type: image/png
1978
- * ```
1979
- *
1980
- * @param filename
1981
- */
1982
-
1983
-
1984
- attachment(filename) {
1985
- this.raw.attachment(filename);
1986
- return this;
1987
- }
1988
- /**
1989
- * Redirects to the URL derived from the specified path, with specified status, a positive integer that corresponds to an [HTTP status code](http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html).
1990
- * If not specified, status defaults to `302 Found`.
1991
- *
1992
- * @param status
1993
- * @param url
1994
- */
1995
-
1996
-
1997
- redirect(status, url) {
1998
- this.raw.redirect(status, url);
1999
- return this;
2000
- }
2001
- /**
2002
- * Sets the response Location HTTP header to the specified path parameter.
2003
- *
2004
- * @param location
2005
- */
2006
-
2007
-
2008
- location(location) {
2009
- this.raw.location(location);
2010
- return this;
2011
- }
2012
- /**
2013
- * Stream the given data.
2014
- *
2015
- * @param data
2016
- */
2017
-
2018
-
2019
- stream(data) {
2020
- data.pipe(this.raw);
2021
- return this;
2022
- }
2023
- /**
2024
- * Renders a view and sends the rendered HTML string to the client.
2025
- *
2026
- * @param path
2027
- * @param options
2028
- */
2029
-
2030
-
2031
- async render(path, options = {}) {
2032
- return this.platformViews.render(path, _extends({}, this.locals, options));
2033
- }
2034
- /**
2035
- * Send any data to your consumer.
2036
- *
2037
- * This method accept a ReadableStream, a plain object, boolean, string, number, null and undefined data.
2038
- * It choose the better way to send the data.
2039
- *
2040
- * @param data
2041
- */
2042
-
2043
-
2044
- body(data) {
2045
- this.data = data;
2046
-
2047
- if (data === undefined) {
2048
- this.raw.send();
2049
- return this;
2050
- }
2051
-
2052
- if (core.isStream(data)) {
2053
- this.stream(data);
2054
- return this;
2055
- }
2056
-
2057
- if (Buffer.isBuffer(data)) {
2058
- if (!this.getContentType()) {
2059
- this.contentType("application/octet-stream");
2060
- }
2061
-
2062
- this.contentLength(data.length);
2063
- this.raw.send(data);
2064
- return this;
2065
- }
2066
-
2067
- if (core.isBoolean(data) || core.isNumber(data) || core.isString(data) || data === null) {
2068
- this.raw.send(data);
2069
- return this;
2070
- }
2071
-
2072
- this.raw.json(data);
2073
- return this;
2074
- }
2075
-
2076
- getBody() {
2077
- return this.data;
2078
- }
2079
- /**
2080
- * Add a listener to handler the end of the request/response.
2081
- * @param cb
2082
- */
2083
-
2084
-
2085
- onEnd(cb) {
2086
- PlatformResponse_1.onFinished(this.getRes(), cb);
2087
- return this;
2088
- }
2089
-
2090
- isDone() {
2091
- if (!this.raw) {
2092
- return true;
2093
- }
2094
-
2095
- const res = this.getRes();
2096
- return Boolean(this.isHeadersSent() || res.writableEnded || res.writableFinished);
2097
- }
2098
-
2099
- destroy() {
2100
- // @ts-ignore
2101
- delete this.raw;
2102
- delete this.data; // @ts-ignore
2103
-
2104
- delete this.request;
2105
- }
2106
-
2107
- isHeadersSent() {
2108
- return this.getRes().headersSent;
2109
- }
2110
-
2111
- };
2112
- exports.PlatformResponse = PlatformResponse_1 = tslib.__decorate([di.Injectable(), di.Scope(di.ProviderScope.INSTANCE), tslib.__metadata("design:paramtypes", [Object])], exports.PlatformResponse);
2113
-
2114
- const _excluded$3 = ["event", "endpoint", "ignoreUrlPatterns", "ResponseKlass", "RequestKlass"];
2115
-
2116
- var _ignoreUrlPatterns = /*#__PURE__*/_classPrivateFieldLooseKey("ignoreUrlPatterns");
2117
-
2118
- class PlatformContext extends di.DIContext {
2119
- constructor(_ref) {
2120
- let {
2121
- event,
2122
- endpoint,
2123
- ignoreUrlPatterns = [],
2124
- ResponseKlass = exports.PlatformResponse,
2125
- RequestKlass = exports.PlatformRequest
2126
- } = _ref,
2127
- options = _objectWithoutPropertiesLoose(_ref, _excluded$3);
2128
-
2129
- super(_extends({}, options, {
2130
- ignoreLog: () => {
2131
- return _classPrivateFieldLooseBase(this, _ignoreUrlPatterns)[_ignoreUrlPatterns].find(reg => !!this.url.match(reg));
2132
- }
2133
- }));
2134
- Object.defineProperty(this, _ignoreUrlPatterns, {
2135
- writable: true,
2136
- value: void 0
2137
- });
2138
- _classPrivateFieldLooseBase(this, _ignoreUrlPatterns)[_ignoreUrlPatterns] = [];
2139
- endpoint && (this.endpoint = endpoint);
2140
- _classPrivateFieldLooseBase(this, _ignoreUrlPatterns)[_ignoreUrlPatterns] = ignoreUrlPatterns.map(pattern => typeof pattern === "string" ? new RegExp(pattern, "gi") : pattern);
2141
- this.response = new ResponseKlass(event);
2142
- this.request = new RequestKlass(event);
2143
- this.response.request = this.request;
2144
- this.request.response = this.response;
2145
- this.request.request.$ctx = this;
2146
- this.request.request.id = this.id;
2147
- this.logger.url = this.url;
2148
- this.container.set(exports.PlatformResponse, this.response);
2149
- this.container.set(exports.PlatformRequest, this.request);
2150
- this.container.set(PlatformContext, this);
2151
- this.response.setHeader("x-request-id", this.id);
2152
- }
2153
-
2154
- get url() {
2155
- return this.request.url;
2156
- }
2157
-
2158
- get app() {
2159
- return this.injector.get(exports.PlatformApplication);
2160
- }
2161
-
2162
- async destroy() {
2163
- var _this$request, _this$request$request;
2164
-
2165
- await super.destroy();
2166
- (_this$request = this.request) == null ? true : (_this$request$request = _this$request.request) == null ? true : delete _this$request$request.$ctx;
2167
- this.response.destroy();
2168
- this.request.destroy(); // @ts-ignore
2169
-
2170
- delete this.endpoint; // @ts-ignore
2171
-
2172
- delete this.response; // @ts-ignore
2173
-
2174
- delete this.request;
2175
- }
2176
-
2177
- isDone() {
2178
- return !this.request || !this.response;
2179
- }
2180
- /**
2181
- * Return the framework request instance (Express, Koa, etc...)
2182
- */
2183
-
2184
-
2185
- getRequest() {
2186
- return this.request.getRequest();
2187
- }
2188
- /**
2189
- * Return the framework response instance (Express, Koa, etc...)
2190
- */
2191
-
2192
-
2193
- getResponse() {
2194
- return this.response.getResponse();
2195
- }
2196
- /**
2197
- * Get Node.js request
2198
- */
2199
-
2200
-
2201
- getReq() {
2202
- return this.request.getReq();
2203
- }
2204
- /**
2205
- * Get Node.js response
2206
- */
2207
-
2208
-
2209
- getRes() {
2210
- return this.response.getRes();
2211
- }
2212
- /**
2213
- * Return the original application instance.
2214
- */
2215
-
2216
-
2217
- getApp() {
2218
- return this.app.getApp();
2219
- }
2220
-
2221
- }
2222
-
2223
- class PlatformRouteDetails {
2224
- constructor({
2225
- provider,
2226
- endpoint,
2227
- method,
2228
- url
2229
- }) {
2230
- this.provider = provider;
2231
- this.endpoint = endpoint;
2232
- this.method = method;
2233
- this.url = url;
2234
- this.rawBody = !!endpoint.params.find(param => param.paramType === platformParams.ParamTypes.RAW_BODY);
2235
- }
2236
-
2237
- get name() {
2238
- return `${this.endpoint.targetName}.${this.methodClassName}()`;
2239
- }
2240
-
2241
- get className() {
2242
- return this.endpoint.targetName;
2243
- }
2244
-
2245
- get methodClassName() {
2246
- return String(this.endpoint.propertyKey);
2247
- }
2248
-
2249
- get parameters() {
2250
- return this.endpoint.params;
2251
- }
2252
-
2253
- toJSON() {
2254
- return {
2255
- method: this.method,
2256
- name: this.name,
2257
- url: this.url,
2258
- className: this.className,
2259
- methodClassName: this.methodClassName,
2260
- parameters: this.parameters,
2261
- rawBody: this.rawBody
2262
- };
2263
- }
2264
-
2265
- }
2266
-
2267
- const ROUTER_OPTIONS = Symbol.for("ROUTER_OPTIONS");
2268
-
2269
- class ControllerProvider extends di.Provider {
2270
- constructor(provide, options = {}) {
2271
- super(provide, options);
2272
- this.type = di.ProviderType.CONTROLLER;
2273
- this.entity = schema.JsonEntityStore.from(provide);
2274
- }
2275
-
2276
- get path() {
2277
- return this.entity.path;
2278
- }
2279
-
2280
- set path(path) {
2281
- this.entity.path = path;
2282
- }
2283
- /**
2284
- *
2285
- * @returns {EndpointMetadata[]}
2286
- */
2287
-
2288
-
2289
- get endpoints() {
2290
- return exports.EndpointMetadata.getEndpoints(this.provide);
2291
- }
2292
-
2293
- get children() {
2294
- return this.store.get("childrenControllers", []);
2295
- }
2296
- /**
2297
- *
2298
- * @returns {ControllerProvider}
2299
- */
2300
-
2301
-
2302
- get parent() {
2303
- return this.store.get("parentController");
2304
- }
2305
- /**
2306
- *
2307
- */
2308
-
2309
-
2310
- get routerOptions() {
2311
- return this.store.get(ROUTER_OPTIONS) || {};
2312
- }
2313
- /**
2314
- *
2315
- * @param value
2316
- */
2317
-
2318
-
2319
- set routerOptions(value) {
2320
- this.store.set(ROUTER_OPTIONS, value);
2321
- }
2322
- /**
2323
- *
2324
- * @returns {any[]}
2325
- */
2326
-
2327
-
2328
- get middlewares() {
2329
- return Object.assign({
2330
- use: [],
2331
- useAfter: [],
2332
- useBefore: []
2333
- }, this.store.get("middlewares", {}));
2334
- }
2335
- /**
2336
- *
2337
- * @param middlewares
2338
- */
2339
-
2340
-
2341
- set middlewares(middlewares) {
2342
- const mdlwrs = this.middlewares;
2343
-
2344
- const concat = (key, a, b) => a[key] = a[key].concat(b[key]);
2345
-
2346
- Object.keys(middlewares).forEach(key => {
2347
- concat(key, mdlwrs, middlewares);
2348
- });
2349
- this.store.set("middlewares", mdlwrs);
2350
- }
2351
- /**
2352
- *
2353
- * @returns {boolean}
2354
- */
2355
-
2356
-
2357
- hasChildren() {
2358
- return !!this.children.length;
2359
- }
2360
- /**
2361
- *
2362
- * @returns {boolean}
2363
- */
2364
-
2365
-
2366
- hasParent() {
2367
- return !!this.store.get("parentController");
2368
- }
2369
-
2370
- getRouter() {
2371
- return this.router;
2372
- }
2373
-
2374
- setRouter(router) {
2375
- this.router = router;
2376
- return this;
2377
- }
2378
-
2379
- }
2380
-
2381
- function getControllerPath(basePath, provider) {
2382
- return (basePath === provider.path ? provider.path : (basePath || "") + provider.path).replace(/\/\//gi, "/");
2383
- }
2384
-
2385
- var _routes, _controllers;
2386
- /**
2387
- * `Platform` is used to provide all routes collected by annotation `@Controller`.
2388
- *
2389
- * @platform
2390
- */
2391
-
2392
- exports.Platform = (_routes = /*#__PURE__*/_classPrivateFieldLooseKey("routes"), _controllers = /*#__PURE__*/_classPrivateFieldLooseKey("controllers"), class Platform {
2393
- constructor(injector, platformApplication) {
2394
- Object.defineProperty(this, _routes, {
2395
- writable: true,
2396
- value: void 0
2397
- });
2398
- Object.defineProperty(this, _controllers, {
2399
- writable: true,
2400
- value: void 0
2401
- });
2402
- this.injector = injector;
2403
- this.platformApplication = platformApplication;
2404
- _classPrivateFieldLooseBase(this, _routes)[_routes] = [];
2405
- _classPrivateFieldLooseBase(this, _controllers)[_controllers] = [];
2406
- }
2407
-
2408
- get app() {
2409
- return this.platformApplication;
2410
- }
2411
-
2412
- get routes() {
2413
- return _classPrivateFieldLooseBase(this, _routes)[_routes];
2414
- }
2415
-
2416
- addRoutes(routes) {
2417
- routes.forEach(routeSettings => {
2418
- this.addRoute(routeSettings.route, routeSettings.token);
2419
- });
2420
- }
2421
-
2422
- addRoute(endpoint, token) {
2423
- const {
2424
- injector
2425
- } = this;
2426
-
2427
- if (injector.hasProvider(token)) {
2428
- const provider = injector.getProvider(token);
2429
-
2430
- if (provider.type === di.ProviderType.CONTROLLER) {
2431
- const route = getControllerPath(endpoint, provider);
2432
-
2433
- if (!provider.hasParent()) {
2434
- const routes = this.buildRoutes(route, provider);
2435
-
2436
- _classPrivateFieldLooseBase(this, _routes)[_routes].push(...routes);
2437
-
2438
- _classPrivateFieldLooseBase(this, _controllers)[_controllers].push({
2439
- route,
2440
- provider
2441
- });
2442
-
2443
- this.app.use(route, ...[].concat(provider.getRouter().callback()));
2444
- }
2445
- }
2446
- }
2447
-
2448
- return this;
2449
- }
2450
- /**
2451
- * Get all routes built by TsExpressDecorators and mounted on Express application.
2452
- * @returns {PlatformRouteDetails[]}
2453
- */
2454
-
2455
-
2456
- getRoutes() {
2457
- return _classPrivateFieldLooseBase(this, _routes)[_routes];
2458
- }
2459
-
2460
- getMountedControllers() {
2461
- return _classPrivateFieldLooseBase(this, _controllers)[_controllers];
2462
- }
2463
- /**
2464
- *
2465
- * @param ctrl
2466
- * @param endpointUrl
2467
- */
2468
-
2469
-
2470
- buildRoutes(endpointUrl, ctrl) {
2471
- const {
2472
- injector
2473
- } = this;
2474
- let routes = [];
2475
- routes = ctrl.children.map(ctrl => injector.getProvider(ctrl)).reduce((routes, provider) => {
2476
- return routes.concat(this.buildRoutes(`${endpointUrl}${provider.path}`, provider));
2477
- }, routes);
2478
- ctrl.endpoints.forEach(endpoint => {
2479
- endpoint.operationPaths.forEach(({
2480
- path,
2481
- method
2482
- }) => {
2483
- if (method) {
2484
- routes.push(new PlatformRouteDetails({
2485
- provider: ctrl,
2486
- endpoint,
2487
- method,
2488
- url: `${endpointUrl}${path || ""}`.replace(/\/\//gi, "/")
2489
- }));
2490
- }
2491
- });
2492
- });
2493
- return routes;
2494
- }
2495
-
2496
- });
2497
- exports.Platform = tslib.__decorate([di.Injectable({
2498
- scope: di.ProviderScope.SINGLETON
2499
- }), tslib.__metadata("design:paramtypes", [di.InjectorService, exports.PlatformApplication])], exports.Platform);
2500
-
2501
- /**
2502
- * @ignore
2503
- */
2504
-
2505
- exports.PlatformModule = class PlatformModule {
2506
- constructor(injector, platform) {
2507
- this.injector = injector;
2508
- this.platform = platform;
2509
- this.createRoutersFromControllers();
2510
- }
2511
- /**
2512
- * Create routers from the collected controllers
2513
- */
2514
-
2515
-
2516
- createRoutersFromControllers() {
2517
- const {
2518
- injector
2519
- } = this;
2520
- return injector.getProviders(di.ProviderType.CONTROLLER).map(provider => {
2521
- provider.setRouter(exports.PlatformRouter.create(injector, provider.routerOptions));
2522
-
2523
- if (!provider.hasParent()) {
2524
- return new PlatformControllerBuilder(provider).build(injector);
2525
- }
2526
- }).filter(Boolean);
2527
- }
2528
-
2529
- $$loadRoutes() {
2530
- const routes = this.injector.settings.get("routes");
2531
- this.platform.addRoutes(routes);
2532
- }
2533
-
2534
- };
2535
- exports.PlatformModule = tslib.__decorate([di.Module({
2536
- imports: [di.InjectorService, exports.ConverterService, exports.Platform]
2537
- }), tslib.__metadata("design:paramtypes", [di.InjectorService, exports.Platform])], exports.PlatformModule);
2538
-
2539
- logger.$log.name = "TSED";
2540
- function createInjector(settings = {}) {
2541
- const injector = new di.InjectorService();
2542
- injector.settings = createSettingsService(injector);
2543
- injector.logger = logger.$log;
2544
- injector.settings.set(settings);
2545
- di.setLoggerLevel(injector);
2546
- return injector;
2547
- }
2548
-
2549
- function createSettingsService(injector) {
2550
- const provider = di.GlobalProviders.get(exports.PlatformConfiguration).clone();
2551
- provider.instance = injector.invoke(provider.useClass);
2552
- injector.addProvider(exports.PlatformConfiguration, provider);
2553
- return provider.instance;
2554
- }
2555
-
2556
- function createPlatformApplication(injector) {
2557
- injector.forkProvider(exports.PlatformApplication);
2558
- }
2559
-
2560
- /**
2561
- * Inject the Http.Server instance.
2562
- *
2563
- * ### Example
2564
- *
2565
- * ```typescript
2566
- * import {HttpServer, Service} from "@tsed/common";
2567
- *
2568
- * @Service()
2569
- * export default class OtherService {
2570
- * constructor(@HttpServer httpServer: HttpServer) {}
2571
- * }
2572
- * ```
2573
- *
2574
- * > Note: TypeScript transform and store `HttpServer` as `Function` type in the metadata. So to inject a factory, you must use the `@Inject(type)` decorator.
2575
- *
2576
- * @param {Type<any>} target
2577
- * @param {string} targetKey
2578
- * @param {TypedPropertyDescriptor<Function> | number} descriptor
2579
- * @returns {any}
2580
- * @decorator
2581
- */
2582
-
2583
- function HttpServer(target, targetKey, descriptor) {
2584
- return di.Inject(HttpServer)(target, targetKey, descriptor);
2585
- }
2586
-
2587
- function listenServer(http, settings) {
2588
- const {
2589
- address,
2590
- port
2591
- } = settings;
2592
- const promise = new Promise((resolve, reject) => {
2593
- http.on("listening", resolve);
2594
- http.on("error", reject);
2595
- }).then(() => {
2596
- const port = http.address().port;
2597
- return {
2598
- address: settings.address,
2599
- port
2600
- };
2601
- });
2602
- http.listen(port, address);
2603
- return promise;
2604
- }
2605
-
2606
- function createHttpServer(injector) {
2607
- injector.forkProvider(HttpServer);
2608
- }
2609
- di.registerProvider({
2610
- provide: HttpServer,
2611
- deps: [exports.PlatformApplication],
2612
- scope: di.ProviderScope.SINGLETON,
2613
- global: true,
2614
-
2615
- useFactory(platformApplication) {
2616
- return Http__default['default'].createServer(platformApplication.callback());
2617
- }
2618
-
2619
- });
2620
- async function listenHttpServer(injector) {
2621
- const {
2622
- settings
2623
- } = injector;
2624
- const server = injector.get(HttpServer);
2625
-
2626
- if (settings.httpPort !== false && server) {
2627
- const {
2628
- address,
2629
- port
2630
- } = settings.getHttpPort();
2631
- injector.logger.debug(`Start server on http://${address}:${port}`);
2632
- const options = await listenServer(server, {
2633
- address,
2634
- port
2635
- });
2636
- settings.setHttpPort(options);
2637
- injector.logger.info(`Listen server on http://${options.address}:${options.port}`);
2638
- }
2639
- }
2640
-
2641
- /**
2642
- * Inject the Https.Server instance.
2643
- *
2644
- * ### Example
2645
- *
2646
- * ```typescript
2647
- * import {HttpsServer, Service} from "@tsed/common";
2648
- *
2649
- * @Service()
2650
- * export default class OtherService {
2651
- * constructor(@HttpsServer httpServer: HttpServer) {}
2652
- * }
2653
- * ```
2654
- *
2655
- * > Note: TypeScript transform and store `HttpsServer` as `Function` type in the metadata. So to inject a factory, you must use the `@Inject(type)` decorator.
2656
- *
2657
- * @param {Type<any>} target
2658
- * @param {string} targetKey
2659
- * @param {TypedPropertyDescriptor<Function> | number} descriptor
2660
- * @returns {any}
2661
- * @decorator
2662
- */
2663
-
2664
- function HttpsServer(target, targetKey, descriptor) {
2665
- return di.Inject(HttpsServer)(target, targetKey, descriptor);
2666
- }
2667
-
2668
- function createHttpsServer(injector) {
2669
- injector.forkProvider(HttpsServer);
2670
- }
2671
- di.registerProvider({
2672
- provide: HttpsServer,
2673
- deps: [exports.PlatformApplication, di.Configuration],
2674
- scope: di.ProviderScope.SINGLETON,
2675
- global: true,
2676
-
2677
- useFactory(platformApplication, settings) {
2678
- const options = settings.httpsOptions;
2679
- return Https__default['default'].createServer(options, platformApplication.callback());
2680
- }
2681
-
2682
- });
2683
- async function listenHttpsServer(injector) {
2684
- const {
2685
- settings
2686
- } = injector;
2687
- const server = injector.get(HttpsServer);
2688
-
2689
- if (settings.httpsPort !== false && server) {
2690
- const {
2691
- address,
2692
- port
2693
- } = settings.getHttpsPort();
2694
- injector.logger.debug(`Start server on https://${address}:${port}`);
2695
- const options = await listenServer(server, {
2696
- address,
2697
- port
2698
- });
2699
- settings.setHttpsPort(options);
2700
- injector.logger.info(`Listen server on https://${options.address}:${options.port}`);
2701
- }
2702
- }
2703
-
2704
- function printRoutes(routes) {
2705
- const mapColor = {
2706
- GET: "green",
2707
- POST: "yellow",
2708
- PUT: "blue",
2709
- DELETE: "red",
2710
- PATCH: "magenta",
2711
- ALL: "cyan"
2712
- };
2713
- const list = routes.map(route => {
2714
- const obj = route.toJSON();
2715
- const method = obj.method.toUpperCase();
2716
- obj.method = {
2717
- length: method.length,
2718
- toString: () => {
2719
- return logger.colorize(method, mapColor[method]);
2720
- }
2721
- };
2722
- return obj;
2723
- });
2724
- const str = logger.$log.drawTable(list, {
2725
- padding: 1,
2726
- header: {
2727
- method: "Method",
2728
- url: "Endpoint",
2729
- name: "Class method"
2730
- }
2731
- });
2732
- return "\n" + str.trim();
2733
- }
2734
-
2735
- const _excluded$2 = ["reqIdBuilder"];
2736
-
2737
- const uuidv4 = require("uuid").v4;
2738
-
2739
- const defaultReqIdBuilder = req => req.get("x-request-id") || uuidv4().replace(/-/gi, "");
2740
- /**
2741
- * Create the TsED context to wrap request, response, injector, etc...
2742
- * @param injector
2743
- * @ignore
2744
- */
2745
-
2746
-
2747
- function createContext(injector) {
2748
- var _injector$getProvider, _injector$getProvider2;
2749
-
2750
- const ResponseKlass = (_injector$getProvider = injector.getProvider(exports.PlatformResponse)) == null ? void 0 : _injector$getProvider.useClass;
2751
- const RequestKlass = (_injector$getProvider2 = injector.getProvider(exports.PlatformRequest)) == null ? void 0 : _injector$getProvider2.useClass;
2752
- const platformViews$1 = injector.get(platformViews.PlatformViews);
2753
-
2754
- const _injector$settings$lo = injector.settings.logger,
2755
- {
2756
- reqIdBuilder = defaultReqIdBuilder
2757
- } = _injector$settings$lo,
2758
- loggerOptions = _objectWithoutPropertiesLoose(_injector$settings$lo, _excluded$2);
2759
-
2760
- return async event => {
2761
- const ctx = new PlatformContext(_extends({
2762
- event,
2763
- id: reqIdBuilder(event.request),
2764
- logger: injector.logger
2765
- }, loggerOptions, {
2766
- injector,
2767
- ResponseKlass,
2768
- RequestKlass
2769
- }));
2770
- ctx.response.platformViews = platformViews$1;
2771
- ctx.response.onEnd(async () => {
2772
- await ctx.emit("$onResponse", ctx);
2773
- await ctx.destroy();
2774
- });
2775
- await ctx.emit("$onRequest", ctx);
2776
- return ctx;
2777
- };
2778
- }
2779
-
2780
- const SKIP_HOOKS = ["$beforeInit", "$afterInit", "$onInit", "$onMountingMiddlewares"];
2781
- const {
2782
- bind,
2783
- start,
2784
- end,
2785
- log
2786
- } = perf.PerfLogger.get("bootstrap");
2787
- /**
2788
- * @platform
2789
- */
2790
-
2791
- var _rootModule = /*#__PURE__*/_classPrivateFieldLooseKey("rootModule");
2792
-
2793
- var _injector = /*#__PURE__*/_classPrivateFieldLooseKey("injector");
2794
-
2795
- var _providers = /*#__PURE__*/_classPrivateFieldLooseKey("providers");
2796
-
2797
- class PlatformBuilder {
2798
- constructor({
2799
- name,
2800
- providers
2801
- }) {
2802
- Object.defineProperty(this, _rootModule, {
2803
- writable: true,
2804
- value: void 0
2805
- });
2806
- Object.defineProperty(this, _injector, {
2807
- writable: true,
2808
- value: void 0
2809
- });
2810
- Object.defineProperty(this, _providers, {
2811
- writable: true,
2812
- value: void 0
2813
- });
2814
- this.name = "";
2815
- this.startedAt = new Date();
2816
- this.name = name;
2817
- _classPrivateFieldLooseBase(this, _providers)[_providers] = core.toMap(providers, "provide");
2818
- this.locals = new di.Container();
2819
- this.useProvider(exports.PlatformHandler, _classPrivateFieldLooseBase(this, _providers)[_providers].get(exports.PlatformHandler)).useProvider(exports.PlatformResponse, _classPrivateFieldLooseBase(this, _providers)[_providers].get(exports.PlatformResponse)).useProvider(exports.PlatformRequest, _classPrivateFieldLooseBase(this, _providers)[_providers].get(exports.PlatformRequest)).useProvider(exports.PlatformRouter, _classPrivateFieldLooseBase(this, _providers)[_providers].get(exports.PlatformRouter)).useProvider(exports.PlatformApplication, _classPrivateFieldLooseBase(this, _providers)[_providers].get(exports.PlatformApplication)).useProvider(exports.Platform, _classPrivateFieldLooseBase(this, _providers)[_providers].get(exports.Platform));
2820
- }
2821
-
2822
- get injector() {
2823
- return _classPrivateFieldLooseBase(this, _injector)[_injector];
2824
- }
2825
-
2826
- get rootModule() {
2827
- return _classPrivateFieldLooseBase(this, _rootModule)[_rootModule];
2828
- }
2829
-
2830
- get app() {
2831
- return this.injector.get(exports.PlatformApplication);
2832
- }
2833
-
2834
- get platform() {
2835
- return this.injector.get(exports.Platform);
2836
- }
2837
- /**
2838
- * Return the settings configured by the decorator @@Configuration@@.
2839
- *
2840
- * ```typescript
2841
- * @Configuration({
2842
- * rootDir: Path.resolve(__dirname),
2843
- * port: 8000,
2844
- * httpsPort: 8080,
2845
- * mount: {
2846
- * "/rest": "${rootDir}/controllers/**\/*.js"
2847
- * }
2848
- * })
2849
- * export class Server {
2850
- * $onInit(){
2851
- * console.log(this.settings); // {rootDir, port, httpsPort,...}
2852
- * }
2853
- * }
2854
- * ```
2855
- *
2856
- * @returns {PlatformConfiguration}
2857
- */
2858
-
2859
-
2860
- get settings() {
2861
- return this.injector.settings;
2862
- }
2863
-
2864
- get logger() {
2865
- return this.injector.logger;
2866
- }
2867
-
2868
- get disableBootstrapLog() {
2869
- return this.settings.logger.disableBootstrapLog;
2870
- }
2871
-
2872
- static build(platformBuildClass) {
2873
- return new platformBuildClass({
2874
- name: core.nameOf(platformBuildClass).replace("Platform", "").toLowerCase(),
2875
- providers: platformBuildClass.providers
2876
- });
2877
- }
2878
-
2879
- log(...data) {
2880
- return this.disableBootstrapLog && this.logger.info(...data);
2881
- }
2882
- /**
2883
- * Add classes to the components list
2884
- * @param classes
2885
- */
2886
-
2887
-
2888
- addComponents(classes) {
2889
- this.settings.componentsScan = this.settings.componentsScan.concat(classes);
2890
- return this;
2891
- }
2892
- /**
2893
- * Add classes decorated by @@Controller@@ to components container.
2894
- *
2895
- * ### Example
2896
- *
2897
- * ```typescript
2898
- * @Controller('/ctrl')
2899
- * class MyController{
2900
- * }
2901
- *
2902
- * platform.addControllers('/rest', [MyController])
2903
- * ```
2904
- *
2905
- * ::: tip
2906
- * If the MyController class isn't decorated, the class will be ignored.
2907
- * :::
2908
- *
2909
- * @param {string} endpoint
2910
- * @param {any[]} controllers
2911
- */
2912
-
2913
-
2914
- addControllers(endpoint, controllers) {
2915
- this.settings.mount[endpoint] = (this.settings.mount[endpoint] || []).concat(controllers);
2916
- }
2917
-
2918
- async runLifecycle() {
2919
- di.setLoggerLevel(this.injector);
2920
- await this.importProviders();
2921
- await this.loadInjector();
2922
- this.useContext();
2923
- this.useRouter();
2924
- await this.loadRoutes();
2925
- await this.logRoutes();
2926
- }
2927
-
2928
- async loadInjector() {
2929
- const {
2930
- injector
2931
- } = this;
2932
- await this.callHook("$beforeInit");
2933
- this.log("Build providers");
2934
- const container = di.createContainer(core.constructorOf(this.rootModule));
2935
- await injector.load(container, exports.PlatformModule);
2936
- this.log("Settings and injector loaded");
2937
- await this.callHook("$afterInit");
2938
- }
2939
-
2940
- async listen() {
2941
- await this.callHook("$beforeListen");
2942
- await this.listenServers();
2943
- await this.callHook("$afterListen");
2944
- await this.ready();
2945
- end();
2946
- }
2947
-
2948
- async stop() {
2949
- await this.callHook("$onDestroy");
2950
- return this.injector.destroy();
2951
- }
2952
-
2953
- async ready() {
2954
- const {
2955
- startedAt
2956
- } = this;
2957
- await this.callHook("$onReady");
2958
- await this.injector.emit("$onServerReady");
2959
- this.log(`Started in ${new Date().getTime() - startedAt.getTime()} ms`);
2960
- }
2961
-
2962
- async callHook(hook, ...args) {
2963
- const {
2964
- injector,
2965
- rootModule
2966
- } = this;
2967
- log(hook);
2968
-
2969
- if (!injector.settings.logger.disableBootstrapLog) {
2970
- injector.logger.info(`\x1B[1mCall hook ${hook}\x1B[22m`);
2971
- } // call hook for the Server
2972
-
2973
-
2974
- if (hook in rootModule) {
2975
- await rootModule[hook](...args);
2976
- } // Load middlewares for the given hook
2977
-
2978
-
2979
- this.loadMiddlewaresFor(hook); // call hooks added by providers
2980
-
2981
- if (!SKIP_HOOKS.includes(hook)) {
2982
- await injector.emit(hook);
2983
- }
2984
- }
2985
-
2986
- async loadStatics() {
2987
- const {
2988
- settings
2989
- } = this;
2990
-
2991
- if (settings.statics) {
2992
- Object.entries(settings.statics).forEach(([path, items]) => {
2993
- [].concat(items).forEach(options => {
2994
- const opts = typeof options === "string" ? {
2995
- root: options
2996
- } : options;
2997
- this.platform.app.statics(path, opts);
2998
- });
2999
- });
3000
- }
3001
- }
3002
-
3003
- useProvider(token, settings) {
3004
- this.locals.addProvider(token, settings);
3005
- return this;
3006
- }
3007
-
3008
- async importProviders() {
3009
- this.injector.logger.debug("Scan components");
3010
- const providers = await componentsScan.importProviders(this.injector.settings, ["imports", "mount", "componentsScan"]);
3011
- const routes = providers.filter(provider => !!provider.route).map(({
3012
- route,
3013
- token
3014
- }) => ({
3015
- route,
3016
- token
3017
- }));
3018
- this.settings.set("routes", routes);
3019
- }
3020
- /**
3021
- * Load middlewares from configuration for the given hook
3022
- * @param hook
3023
- * @protected
3024
- */
3025
-
3026
-
3027
- loadMiddlewaresFor(hook) {
3028
- return platformMiddlewares.getMiddlewaresForHook(hook, this.settings, "$beforeRoutesInit").forEach(({
3029
- use
3030
- }) => {
3031
- this.app.use(use);
3032
- });
3033
- }
3034
-
3035
- useRouter() {
3036
- return this;
3037
- }
3038
-
3039
- useContext() {
3040
- return this;
3041
- }
3042
-
3043
- async bootstrap(module, settings = {}) {
3044
- var _settings$logger;
3045
-
3046
- // istanbul ignore next
3047
- if ((_settings$logger = settings.logger) != null && _settings$logger.perf) {
3048
- start();
3049
- bind(this);
3050
- settings.logger = _extends({}, settings.logger, {
3051
- level: "off"
3052
- });
3053
- }
3054
-
3055
- this.createInjector(module, _extends({}, settings, {
3056
- PLATFORM_NAME: this.name
3057
- }));
3058
- this.createRootModule(module);
3059
- await this.runLifecycle();
3060
- return this;
3061
- }
3062
-
3063
- async listenServers() {
3064
- await Promise.all([listenHttpServer(this.injector), listenHttpsServer(this.injector)]);
3065
- }
3066
-
3067
- async logRoutes() {
3068
- const {
3069
- logger,
3070
- platform
3071
- } = this;
3072
-
3073
- if (!this.settings.logger.disableRoutesSummary && !this.disableBootstrapLog) {
3074
- logger.info("Routes mounted :");
3075
- logger.info(printRoutes(await this.injector.alterAsync("$logRoutes", platform.getRoutes())));
3076
- }
3077
- }
3078
-
3079
- async loadRoutes() {
3080
- // istanbul ignore next
3081
- if (this.settings.logger.level !== "off") {
3082
- this.app.use(exports.PlatformLogMiddleware);
3083
- }
3084
-
3085
- this.log("Load routes");
3086
- await this.callHook("$beforeRoutesInit");
3087
- await this.callHook("$$loadRoutes");
3088
- await this.callHook("$onRoutesInit");
3089
- await this.loadStatics();
3090
- await this.callHook("$afterRoutesInit");
3091
- }
3092
-
3093
- createInjector(module, settings) {
3094
- const configuration = di.getConfiguration(module, settings);
3095
- _classPrivateFieldLooseBase(this, _injector)[_injector] = createInjector(configuration); // configure locals providers
3096
-
3097
- this.locals.forEach(provider => {
3098
- this.injector.addProvider(provider.token, provider);
3099
- });
3100
- createPlatformApplication(this.injector);
3101
- createHttpsServer(this.injector);
3102
- createHttpServer(this.injector);
3103
- }
3104
-
3105
- createRootModule(module) {
3106
- _classPrivateFieldLooseBase(this, _rootModule)[_rootModule] = this.injector.invoke(module);
3107
- this.injector.delete(core.constructorOf(_classPrivateFieldLooseBase(this, _rootModule)[_rootModule]));
3108
- this.injector.delete(core.classOf(_classPrivateFieldLooseBase(this, _rootModule)[_rootModule]));
3109
- }
3110
-
3111
- }
3112
-
3113
- /**
3114
- * Define multer option for all MultipartFile
3115
- *
3116
- * ```typescript
3117
- * import {Controller, Post, PlatformMulterFile, MultipartFile, MulterOptions} from "@tsed/common";
3118
- *
3119
- * @Controller('/')
3120
- * class MyCtrl {
3121
- * @Post('/file')
3122
- * private uploadFile(@MultipartFile("file1") file: PlatformMulterFile) {
3123
- *
3124
- * }
3125
- *
3126
- * @Post('/file')
3127
- * @MulterOptions({dest: "/other-dir"})
3128
- * private uploadFile(@MultipartFile("file1") file: PlatformMulterFile) {
3129
- *
3130
- * }
3131
- *
3132
- * @Post('/file2')
3133
- * @MulterOptions({dest: "/other-dir"})
3134
- * private uploadFile(@MultipartFile("file1") file: PlatformMulterFile, @MultipartFile("file2") file2: PlatformMulterFile) {
3135
- *
3136
- * }
3137
- *
3138
- * @Post('/files')
3139
- * private uploadFile(@MultipartFile("file1") files: PlatformMulterFile[]) {
3140
- *
3141
- * }
3142
- * }
3143
- * ```
3144
- *
3145
- * See the tutorial on the [multer configuration](/tutorials/multer.md).
3146
- *
3147
- * @param {multer.Options} options
3148
- * @returns {(target: any, propertyKey: string, descriptor: PropertyDescriptor) => PropertyDescriptor}
3149
- * @decorator
3150
- * @multer
3151
- */
3152
-
3153
- function MulterOptions(options) {
3154
- return (target, propertyKey, descriptor) => {
3155
- core.StoreMerge(exports.PlatformMulterMiddleware, {
3156
- options
3157
- })(target, propertyKey, descriptor);
3158
- return descriptor;
3159
- };
3160
- }
3161
-
3162
- /**
3163
- * Define file size limit.
3164
- *
3165
- * ```typescript
3166
- * import {Controller, Post} from "@tsed/common";
3167
- * import {MulterOptions, MultipartFile} from "@tsed/common";
3168
- * import {Multer} from "@types/multer";
3169
- *
3170
- * type MulterFile = Express.Multer.File;
3171
- *
3172
- * @Controller('/')
3173
- * class MyCtrl {
3174
- * @Post('/file2')
3175
- * @MulterFileSize(1024) // (Ko). Applied for all fields
3176
- * private uploadFile(@MultipartFile("file1") file: MulterFile, @MultipartFile("file2") file2: MulterFile) {
3177
- *
3178
- * }
3179
- * }
3180
- * ```
3181
- *
3182
- * > See the tutorial on the [multer configuration](/tutorials/multer.md).
3183
- * @param fileSize
3184
- * @returns {(target: any, propertyKey: string, descriptor: PropertyDescriptor) => PropertyDescriptor}
3185
- * @decorator
3186
- * @multer
3187
- */
3188
-
3189
- function MulterFileSize(fileSize) {
3190
- return MulterOptions({
3191
- limits: {
3192
- fileSize
3193
- }
3194
- });
3195
- }
3196
-
3197
- function mapOptions$1(name, maxCount) {
3198
- return {
3199
- fields: [{
3200
- name,
3201
- maxCount
3202
- }]
3203
- };
3204
- }
3205
- /**
3206
- * Define a parameter as Multipart file.
3207
- *
3208
- * ```typescript
3209
- * import {Controller, Post} from "@tsed/common";
3210
- * import {MulterOptions, MultipartFile} from "@tsed/common";
3211
- * import {Multer} from "@types/multer";
3212
- *
3213
- * type MulterFile = Express.Multer.File;
3214
- *
3215
- * @Controller('/')
3216
- * class MyCtrl {
3217
- * @Post('/file')
3218
- * private uploadFile(@MultipartFile("file1") file: MulterFile) {
3219
- *
3220
- * }
3221
- *
3222
- * @Post('/file')
3223
- * @MulterOptions({dest: "/other-dir"})
3224
- * private uploadFile(@MultipartFile("file1") file: MulterFile) {
3225
- *
3226
- * }
3227
- *
3228
- * @Post('/file2')
3229
- * @MulterOptions({dest: "/other-dir"})
3230
- * private uploadFile(@MultipartFile("file1") file: MulterFile, @MultipartFile("file2") file2: MulterFile) {
3231
- *
3232
- * }
3233
- *
3234
- * @Post('/files')
3235
- * private uploadFile(@MultipartFile("file1") files: MulterFile[]) {
3236
- *
3237
- * }
3238
- * }
3239
- * ```
3240
- *
3241
- * > See the tutorial on the [multer configuration](/tutorials/multer.md).
3242
- *
3243
- * @param name
3244
- * @param maxCount
3245
- * @returns Function
3246
- * @decorator
3247
- * @input
3248
- */
3249
-
3250
-
3251
- function MultipartFile(name, maxCount) {
3252
- return (...args) => {
3253
- const [target, propertyKey, index] = args;
3254
- const multiple = core.Metadata.getParamTypes(target, propertyKey)[index] === Array;
3255
- name = typeof name === "object" ? undefined : name;
3256
- const expression = [name, !multiple && "0"].filter(Boolean).join(".");
3257
- const decorators = core.useDecorators(core.useMethodDecorators(schema.Returns(400).Description(`<File too long | Too many parts | Too many files | Field name too long | Field value too long | Too many fields | Unexpected field> [fieldName] Example: File too long file1`), schema.Consumes("multipart/form-data"), core.StoreMerge(exports.PlatformMulterMiddleware, mapOptions$1(name, maxCount))), platformParams.UseParam({
3258
- paramType: platformParams.ParamTypes.FILES,
3259
- dataPath: "$ctx.request.files",
3260
- expression,
3261
- useValidation: true
3262
- }));
3263
- decorators(...args);
3264
- };
3265
- }
3266
-
3267
- /**
3268
- * This method is just like the `router.METHOD()` methods, except that it matches all HTTP methods (verbs).
3269
- *
3270
- * This method is extremely useful for mapping “global” logic for specific path prefixes or arbitrary matches.
3271
- * For example, if you placed the following route at the top of all other route definitions, it would require that
3272
- * all routes from that point on would require authentication, and automatically load a user.
3273
- * Keep in mind that these callbacks do not have to act as end points; loadUser can perform a task, then call next()
3274
- * to continue matching subsequent routes.
3275
- * @param path
3276
- * @param args
3277
- * @returns {Function}
3278
- * @decorator
3279
- * @operation
3280
- * @httpMethod
3281
- */
3282
-
3283
- function All(path = "/", ...args) {
3284
- return platformMiddlewares.Use(...["all", path].concat(args));
3285
- }
3286
- /**
3287
- * This method is just like the `router.METHOD()` methods, except that it matches all HTTP methods (verbs).
3288
- *
3289
- * This method is extremely useful for mapping “global” logic for specific path prefixes or arbitrary matches.
3290
- * For example, if you placed the following route at the top of all other route definitions, it would require that
3291
- * all routes from that point on would require authentication, and automatically load a user.
3292
- * Keep in mind that these callbacks do not have to act as end points; loadUser can perform a task, then call next()
3293
- * to continue matching subsequent routes.
3294
- * @param path
3295
- * @param args
3296
- * @returns {Function}
3297
- * @decorator
3298
- * @operation
3299
- * @httpMethod
3300
- */
3301
-
3302
- function Get(path = "/", ...args) {
3303
- return platformMiddlewares.Use(...["get", path].concat(args));
3304
- }
3305
- /**
3306
- * This method is just like the `router.METHOD()` methods, except that it matches all HTTP methods (verbs).
3307
- *
3308
- * This method is extremely useful for mapping “global” logic for specific path prefixes or arbitrary matches.
3309
- * For example, if you placed the following route at the top of all other route definitions, it would require that
3310
- * all routes from that point on would require authentication, and automatically load a user.
3311
- * Keep in mind that these callbacks do not have to act as end points; loadUser can perform a task, then call next()
3312
- * to continue matching subsequent routes.
3313
- * @param path
3314
- * @param args
3315
- * @returns {Function}
3316
- * @decorator
3317
- * @operation
3318
- * @httpMethod
3319
- */
3320
-
3321
- function Post(path = "/", ...args) {
3322
- return platformMiddlewares.Use(...["post", path].concat(args));
3323
- }
3324
- /**
3325
- * This method is just like the `router.METHOD()` methods, except that it matches all HTTP methods (verbs).
3326
- *
3327
- * This method is extremely useful for mapping “global” logic for specific path prefixes or arbitrary matches.
3328
- * For example, if you placed the following route at the top of all other route definitions, it would require that
3329
- * all routes from that point on would require authentication, and automatically load a user.
3330
- * Keep in mind that these callbacks do not have to act as end points; loadUser can perform a task, then call next()
3331
- * to continue matching subsequent routes.
3332
- * @param path
3333
- * @param args
3334
- * @returns {Function}
3335
- * @decorator
3336
- * @operation
3337
- * @httpMethod
3338
- */
3339
-
3340
- function Put(path = "/", ...args) {
3341
- return platformMiddlewares.Use(...["put", path].concat(args));
3342
- }
3343
- /**
3344
- * This method is just like the `router.METHOD()` methods, except that it matches all HTTP methods (verbs).
3345
- *
3346
- * This method is extremely useful for mapping “global” logic for specific path prefixes or arbitrary matches.
3347
- * For example, if you placed the following route at the top of all other route definitions, it would require that
3348
- * all routes from that point on would require authentication, and automatically load a user.
3349
- * Keep in mind that these callbacks do not have to act as end points; loadUser can perform a task, then call next()
3350
- * to continue matching subsequent routes.
3351
- * @param path
3352
- * @param args
3353
- * @returns {Function}
3354
- * @decorator
3355
- * @operation
3356
- * @httpMethod
3357
- */
3358
-
3359
- function Delete(path = "/", ...args) {
3360
- return platformMiddlewares.Use(...["delete", path].concat(args));
3361
- }
3362
- /**
3363
- * This method is just like the `router.METHOD()` methods, except that it matches all HTTP methods (verbs).
3364
- *
3365
- * This method is extremely useful for mapping “global” logic for specific path prefixes or arbitrary matches.
3366
- * For example, if you placed the following route at the top of all other route definitions, it would require that
3367
- * all routes from that point on would require authentication, and automatically load a user.
3368
- * Keep in mind that these callbacks do not have to act as end points; loadUser can perform a task, then call next()
3369
- * to continue matching subsequent routes.
3370
- * @param path
3371
- * @param args
3372
- * @returns {Function}
3373
- * @decorator
3374
- * @operation
3375
- * @httpMethod
3376
- */
3377
-
3378
- function Head(path = "/", ...args) {
3379
- return platformMiddlewares.Use(...["head", path].concat(args));
3380
- }
3381
- /**
3382
- * This method is just like the `router.METHOD()` methods, except that it matches all HTTP methods (verbs).
3383
- *
3384
- * This method is extremely useful for mapping “global” logic for specific path prefixes or arbitrary matches.
3385
- * For example, if you placed the following route at the top of all other route definitions, it would require that
3386
- * all routes from that point on would require authentication, and automatically load a user.
3387
- * Keep in mind that these callbacks do not have to act as end points; loadUser can perform a task, then call next()
3388
- * to continue matching subsequent routes.
3389
- * @param path
3390
- * @param args
3391
- * @returns {Function}
3392
- * @decorator
3393
- * @operation
3394
- * @httpMethod
3395
- */
3396
-
3397
- function Patch(path = "/", ...args) {
3398
- return platformMiddlewares.Use(...["patch", path].concat(args));
3399
- }
3400
- /**
3401
- * This method is just like the `router.METHOD()` methods, except that it matches all HTTP methods (verbs).
3402
- *
3403
- * This method is extremely useful for mapping “global” logic for specific path prefixes or arbitrary matches.
3404
- * For example, if you placed the following route at the top of all other route definitions, it would require that
3405
- * all routes from that point on would require authentication, and automatically load a user.
3406
- * Keep in mind that these callbacks do not have to act as end points; loadUser can perform a task, then call next()
3407
- * to continue matching subsequent routes.
3408
- * @param path
3409
- * @param args
3410
- * @returns {Function}
3411
- * @decorator
3412
- * @operation
3413
- * @httpMethod
3414
- */
3415
-
3416
- function Options(path = "/", ...args) {
3417
- return platformMiddlewares.Use(...["options", path].concat(args));
3418
- }
3419
-
3420
- /**
3421
- *
3422
- * @param fn
3423
- * @decorator
3424
- */
3425
-
3426
- function EndpointFn(fn) {
3427
- return schema.JsonEntityFn(fn);
3428
- }
3429
-
3430
- /**
3431
- * Set a mime list which are acceptable and checks if the specified content types are acceptable, based on the request’s Accept HTTP header field.
3432
- *
3433
- * ```typescript
3434
- * @Controller('/mypath')
3435
- * export class MyCtrl {
3436
- *
3437
- * @Get('/')
3438
- * @AcceptMime('application/json')
3439
- * public getResource(){}
3440
- * }
3441
- * ```
3442
- *
3443
- * @param mimes
3444
- * @decorator
3445
- * @operation
3446
- * @response
3447
- */
3448
-
3449
- function AcceptMime(...mimes) {
3450
- return core.useDecorators(schema.Produces(...mimes), EndpointFn(endpoint => {
3451
- endpoint.acceptMimes = mimes;
3452
- }));
3453
- }
3454
-
3455
- const _excluded$1 = ["children"];
3456
-
3457
- function mapOptions(options) {
3458
- if (typeof options === "string" || options instanceof RegExp || core.isArrayOrArrayClass(options)) {
3459
- return {
3460
- path: options
3461
- };
3462
- }
3463
-
3464
- return options;
3465
- }
3466
- /**
3467
- * Declare a new controller with his Rest path. His methods annotated will be collected to build the routing list.
3468
- * This routing listing will be built with the `express.Router` object.
3469
- *
3470
- * ::: tip
3471
- * See [Controllers](/docs/controllers.md) section for more details
3472
- * :::
3473
- *
3474
- * ```typescript
3475
- * @Controller("/calendars")
3476
- * export provide CalendarCtrl {
3477
- *
3478
- * @Get("/:id")
3479
- * public get(
3480
- * @Req() request: Req,
3481
- * @Res() response: Res,
3482
- * @Next() next: Next
3483
- * ): void {
3484
- *
3485
- * }
3486
- * }
3487
- * ```
3488
- *
3489
- * @param options
3490
- * @controller
3491
- * @decorator
3492
- * @classDecorator
3493
- */
3494
-
3495
-
3496
- function Controller(options) {
3497
- const _mapOptions = mapOptions(options),
3498
- {
3499
- children = []
3500
- } = _mapOptions,
3501
- opts = _objectWithoutPropertiesLoose(_mapOptions, _excluded$1);
3502
-
3503
- return target => {
3504
- di.registerController(_extends({
3505
- provide: target
3506
- }, opts));
3507
- core.Store.from(target).set("childrenControllers", children);
3508
- children.forEach(childToken => {
3509
- core.Store.from(childToken).set("parentController", target);
3510
- });
3511
- };
3512
- }
3513
-
3514
- function getParamType$1(target, propertyKey, parameterIndex) {
3515
- const type = core.Metadata.getOwnParamTypes(target, propertyKey)[parameterIndex];
3516
-
3517
- if (core.isClass(type)) {
3518
- if (core.nameOf(type) === "PlatformResponse") {
3519
- return {
3520
- paramType: platformParams.ParamTypes.PLATFORM_RESPONSE,
3521
- dataPath: "$ctx.response"
3522
- };
3523
- }
3524
-
3525
- if (type === Http.ServerResponse) {
3526
- return {
3527
- paramType: platformParams.ParamTypes.NODE_RESPONSE,
3528
- dataPath: "$ctx.response.res"
3529
- };
3530
- }
3531
- }
3532
-
3533
- return {
3534
- paramType: platformParams.ParamTypes.RESPONSE,
3535
- dataPath: "$ctx.response.response"
3536
- };
3537
- }
3538
-
3539
- function Response() {
3540
- return Res();
3541
- }
3542
- function Res() {
3543
- return (target, propertyKey, parameterIndex) => {
3544
- const {
3545
- paramType,
3546
- dataPath
3547
- } = getParamType$1(target, propertyKey, parameterIndex);
3548
- platformParams.UseParam({
3549
- paramType,
3550
- dataPath
3551
- })(target, propertyKey, parameterIndex);
3552
- };
3553
- }
3554
-
3555
- function getParamType(target, propertyKey, parameterIndex) {
3556
- const type = core.Metadata.getOwnParamTypes(target, propertyKey)[parameterIndex];
3557
-
3558
- if (core.isClass(type)) {
3559
- if (core.nameOf(type) === "PlatformRequest") {
3560
- return {
3561
- paramType: platformParams.ParamTypes.PLATFORM_REQUEST,
3562
- dataPath: "$ctx.request"
3563
- };
3564
- }
3565
-
3566
- if (type === Http.IncomingMessage) {
3567
- return {
3568
- paramType: platformParams.ParamTypes.NODE_REQUEST,
3569
- dataPath: "$ctx.request.req"
3570
- };
3571
- }
3572
- }
3573
-
3574
- return {
3575
- paramType: platformParams.ParamTypes.REQUEST,
3576
- dataPath: "$ctx.request.request"
3577
- };
3578
- }
3579
-
3580
- function Request(...args) {
3581
- // @ts-ignore
3582
- return Req(...args);
3583
- }
3584
- function Req(...args) {
3585
- const {
3586
- expression,
3587
- useType,
3588
- useConverter = false,
3589
- useValidation = false
3590
- } = platformParams.mapParamsOptions(args);
3591
- return (target, propertyKey, parameterIndex) => {
3592
- const {
3593
- paramType,
3594
- dataPath
3595
- } = getParamType(target, propertyKey, parameterIndex);
3596
- platformParams.UseParam({
3597
- paramType,
3598
- dataPath,
3599
- expression,
3600
- useType,
3601
- useConverter,
3602
- useValidation
3603
- })(target, propertyKey, parameterIndex);
3604
- };
3605
- }
3606
-
3607
- /**
3608
- * Get the Next function (for express application and middleware).
3609
- *
3610
- * @decorator
3611
- * @operation
3612
- * @input
3613
- */
3614
-
3615
- function Next() {
3616
- return platformParams.UseParam({
3617
- paramType: platformParams.ParamTypes.NEXT_FN,
3618
- dataPath: "next",
3619
- useConverter: false,
3620
- useValidation: false
3621
- });
3622
- }
3623
-
3624
- /**
3625
- * @returns {Function}
3626
- * @decorator
3627
- * @operation
3628
- * @input
3629
- */
3630
-
3631
- function Err() {
3632
- return platformParams.UseParam({
3633
- paramType: platformParams.ParamTypes.ERR,
3634
- dataPath: "err",
3635
- useValidation: false,
3636
- useConverter: false
3637
- });
3638
- }
3639
-
3640
- const _excluded = ["use", "collection"];
3641
-
3642
- /**
3643
- * @ignore
3644
- */
3645
- function mapReturnedResponse(_ref) {
3646
- let {
3647
- use,
3648
- collection
3649
- } = _ref,
3650
- options = _objectWithoutPropertiesLoose(_ref, _excluded);
3651
-
3652
- return _extends({}, options, {
3653
- type: options.type || use,
3654
- collectionType: options.collectionType || collection
3655
- });
3656
- }
3657
-
3658
- /**
3659
- * @platform
3660
- */
3661
-
3662
- class PlatformTest extends di.DITest {
3663
- static async create(options = {}) {
3664
- di.DITest.injector = PlatformTest.createInjector(options);
3665
- const container = di.createContainer();
3666
- await di.DITest.injector.load(container, exports.PlatformModule);
3667
- }
3668
- /**
3669
- * Create a new injector with the right default services
3670
- */
3671
-
3672
-
3673
- static createInjector(settings = {}) {
3674
- return createInjector(di.DITest.configure(settings));
3675
- }
3676
- /**
3677
- * Load the server silently without listening port and configure it on test profile.
3678
- * @decorator
3679
- * @param mod
3680
- * @param settings
3681
- * @returns {Promise<void>}
3682
- */
3683
-
3684
-
3685
- static bootstrap(mod, settings = {}) {
3686
- return async function before() {
3687
- let instance;
3688
- const platform = settings.platform || PlatformTest.platformBuilder;
3689
- /* istanbul ignore next */
3690
-
3691
- if (!platform) {
3692
- throw new Error("Platform type is not specified. Have you added at least `import @tsed/platform-express` (or equivalent) on your Server.ts ?");
3693
- } // @ts-ignore
3694
-
3695
-
3696
- instance = await PlatformBuilder.build(platform).bootstrap(mod, di.DITest.configure(settings));
3697
-
3698
- if (!settings.listen) {
3699
- await instance.callHook("$beforeListen");
3700
- await instance.callHook("$afterListen");
3701
- await instance.ready();
3702
- } else {
3703
- await instance.listen();
3704
- } // used by inject method
3705
-
3706
-
3707
- di.DITest.injector = instance.injector;
3708
- };
3709
- }
3710
- /**
3711
- * It injects services into the test function where you can alter, spy on, and manipulate them.
3712
- *
3713
- * The inject function has two parameters
3714
- *
3715
- * * an array of Service dependency injection tokens,
3716
- * * a test function whose parameters correspond exactly to each item in the injection token array.
3717
- *
3718
- * @param targets
3719
- * @param func
3720
- */
3721
-
3722
-
3723
- static inject(targets, func) {
3724
- return async () => {
3725
- if (!di.DITest.hasInjector()) {
3726
- await PlatformTest.create();
3727
- }
3728
-
3729
- const injector = di.DITest.injector;
3730
- const deps = [];
3731
-
3732
- for (const target of targets) {
3733
- deps.push(injector.has(target) ? injector.get(target) : await injector.invoke(target));
3734
- }
3735
-
3736
- return await func(...deps);
3737
- };
3738
- }
3739
- /**
3740
- * Return the raw application (express or koa).
3741
- * Use this callback with SuperTest.
3742
- *
3743
- * ```typescript
3744
- * let request: SuperTest.SuperTest<SuperTest.Test>;
3745
- * beforeEach(PlatformTest.bootstrap(Server, {
3746
- * mount: {
3747
- * "/rest": [ProductsController]
3748
- * }
3749
- * }));
3750
- * beforeEach(() => {
3751
- * request = SuperTest(PlatformTest.callback());
3752
- * });
3753
- * ```
3754
- */
3755
-
3756
-
3757
- static callback() {
3758
- var _DITest$injector$get;
3759
-
3760
- return (_DITest$injector$get = di.DITest.injector.get(exports.PlatformApplication)) == null ? void 0 : _DITest$injector$get.callback();
3761
- }
3762
-
3763
- static createRequest(options = {}) {
3764
- return _extends({
3765
- headers: {},
3766
-
3767
- get(key) {
3768
- return this.headers[key.toLowerCase()];
3769
- },
3770
-
3771
- accepts(mime) {
3772
- return require("accepts")(this).types([].concat(mime));
3773
- }
3774
-
3775
- }, options);
3776
- }
3777
-
3778
- static createResponse(options = {}) {
3779
- return _extends({
3780
- headers: {},
3781
- locals: {},
3782
- statusCode: 200,
3783
-
3784
- status(code) {
3785
- this.statusCode = code;
3786
- return this;
3787
- },
3788
-
3789
- contentType(content) {
3790
- this.set("content-type", content);
3791
- },
3792
-
3793
- contentLength(content) {
3794
- this.set("content-length", content);
3795
- },
3796
-
3797
- redirect(status, path) {
3798
- this.statusCode = status;
3799
- this.set("location", path);
3800
- },
3801
-
3802
- location(path) {
3803
- this.set("location", path);
3804
- },
3805
-
3806
- get(key) {
3807
- return this.headers[key.toLowerCase()];
3808
- },
3809
-
3810
- getHeaders() {
3811
- return this.headers;
3812
- },
3813
-
3814
- set(key, value) {
3815
- this.headers[key.toLowerCase()] = value;
3816
- return this;
3817
- },
3818
-
3819
- send(data) {
3820
- this.data = data;
3821
- },
3822
-
3823
- json(data) {
3824
- this.data = data;
3825
- }
3826
-
3827
- }, options);
3828
- }
3829
-
3830
- static createRequestContext(options = {}) {
3831
- var _options$request, _options$event, _options$response, _options$event2;
3832
-
3833
- const event = {
3834
- request: (options == null ? void 0 : (_options$request = options.request) == null ? void 0 : _options$request.request) || (options == null ? void 0 : (_options$event = options.event) == null ? void 0 : _options$event.request) || PlatformTest.createRequest(),
3835
- response: (options == null ? void 0 : (_options$response = options.response) == null ? void 0 : _options$response.response) || (options == null ? void 0 : (_options$event2 = options.event) == null ? void 0 : _options$event2.response) || PlatformTest.createResponse()
3836
- };
3837
- const ctx = new PlatformContext(_extends({
3838
- id: "id",
3839
- injector: di.DITest.injector,
3840
- logger: di.DITest.injector.logger,
3841
- url: "/"
3842
- }, options, {
3843
- event
3844
- }));
3845
- ctx.response.platformViews = PlatformTest.get(platformViews.PlatformViews);
3846
- return ctx;
3847
- }
3848
-
3849
- }
3850
-
3851
- di.GlobalProviders.createRegistry(di.ProviderType.CONTROLLER, ControllerProvider, {
3852
- onInvoke(provider, locals) {
3853
- locals.set(exports.PlatformRouter, provider.getRouter());
3854
- }
3855
-
3856
- });
3857
-
3858
- Object.defineProperty(exports, '$log', {
3859
- enumerable: true,
3860
- get: function () {
3861
- return logger.$log;
3862
- }
3863
- });
3864
- Object.defineProperty(exports, 'Logger', {
3865
- enumerable: true,
3866
- get: function () {
3867
- return logger.Logger;
3868
- }
3869
- });
3870
- Object.defineProperty(exports, 'Location', {
3871
- enumerable: true,
3872
- get: function () {
3873
- return schema.Location;
3874
- }
3875
- });
3876
- Object.defineProperty(exports, 'Redirect', {
3877
- enumerable: true,
3878
- get: function () {
3879
- return schema.Redirect;
3880
- }
3881
- });
3882
- exports.AcceptMime = AcceptMime;
3883
- exports.All = All;
3884
- exports.AnyToPromiseWithCtx = AnyToPromiseWithCtx;
3885
- exports.Controller = Controller;
3886
- exports.ControllerProvider = ControllerProvider;
3887
- exports.Delete = Delete;
3888
- exports.EndpointFn = EndpointFn;
3889
- exports.Err = Err;
3890
- exports.Get = Get;
3891
- exports.HandlerMetadata = HandlerMetadata;
3892
- exports.Head = Head;
3893
- exports.HttpServer = HttpServer;
3894
- exports.HttpsServer = HttpsServer;
3895
- exports.MulterFileSize = MulterFileSize;
3896
- exports.MulterOptions = MulterOptions;
3897
- exports.MultipartFile = MultipartFile;
3898
- exports.Next = Next;
3899
- exports.Options = Options;
3900
- exports.PLATFORM_ROUTER_OPTIONS = PLATFORM_ROUTER_OPTIONS;
3901
- exports.Patch = Patch;
3902
- exports.PlatformBuilder = PlatformBuilder;
3903
- exports.PlatformContext = PlatformContext;
3904
- exports.PlatformControllerBuilder = PlatformControllerBuilder;
3905
- exports.PlatformRouteDetails = PlatformRouteDetails;
3906
- exports.PlatformTest = PlatformTest;
3907
- exports.Post = Post;
3908
- exports.Put = Put;
3909
- exports.ROUTER_OPTIONS = ROUTER_OPTIONS;
3910
- exports.Req = Req;
3911
- exports.Request = Request;
3912
- exports.Res = Res;
3913
- exports.Response = Response;
3914
- exports.bindEndpointMiddleware = bindEndpointMiddleware;
3915
- exports.createContext = createContext;
3916
- exports.createHttpServer = createHttpServer;
3917
- exports.createHttpsServer = createHttpsServer;
3918
- exports.createInjector = createInjector;
3919
- exports.createPlatformApplication = createPlatformApplication;
3920
- exports.listenHttpServer = listenHttpServer;
3921
- exports.listenHttpsServer = listenHttpsServer;
3922
- exports.listenServer = listenServer;
3923
- exports.mapReturnedResponse = mapReturnedResponse;
3924
- exports.printRoutes = printRoutes;
3925
- exports.useCtxHandler = useCtxHandler;
3926
- Object.keys(di).forEach(function (k) {
3927
- if (k !== 'default' && !exports.hasOwnProperty(k)) Object.defineProperty(exports, k, {
3928
- enumerable: true,
3929
- get: function () {
3930
- return di[k];
3931
- }
3932
- });
3933
- });
3934
- Object.keys(platformParams).forEach(function (k) {
3935
- if (k !== 'default' && !exports.hasOwnProperty(k)) Object.defineProperty(exports, k, {
3936
- enumerable: true,
3937
- get: function () {
3938
- return platformParams[k];
3939
- }
3940
- });
3941
- });
3942
- Object.keys(platformExceptions).forEach(function (k) {
3943
- if (k !== 'default' && !exports.hasOwnProperty(k)) Object.defineProperty(exports, k, {
3944
- enumerable: true,
3945
- get: function () {
3946
- return platformExceptions[k];
3947
- }
3948
- });
3949
- });
3950
- Object.keys(platformResponseFilter).forEach(function (k) {
3951
- if (k !== 'default' && !exports.hasOwnProperty(k)) Object.defineProperty(exports, k, {
3952
- enumerable: true,
3953
- get: function () {
3954
- return platformResponseFilter[k];
3955
- }
3956
- });
3957
- });
3958
- Object.keys(platformCache).forEach(function (k) {
3959
- if (k !== 'default' && !exports.hasOwnProperty(k)) Object.defineProperty(exports, k, {
3960
- enumerable: true,
3961
- get: function () {
3962
- return platformCache[k];
3963
- }
3964
- });
3965
- });
3966
- Object.keys(platformMiddlewares).forEach(function (k) {
3967
- if (k !== 'default' && !exports.hasOwnProperty(k)) Object.defineProperty(exports, k, {
3968
- enumerable: true,
3969
- get: function () {
3970
- return platformMiddlewares[k];
3971
- }
3972
- });
3973
- });
3974
- Object.keys(platformViews).forEach(function (k) {
3975
- if (k !== 'default' && !exports.hasOwnProperty(k)) Object.defineProperty(exports, k, {
3976
- enumerable: true,
3977
- get: function () {
3978
- return platformViews[k];
3979
- }
3980
- });
3981
- });
3982
- Object.keys(componentsScan).forEach(function (k) {
3983
- if (k !== 'default' && !exports.hasOwnProperty(k)) Object.defineProperty(exports, k, {
3984
- enumerable: true,
3985
- get: function () {
3986
- return componentsScan[k];
3987
- }
3988
- });
3989
- });
3990
- //# sourceMappingURL=index.js.map