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

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