node-server-engine 1.4.8 → 1.5.0

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 (261) hide show
  1. package/.commitlintrc.js +27 -0
  2. package/.releaserc.js +56 -0
  3. package/README.md +154 -2
  4. package/dist/const/tokenIssuer.js +1 -0
  5. package/dist/const/tokenIssuer.js.map +1 -1
  6. package/dist/db/models/SequelizeMeta.js +3 -1
  7. package/dist/db/models/SequelizeMeta.js.map +1 -1
  8. package/dist/entities/ElasticSearch/ElasticSearch.js +1 -2
  9. package/dist/entities/ElasticSearch/ElasticSearch.js.map +1 -1
  10. package/dist/entities/SocketClient/SocketClient.js +1 -0
  11. package/dist/entities/SocketClient/SocketClient.js.map +1 -1
  12. package/dist/index.js +1 -2
  13. package/dist/index.js.map +1 -1
  14. package/dist/middleware/checkPermission/checkPermission.d.ts +1 -1
  15. package/dist/middleware/checkPermission/checkPermission.js +4 -2
  16. package/dist/middleware/checkPermission/checkPermission.js.map +1 -1
  17. package/dist/utils/createHttpServer/createHttpServer.js +1 -1
  18. package/dist/utils/createHttpServer/createHttpServer.js.map +1 -1
  19. package/dist/utils/jwt/jwt.js +1 -1
  20. package/dist/utils/jwt/jwt.js.map +1 -1
  21. package/dist/utils/semverCompare/semverCompare.js +1 -5
  22. package/dist/utils/semverCompare/semverCompare.js.map +1 -1
  23. package/package.json +30 -19
  24. package/.env.example +0 -186
  25. package/.github/workflows/publish.yml +0 -41
  26. package/.prettierrc +0 -7
  27. package/Dockerfile +0 -31
  28. package/babel.config.json +0 -34
  29. package/eslint.config.mjs +0 -11
  30. package/src/const/DebeziumEvent.ts +0 -6
  31. package/src/const/LogSeverity.ts +0 -7
  32. package/src/const/index.ts +0 -5
  33. package/src/const/metrics.ts +0 -6
  34. package/src/const/mime.ts +0 -37
  35. package/src/const/tokenIssuer.ts +0 -7
  36. package/src/db/migrations/20241030121500-create-sequelize-meta-table.ts +0 -29
  37. package/src/db/models/SequelizeMeta.ts +0 -16
  38. package/src/db/models/index.ts +0 -2
  39. package/src/entities/ElasticSearch/ElasticSearch.ts +0 -103
  40. package/src/entities/ElasticSearch/ElasticSearch.types.ts +0 -7
  41. package/src/entities/ElasticSearch/index.ts +0 -2
  42. package/src/entities/Endpoint/Endpoint.test.ts +0 -248
  43. package/src/entities/Endpoint/Endpoint.ts +0 -221
  44. package/src/entities/Endpoint/Endpoint.types.ts +0 -181
  45. package/src/entities/Endpoint/index.ts +0 -2
  46. package/src/entities/EngineError/EngineError.ts +0 -28
  47. package/src/entities/EngineError/EngineError.types.ts +0 -15
  48. package/src/entities/EngineError/index.ts +0 -2
  49. package/src/entities/KeySet/KeySet.test.ts +0 -126
  50. package/src/entities/KeySet/KeySet.ts +0 -172
  51. package/src/entities/KeySet/KeySet.types.ts +0 -28
  52. package/src/entities/KeySet/index.ts +0 -2
  53. package/src/entities/LifecycleController/LifecycleController.test.ts +0 -48
  54. package/src/entities/LifecycleController/LifecycleController.ts +0 -24
  55. package/src/entities/LifecycleController/LifecycleController.types.ts +0 -5
  56. package/src/entities/LifecycleController/index.ts +0 -2
  57. package/src/entities/Localizator/Localizator.ts +0 -139
  58. package/src/entities/Localizator/Localizator.types.ts +0 -52
  59. package/src/entities/Localizator/guessNamingConvention/guessNamingConvention.test.ts +0 -165
  60. package/src/entities/Localizator/guessNamingConvention/guessNamingConvention.ts +0 -58
  61. package/src/entities/Localizator/guessNamingConvention/index.ts +0 -1
  62. package/src/entities/Localizator/index.ts +0 -2
  63. package/src/entities/MessageHandler/MessageHandler.test.ts +0 -130
  64. package/src/entities/MessageHandler/MessageHandler.ts +0 -72
  65. package/src/entities/MessageHandler/MessageHandler.types.ts +0 -15
  66. package/src/entities/MessageHandler/index.ts +0 -2
  67. package/src/entities/PubSub/PubSub.test.ts +0 -297
  68. package/src/entities/PubSub/PubSub.ts +0 -202
  69. package/src/entities/PubSub/PubSub.types.ts +0 -76
  70. package/src/entities/PubSub/handleMessage/handleMessage.test.ts +0 -102
  71. package/src/entities/PubSub/handleMessage/handleMessage.ts +0 -65
  72. package/src/entities/PubSub/handleMessage/index.ts +0 -1
  73. package/src/entities/PubSub/index.ts +0 -2
  74. package/src/entities/PushNotification/PushNotification.test.ts +0 -35
  75. package/src/entities/PushNotification/PushNotification.ts +0 -44
  76. package/src/entities/PushNotification/PushNotification.types.ts +0 -25
  77. package/src/entities/PushNotification/index.ts +0 -2
  78. package/src/entities/Redis/Redis.ts +0 -71
  79. package/src/entities/Redis/Redis.types.ts +0 -19
  80. package/src/entities/Redis/Redis.validate.ts +0 -17
  81. package/src/entities/Redis/index.ts +0 -2
  82. package/src/entities/Sequelize/Sequelize.config.ts +0 -59
  83. package/src/entities/Sequelize/Sequelize.test.ts +0 -21
  84. package/src/entities/Sequelize/Sequelize.ts +0 -75
  85. package/src/entities/Sequelize/Sequelize.types.ts +0 -10
  86. package/src/entities/Sequelize/Sequelize.validate.ts +0 -15
  87. package/src/entities/Sequelize/index.ts +0 -2
  88. package/src/entities/Server/Server.const.ts +0 -56
  89. package/src/entities/Server/Server.test.ts +0 -272
  90. package/src/entities/Server/Server.ts +0 -471
  91. package/src/entities/Server/Server.types.ts +0 -88
  92. package/src/entities/Server/index.ts +0 -2
  93. package/src/entities/SocketClient/SocketClient.test.ts +0 -392
  94. package/src/entities/SocketClient/SocketClient.ts +0 -401
  95. package/src/entities/SocketClient/SocketClient.types.ts +0 -62
  96. package/src/entities/SocketClient/index.ts +0 -2
  97. package/src/entities/SocketClient/parseMessage/index.ts +0 -1
  98. package/src/entities/SocketClient/parseMessage/parseMessage.test.ts +0 -20
  99. package/src/entities/SocketClient/parseMessage/parseMessage.ts +0 -26
  100. package/src/entities/Storage/Storage.test.ts +0 -58
  101. package/src/entities/Storage/Storage.ts +0 -219
  102. package/src/entities/Storage/Storage.types.ts +0 -57
  103. package/src/entities/Storage/index.ts +0 -2
  104. package/src/entities/ValidationError/ValidationError.ts +0 -34
  105. package/src/entities/ValidationError/index.ts +0 -1
  106. package/src/entities/WebError/WebError.test.ts +0 -18
  107. package/src/entities/WebError/WebError.ts +0 -23
  108. package/src/entities/WebError/WebError.types.ts +0 -9
  109. package/src/entities/WebError/index.ts +0 -2
  110. package/src/entities/index.ts +0 -16
  111. package/src/index.ts +0 -6
  112. package/src/metrics/debug.ts +0 -10
  113. package/src/metrics/index.ts +0 -2
  114. package/src/metrics/request.ts +0 -17
  115. package/src/middleware/authHmac/authHmac.test.ts +0 -86
  116. package/src/middleware/authHmac/authHmac.ts +0 -56
  117. package/src/middleware/authHmac/authHmac.types.ts +0 -7
  118. package/src/middleware/authHmac/index.ts +0 -2
  119. package/src/middleware/authJwt/authJwt.test.ts +0 -54
  120. package/src/middleware/authJwt/authJwt.ts +0 -55
  121. package/src/middleware/authJwt/authJwt.types.ts +0 -14
  122. package/src/middleware/authJwt/index.ts +0 -2
  123. package/src/middleware/authStatic/authStatic.test.ts +0 -36
  124. package/src/middleware/authStatic/authStatic.ts +0 -45
  125. package/src/middleware/authStatic/index.ts +0 -1
  126. package/src/middleware/authTls/authTls.test.ts +0 -138
  127. package/src/middleware/authTls/authTls.ts +0 -119
  128. package/src/middleware/authTls/authTls.types.ts +0 -13
  129. package/src/middleware/authTls/index.ts +0 -2
  130. package/src/middleware/checkPermission/checkPermission.ts +0 -33
  131. package/src/middleware/checkPermission/index.ts +0 -1
  132. package/src/middleware/error/error.test.ts +0 -60
  133. package/src/middleware/error/error.ts +0 -25
  134. package/src/middleware/error/index.ts +0 -1
  135. package/src/middleware/fileUploader/fileUploader.ts +0 -154
  136. package/src/middleware/fileUploader/fileUploader.types.ts +0 -35
  137. package/src/middleware/fileUploader/index.ts +0 -2
  138. package/src/middleware/fileUploader/isMultiPart/index.ts +0 -1
  139. package/src/middleware/fileUploader/isMultiPart/isMultipart.ts +0 -9
  140. package/src/middleware/fileUploader/validate/index.ts +0 -1
  141. package/src/middleware/fileUploader/validate/validate.ts +0 -27
  142. package/src/middleware/fourOhFour/fourOhFour.test.ts +0 -14
  143. package/src/middleware/fourOhFour/fourOhFour.ts +0 -13
  144. package/src/middleware/fourOhFour/index.ts +0 -1
  145. package/src/middleware/geminiFileUploader/geminiFileUploader.ts +0 -68
  146. package/src/middleware/geminiFileUploader/index.ts +0 -1
  147. package/src/middleware/healthCheck/healthCheck.test.ts +0 -12
  148. package/src/middleware/healthCheck/healthCheck.ts +0 -14
  149. package/src/middleware/healthCheck/index.ts +0 -1
  150. package/src/middleware/index.ts +0 -17
  151. package/src/middleware/metrics/index.ts +0 -1
  152. package/src/middleware/metrics/metrics.test.ts +0 -46
  153. package/src/middleware/metrics/metrics.ts +0 -24
  154. package/src/middleware/multiPartFileUploader/index.ts +0 -2
  155. package/src/middleware/multiPartFileUploader/multiPartFileUploader.ts +0 -249
  156. package/src/middleware/multiPartFileUploader/multiPartFileUploader.types.ts +0 -23
  157. package/src/middleware/multiPartFileUploader/validate/index.ts +0 -1
  158. package/src/middleware/multiPartFileUploader/validate/validate.ts +0 -27
  159. package/src/middleware/requestMetrics/index.ts +0 -1
  160. package/src/middleware/requestMetrics/requestMetrics.test.ts +0 -77
  161. package/src/middleware/requestMetrics/requestMetrics.ts +0 -20
  162. package/src/middleware/swaggerDocs/index.ts +0 -2
  163. package/src/middleware/swaggerDocs/swaggerDocs.ts +0 -114
  164. package/src/middleware/swaggerDocs/swaggerDocs.types.ts +0 -41
  165. package/src/middleware/userResolver/index.ts +0 -1
  166. package/src/middleware/userResolver/userResolver.ts +0 -53
  167. package/src/middleware/validate/index.ts +0 -1
  168. package/src/middleware/validate/validate.test.ts +0 -43
  169. package/src/middleware/validate/validate.ts +0 -25
  170. package/src/middleware/version/index.ts +0 -1
  171. package/src/middleware/version/version.test.ts +0 -23
  172. package/src/middleware/version/version.ts +0 -12
  173. package/src/utils/checkEnvironment/index.ts +0 -49
  174. package/src/utils/createHttpServer/createHttpServer.test.ts +0 -24
  175. package/src/utils/createHttpServer/createHttpServer.ts +0 -34
  176. package/src/utils/createHttpServer/createHttpServer.validate.ts +0 -17
  177. package/src/utils/createHttpServer/index.ts +0 -1
  178. package/src/utils/createSortedObject/createSortedObject.ts +0 -20
  179. package/src/utils/createSortedObject/createSortedObjet.test.ts +0 -47
  180. package/src/utils/createSortedObject/index.ts +0 -1
  181. package/src/utils/dbMigration/dbMigration.test.ts +0 -209
  182. package/src/utils/dbMigration/dbMigration.ts +0 -199
  183. package/src/utils/dbMigration/dbMigration.types.ts +0 -11
  184. package/src/utils/dbMigration/index.ts +0 -2
  185. package/src/utils/dbMigration/migrateMetadataTable/index.ts +0 -1
  186. package/src/utils/dbMigration/migrateMetadataTable/migrateMetadataTable.test.ts +0 -59
  187. package/src/utils/dbMigration/migrateMetadataTable/migrateMetadataTable.ts +0 -102
  188. package/src/utils/envAssert/envAssert.ts +0 -31
  189. package/src/utils/envAssert/index.ts +0 -1
  190. package/src/utils/envAssert/validators/hostList.ts +0 -17
  191. package/src/utils/envAssert/validators/index.ts +0 -5
  192. package/src/utils/envAssert/validators/ipList.ts +0 -13
  193. package/src/utils/envAssert/validators/path.ts +0 -13
  194. package/src/utils/envAssert/validators/string.ts +0 -9
  195. package/src/utils/envAssert/validators/stringList.ts +0 -13
  196. package/src/utils/filter/filter.ts +0 -17
  197. package/src/utils/filter/index.ts +0 -1
  198. package/src/utils/geminiFileUpload/geminiFileUpload.ts +0 -93
  199. package/src/utils/geminiFileUpload/index.ts +0 -1
  200. package/src/utils/hmac/checkEnv/checkEnv.test.ts +0 -18
  201. package/src/utils/hmac/checkEnv/checkEnv.ts +0 -9
  202. package/src/utils/hmac/checkEnv/index.ts +0 -1
  203. package/src/utils/hmac/createHmac/createHmac.ts +0 -33
  204. package/src/utils/hmac/createHmac/index.ts +0 -1
  205. package/src/utils/hmac/index.ts +0 -4
  206. package/src/utils/hmac/index.types.ts +0 -13
  207. package/src/utils/hmac/signPayload/index.ts +0 -1
  208. package/src/utils/hmac/signPayload/signPayload.ts +0 -16
  209. package/src/utils/hmac/verifySignature/index.ts +0 -1
  210. package/src/utils/hmac/verifySignature/verifySignature.ts +0 -24
  211. package/src/utils/index.ts +0 -29
  212. package/src/utils/jwt/index.ts +0 -2
  213. package/src/utils/jwt/jwt.test.ts +0 -28
  214. package/src/utils/jwt/jwt.ts +0 -182
  215. package/src/utils/jwt/jwt.types.ts +0 -21
  216. package/src/utils/report/index.ts +0 -3
  217. package/src/utils/report/output.ts +0 -45
  218. package/src/utils/report/output.types.ts +0 -70
  219. package/src/utils/report/report.test.ts +0 -133
  220. package/src/utils/report/report.ts +0 -133
  221. package/src/utils/report/report.types.ts +0 -13
  222. package/src/utils/request/index.ts +0 -1
  223. package/src/utils/request/request.test.ts +0 -26
  224. package/src/utils/request/request.ts +0 -48
  225. package/src/utils/secretManager/index.ts +0 -2
  226. package/src/utils/secretManager/secretLoader.ts +0 -62
  227. package/src/utils/secretManager/secretResolver.ts +0 -35
  228. package/src/utils/semverCompare/index.ts +0 -1
  229. package/src/utils/semverCompare/semverCompare.test.ts +0 -49
  230. package/src/utils/semverCompare/semverCompare.ts +0 -60
  231. package/src/utils/sendEmail/index.ts +0 -2
  232. package/src/utils/sendEmail/sendEmail.ts +0 -61
  233. package/src/utils/sendEmail/sendEmail.types.ts +0 -61
  234. package/src/utils/sendPush/index.ts +0 -2
  235. package/src/utils/sendPush/sendPush.ts +0 -20
  236. package/src/utils/sendPush/sendPush.types.ts +0 -25
  237. package/src/utils/tlsConfig/index.ts +0 -2
  238. package/src/utils/tlsConfig/tlsConfig.test.ts +0 -32
  239. package/src/utils/tlsConfig/tlsConfig.ts +0 -47
  240. package/src/utils/tlsConfig/tlsConfig.types.ts +0 -11
  241. package/src/utils/tlsConfig/tlsConfig.validate.ts +0 -25
  242. package/src/utils/tlsRequest/index.ts +0 -1
  243. package/src/utils/tlsRequest/tlsRequest.test.ts +0 -63
  244. package/src/utils/tlsRequest/tlsRequest.ts +0 -12
  245. package/src/utils/trimPathSlash/index.ts +0 -1
  246. package/src/utils/trimPathSlash/trimPathSlash.test.ts +0 -26
  247. package/src/utils/trimPathSlash/trimPathSlash.ts +0 -8
  248. package/test/env.ts +0 -53
  249. package/test/factory/index.ts +0 -8
  250. package/test/factory/sequelizeMeta.ts +0 -12
  251. package/test/hooks.ts +0 -35
  252. package/test/index.ts +0 -3
  253. package/test/stub/index.ts +0 -3
  254. package/test/stub/stubLocales.ts +0 -68
  255. package/test/stub/stubPubSub.ts +0 -7
  256. package/test/stub/stubStorage.ts +0 -77
  257. package/test/stub/stubStorage.types.ts +0 -11
  258. package/test/utils/app.ts +0 -31
  259. package/test/utils/index.ts +0 -1
  260. package/tsconfig.build.json +0 -5
  261. package/tsconfig.json +0 -32
@@ -1,23 +0,0 @@
1
- import express from 'express';
2
- import { describe } from 'mocha';
3
- import request from 'supertest';
4
- import { version as engineVersion } from '../../../package.json';
5
- import { version } from './version';
6
-
7
- describe('Middleware - version', () => {
8
- let serviceVersion: string;
9
-
10
- beforeEach(() => {
11
- serviceVersion = '1.0.1';
12
- process.env.BUILD_ID = serviceVersion;
13
- });
14
-
15
- it('should fetch the current version of the service', async () => {
16
- const app = express();
17
- app.use(version());
18
-
19
- await request(app)
20
- .get('/version')
21
- .expect(200, { version: serviceVersion, engineVersion });
22
- });
23
- });
@@ -1,12 +0,0 @@
1
- import { Router, Request, Response } from 'express';
2
- import { version as engineVersion } from '../../../package.json';
3
-
4
- /**
5
- * Path returning the version of the service
6
- * @return {Router}
7
- */
8
- export function version(): Router {
9
- return Router().use('/version', (req: Request, res: Response) => {
10
- res.json({ version: process.env.BUILD_ID, engineVersion });
11
- });
12
- }
@@ -1,49 +0,0 @@
1
- import { cleanEnv, ReporterOptions } from 'envalid';
2
- import { EngineError } from 'entities/EngineError';
3
- import { reportError } from 'utils/report';
4
-
5
- /**
6
- * Create an Envalid reporter
7
- * @param shouldExit - should the reporter exit the process on fail
8
- * @return Envalid reporter function
9
- */
10
- function createReporter(shouldExit: boolean) {
11
- return (reporter: ReporterOptions<unknown>): void => {
12
- const { errors } = reporter;
13
- const failedChecks = Object.keys(errors);
14
- const message = failedChecks.join(', ');
15
- if (failedChecks.length == 0) return;
16
- if (shouldExit) {
17
- reportError(
18
- new EngineError({
19
- message: `Check Environment Failed: ${message}`,
20
- data: failedChecks
21
- })
22
- );
23
- process.exit(1);
24
- }
25
- throw new EngineError({
26
- message: `Check Environment Failed: ${message}`,
27
- data: failedChecks
28
- });
29
- };
30
- }
31
-
32
- /**
33
- * Ensure the process.env is valid using Envalid.
34
- * if the validation fails it will log a helpful EngineError.emergency()
35
- * and exit the process with status-code 1.
36
- * @param validators - Envalid validators
37
- */
38
- export function checkEnvironment(validators = {}): void {
39
- cleanEnv(process.env, validators, { reporter: createReporter(true) });
40
- }
41
-
42
- /**
43
- * Ensure the process.env is valid using Envalid.
44
- * if the validation fails it will throw a EngineError.emergency()
45
- * @param validators - Envalid validators
46
- */
47
- export function assertEnvironment(validators = {}): void {
48
- cleanEnv({ ...process.env }, validators, { reporter: createReporter(false) });
49
- }
@@ -1,24 +0,0 @@
1
- import { Server } from 'http';
2
- import { Server as SecureServer } from 'https';
3
- import { expect } from 'chai';
4
- import { createHttpServer } from './createHttpServer';
5
- import { validateHttpEnvironment } from './createHttpServer.validate';
6
-
7
- describe('App - httpServer', () => {
8
- it('should create an httpServer', () => {
9
- delete process.env.TLS_SERVER_KEY;
10
- delete process.env.TLS_SERVER_CERT;
11
- const httpServer = createHttpServer();
12
- expect(httpServer instanceof Server).to.be.ok;
13
- });
14
-
15
- it('should create an httpsServer', () => {
16
- const httpServer = createHttpServer();
17
- expect(httpServer instanceof SecureServer).to.be.ok;
18
- });
19
-
20
- it('should accept TLS environment variables', () => {
21
- process.env.TLS_SERVER_KEY_PASSPHRASE = 'password';
22
- expect(validateHttpEnvironment).to.not.throw;
23
- });
24
- });
@@ -1,34 +0,0 @@
1
- import fs from 'fs';
2
- import { createServer, RequestListener, Server } from 'http';
3
- import {
4
- createServer as createSecureServer,
5
- Server as SecureServer
6
- } from 'https';
7
- import { Application } from 'express';
8
- import { validateHttpEnvironment } from './createHttpServer.validate';
9
-
10
- /** Create and configure an http/https server */
11
- export function createHttpServer(
12
- handler?: Application | RequestListener
13
- ): Server | SecureServer {
14
- // Validate the environment variables
15
- validateHttpEnvironment();
16
- // Create a https server if env var are specified
17
- if (process.env.TLS_SERVER_KEY && process.env.TLS_SERVER_CERT) {
18
- return createSecureServer(
19
- {
20
- key: fs.readFileSync(process.env.TLS_SERVER_KEY),
21
- passphrase: process.env.TLS_SERVER_KEY_PASSPHRASE,
22
- cert: fs.readFileSync(process.env.TLS_SERVER_CERT),
23
- ca: process.env.TLS_CA
24
- ? fs.readFileSync(process.env.TLS_CA)
25
- : undefined,
26
- requestCert: true,
27
- rejectUnauthorized: true
28
- },
29
- handler
30
- );
31
- } else {
32
- return createServer(handler);
33
- }
34
- }
@@ -1,17 +0,0 @@
1
- import { assertEnvironment, envAssert } from 'utils';
2
-
3
- /**
4
- * Environment variable validator for the creation of a HTTP(S) server
5
- */
6
- export function validateHttpEnvironment(): void {
7
- // We only check if there is at least the host specified
8
- if (process.env.TLS_SERVER_CERT && process.env.TLS_SERVER_CERT) {
9
- assertEnvironment({ TLS_SERVER_KEY: envAssert.isPath() });
10
- assertEnvironment({ TLS_SERVER_CERT: envAssert.isPath() });
11
- // Optional variables
12
- if (process.env.TLS_SERVER_KEY_PASSPHRASE) {
13
- assertEnvironment({ TLS_SERVER_KEY_PASSPHRASE: envAssert.isString() });
14
- }
15
- if (process.env.TLS_CA) assertEnvironment({ TLS_CA: envAssert.isPath() });
16
- }
17
- }
@@ -1 +0,0 @@
1
- export * from './createHttpServer';
@@ -1,20 +0,0 @@
1
- /** Deep sort the objects keys alphabetically */
2
- export function createSortedObject<T>(data: T): T {
3
- if (!(data instanceof Object)) throw new Error('Non');
4
- const result: Record<string, unknown> = {};
5
- Object.keys(data)
6
- .sort()
7
- .forEach((key: string) => {
8
- const value = (data as Record<string, unknown>)[key];
9
- if (
10
- typeof value !== 'object' ||
11
- value instanceof Array ||
12
- value === null
13
- ) {
14
- result[key] = value;
15
- } else {
16
- result[key] = createSortedObject(value);
17
- }
18
- });
19
- return result as T;
20
- }
@@ -1,47 +0,0 @@
1
- import { expect } from 'chai';
2
- import { faker } from '@faker-js/faker';
3
- import { createSortedObject } from './createSortedObject';
4
-
5
- describe('Utils - createSortedObject', () => {
6
- it('should sort an object', () => {
7
- const object: { [key: string]: string } = {};
8
- for (let i = 0; i < 20; i++) {
9
- object[faker.lorem.word()] = faker.lorem.word();
10
- }
11
- const sorted = createSortedObject(object);
12
- const expectedKeys = Object.keys(object).sort();
13
- const sortedKeys = Object.keys(sorted);
14
-
15
- expectedKeys.forEach((value, index) => {
16
- expect(value).to.equal(sortedKeys[index]);
17
- });
18
- });
19
-
20
- it('should deeply sort an object', () => {
21
- const object: {
22
- /** */
23
- x: { [key: string]: string };
24
- } = { x: {} };
25
- for (let i = 0; i < 20; i++) {
26
- object.x[faker.lorem.word()] = faker.lorem.word();
27
- }
28
- const sorted = createSortedObject(object);
29
- const expectedKeys = Object.keys(object.x).sort();
30
- const sortedKeys = Object.keys(sorted.x);
31
-
32
- expectedKeys.forEach((value, index) => {
33
- expect(value).to.equal(sortedKeys[index]);
34
- });
35
- });
36
-
37
- it('should handle null values', () => {
38
- const object = { a: null };
39
- expect(() => createSortedObject(object)).to.not.throw();
40
- });
41
-
42
- it('should not sort arrays', () => {
43
- const object = { a: ['z', 'a', 'o', 'd'] };
44
- const sorted = createSortedObject(object);
45
- expect(object).to.deep.equal(sorted);
46
- });
47
- });
@@ -1 +0,0 @@
1
- export * from './createSortedObject';
@@ -1,209 +0,0 @@
1
- // import path from 'path';
2
- // import { expect } from 'chai';
3
- // import mockFs, { restore } from 'mock-fs';
4
- // import mockRequire from 'mock-require';
5
- // import {
6
- // runPendingMigrations,
7
- // rollbackMigrations,
8
- // testClearDB
9
- // } from './dbMigration';
10
- // import { SequelizeMeta } from 'db/models';
11
- // import { factory } from 'test';
12
-
13
- // describe('Utils - DB Migration', function () {
14
- // beforeEach(async () => {
15
- // await testClearDB({ includeMetadata: true });
16
-
17
- // process.env.BUILD_ID = '1.5.0';
18
-
19
- // const basePath = path.join(process.cwd(), './src/db/migrations');
20
- // // Requires use the real filesystem and need to be mocked
21
- // const requiredContent = {
22
- // // eslint-disable-next-line @typescript-eslint/no-empty-function
23
- // up: async (): Promise<void> => {},
24
- // // eslint-disable-next-line @typescript-eslint/no-empty-function
25
- // down: async (): Promise<void> => {}
26
- // };
27
- // mockRequire(`${basePath}/1-test.js`, requiredContent);
28
- // mockRequire(`${basePath}/2-test.js`, requiredContent);
29
- // mockRequire(`${basePath}/3-test.ts`, requiredContent);
30
- // // Umzug checks that the files is on the FS
31
- // mockFs({
32
- // [basePath]: { '1-test.js': '', '2-test.js': '', '3-test.ts': '' }
33
- // });
34
- // });
35
-
36
- // afterEach(() => {
37
- // restore();
38
- // mockRequire.stopAll();
39
- // });
40
-
41
- // describe('runPendingMigrations', function () {
42
- // // it('should run the migrations when there are no history', async () => {
43
- // // await runPendingMigrations();
44
-
45
- // // const migrations = await SequelizeMeta.findAll();
46
-
47
- // // expect(migrations).to.have.length(3);
48
- // // migrations.forEach((migration) => {
49
- // // expect(['1-test.js', '2-test.js', '3-test.ts']).to.include(migration.name);
50
- // // expect(migration.version).to.equal(process.env.BUILD_ID);
51
- // // });
52
- // // });
53
-
54
- // it('should prefer migrations in the prod directory', async () => {
55
- // const prodBasePath = path.join(process.cwd(), './dist/db/migrations');
56
- // // Requires use the real filesystem and need to be mocked
57
- // const requiredContent = {
58
- // // eslint-disable-next-line @typescript-eslint/no-empty-function
59
- // up: async (): Promise<void> => {},
60
- // // eslint-disable-next-line @typescript-eslint/no-empty-function
61
- // down: async (): Promise<void> => {}
62
- // };
63
- // mockRequire(`${prodBasePath}/1-prod-test.js`, requiredContent);
64
- // mockRequire(`${prodBasePath}/2-prod-test.js`, requiredContent);
65
- // mockRequire(`${prodBasePath}/3-prod-test.js`, requiredContent);
66
- // // Umzug checks that the files is on the FS
67
- // mockFs({
68
- // [prodBasePath]: {
69
- // '1-prod-test.js': '',
70
- // '2-prod-test.js': '',
71
- // '3-prod-test.js': ''
72
- // }
73
- // });
74
-
75
- // await runPendingMigrations();
76
-
77
- // const migrations = await SequelizeMeta.findAll();
78
-
79
- // expect(migrations).to.have.length(3);
80
- // migrations.forEach((migration) => {
81
- // expect([
82
- // '1-prod-test.js',
83
- // '2-prod-test.js',
84
- // '3-prod-test.js'
85
- // ]).to.include(migration.name);
86
- // expect(migration.version).to.equal(process.env.BUILD_ID);
87
- // });
88
-
89
- // it('should allow to specify a custom directory', async () => {
90
- // const customBasePath = path.join(process.cwd(), './migrations');
91
- // process.env.DB_MIGRATIONS_DIR = customBasePath;
92
-
93
- // // Requires use the real filesystem and need to be mocked
94
- // const requiredContent = {
95
- // // eslint-disable-next-line @typescript-eslint/no-empty-function
96
- // up: async (): Promise<void> => {},
97
- // // eslint-disable-next-line @typescript-eslint/no-empty-function
98
- // down: async (): Promise<void> => {}
99
- // };
100
- // mockRequire(`${customBasePath}/1-custom-test.js`, requiredContent);
101
- // mockRequire(`${customBasePath}/2-custom-test.js`, requiredContent);
102
- // mockRequire(`${customBasePath}/3-custom-test.js`, requiredContent);
103
- // // Umzug checks that the files is on the FS
104
- // mockFs({
105
- // [customBasePath]: {
106
- // '1-custom-test.js': '',
107
- // '2-custom-test.js': '',
108
- // '3-custom-test.js': ''
109
- // }
110
- // });
111
-
112
- // await runPendingMigrations();
113
-
114
- // const migrations = await SequelizeMeta.findAll();
115
-
116
- // expect(migrations).to.have.length(3);
117
- // migrations.forEach((migration) => {
118
- // expect([
119
- // '1-custom-test.js',
120
- // '2-custom-test.js',
121
- // '3-custom-test.js'
122
- // ]).to.include(migration.name);
123
- // expect(migration.version).to.equal(process.env.BUILD_ID);
124
- // });
125
- // });
126
- // });
127
- // });
128
-
129
- // describe('rollbackMigrations', function () {
130
- // it('should not rollback previous migrations', async () => {
131
- // await factory.create('sequelizeMeta', {
132
- // name: '1-test.js',
133
- // version: '1.4.0'
134
- // });
135
- // await factory.create('sequelizeMeta', {
136
- // name: '2-test.js',
137
- // version: process.env.BUILD_ID
138
- // });
139
-
140
- // await rollbackMigrations();
141
-
142
- // // expect(rolledBack).to.have.length(0);
143
- // });
144
-
145
- // it('should rollback the higher migrations', async () => {
146
- // await factory.create('sequelizeMeta', {
147
- // name: '1-test.js',
148
- // version: '1.5.0'
149
- // });
150
- // await factory.create('sequelizeMeta', {
151
- // name: '2-test.js',
152
- // version: process.env.BUILD_ID
153
- // });
154
- // await factory.create('sequelizeMeta', {
155
- // name: '3-test.ts',
156
- // version: '1.5.1'
157
- // });
158
-
159
- // await rollbackMigrations();
160
-
161
- // // expect(rolledBack).to.have.length(1);
162
- // // expect(rolledBack[0].file).to.equal('3-test.ts');
163
- // });
164
-
165
- // it('should rollback multiple migrations with higher version', async () => {
166
- // await factory.create('sequelizeMeta', {
167
- // name: '1-test.js',
168
- // version: process.env.BUILD_ID
169
- // });
170
- // await factory.create('sequelizeMeta', {
171
- // name: '2-test.js',
172
- // version: '1.5.2'
173
- // });
174
- // await factory.create('sequelizeMeta', {
175
- // name: '3-test.ts',
176
- // version: '1.6.0'
177
- // });
178
-
179
- // await rollbackMigrations();
180
-
181
- // // expect(rolledBack).to.have.length(2);
182
- // // rolledBack.forEach((migration) => {
183
- // // expect(['2-test.js', '3-test.ts']).to.include(migration.file);
184
- // // });
185
- // });
186
-
187
- // it('should handle pre-release (alpha<beta)', async () => {
188
- // process.env.BUILD_ID = '1.5.0-alpha.2';
189
-
190
- // await factory.create('sequelizeMeta', {
191
- // name: '1-test.js',
192
- // version: '1.5.0-alpha.1'
193
- // });
194
- // await factory.create('sequelizeMeta', {
195
- // name: '2-test.js',
196
- // version: process.env.BUILD_ID
197
- // });
198
- // await factory.create('sequelizeMeta', {
199
- // name: '3-test.ts',
200
- // version: '1.5.0-beta.1'
201
- // });
202
-
203
- // await rollbackMigrations();
204
-
205
- // // expect(rolledBack).to.have.length(1);
206
- // // expect(rolledBack[0].file).to.equal('3-test.ts');
207
- // });
208
- // });
209
- // });
@@ -1,199 +0,0 @@
1
- /* eslint-disable @typescript-eslint/no-require-imports */
2
- // Register ts-node at the top of runMigrations.ts
3
- require('ts-node/register');
4
-
5
- import { existsSync, lstatSync } from 'fs';
6
- import { join } from 'path';
7
- import { Sequelize, Transaction } from 'sequelize';
8
- import { Umzug, SequelizeStorage } from 'umzug';
9
- import { ClearDbOptions, RecreateDbOptions } from './dbMigration.types';
10
- import { migrateMetadataTable } from './migrateMetadataTable';
11
- import { SequelizeMeta } from 'db/models';
12
- import { EngineError } from 'entities/EngineError';
13
- import { sequelize } from 'entities/Sequelize';
14
- import { reportDebug } from 'utils/report';
15
- import { semverCompare } from 'utils/semverCompare';
16
-
17
- const namespace = 'engine:utils:dbMigration';
18
-
19
- function getMigrationPaths(): Array<string> | undefined {
20
- // We look between possibilities for the first directory that exists and matches our expectations
21
- // First a user specified one, then the production default, then the development default
22
- const prodDefaultPath = join(process.cwd(), './dist/db/migrations');
23
- const devDefaultPath = join(process.cwd(), './src/db/migrations');
24
- const path = [
25
- process.env.DB_MIGRATIONS_DIR,
26
- process.env.NODE_ENV === 'prod' ? prodDefaultPath : devDefaultPath
27
- ].filter((path) => path && existsSync(path) && lstatSync(path).isDirectory());
28
- reportDebug({
29
- namespace,
30
- message: 'Obtaining Umzug migration options',
31
- data: {
32
- path,
33
- prodPath: prodDefaultPath,
34
- devPath: devDefaultPath,
35
- customPath: process.env.DB_MIGRATIONS_DIR
36
- }
37
- });
38
- return path.map((p) =>
39
- process.env.NODE_ENV === 'prod' ? `${p}/*.js` : `${p}/*.ts`
40
- );
41
- }
42
-
43
- /** Run all the non-executed migrations one by one */
44
- export async function runPendingMigrations(): Promise<void> {
45
- if (!sequelize)
46
- throw new EngineError({ message: 'Sequelize is not initialized' });
47
- // First make sure that the metadata table is up to date
48
- await migrateMetadataTable(sequelize);
49
- const migrationPaths = getMigrationPaths();
50
-
51
- if (!migrationPaths || migrationPaths.length <= 0) {
52
- reportDebug({
53
- namespace,
54
- message: 'No valid migration paths found.',
55
- data: { migrationPaths }
56
- });
57
- return;
58
- }
59
-
60
- migrationPaths?.forEach(async (path) => {
61
- const migrator = new Umzug({
62
- migrations: {
63
- glob: path,
64
- resolve: ({ name, path, context }) => {
65
- // Use require to import the migration file
66
- const migration = require(path || '');
67
- return {
68
- name,
69
- up: async () => migration.up(context),
70
- down: async () => migration.down(context)
71
- };
72
- }
73
- },
74
- context: sequelize.getQueryInterface(),
75
- storage: new SequelizeStorage({ sequelize }),
76
- logger: console
77
- });
78
-
79
- reportDebug({
80
- namespace,
81
- message: 'Starting pending database migrations',
82
- data: { path }
83
- });
84
- await migrator.up();
85
- console.log('Db Migration Completed');
86
- });
87
- }
88
-
89
- /** Rollback all migrations up to a specified target version */
90
- export async function rollbackMigrations(): Promise<void> {
91
- if (!sequelize)
92
- throw new EngineError({ message: 'Sequelize is not initialized' });
93
- if (!process.env.BUILD_ID)
94
- throw new EngineError({ message: 'BUILD_ID is not defined' });
95
-
96
- // Fetch executed migrations in ascending order
97
- const migrations = await SequelizeMeta.findAll({
98
- order: [['name', 'ASC']],
99
- raw: true
100
- });
101
- const rollbackUntil = migrations.find(
102
- (migration) =>
103
- migration.version &&
104
- semverCompare(migration.version, process.env.BUILD_ID as string) === 1
105
- );
106
-
107
- if (!rollbackUntil) {
108
- reportDebug({
109
- namespace,
110
- message: 'No rollback target found for the current BUILD_ID.',
111
- data: { buildId: process.env.BUILD_ID }
112
- });
113
- return;
114
- }
115
-
116
- const migrationPaths = getMigrationPaths();
117
-
118
- if (!migrationPaths || migrationPaths.length <= 0) {
119
- reportDebug({
120
- namespace,
121
- message: 'No valid migration paths found for rollback.',
122
- data: { migrationPaths }
123
- });
124
- return;
125
- }
126
-
127
- migrationPaths.forEach(async (path) => {
128
- const migrator = new Umzug({
129
- migrations: {
130
- glob: path,
131
- resolve: ({ name, path, context }) => {
132
- const migration = require(path || '');
133
- return {
134
- name,
135
- up: async () => migration.up(context),
136
- down: async () => migration.down(context)
137
- };
138
- }
139
- },
140
- context: sequelize.getQueryInterface(),
141
- storage: new SequelizeStorage({ sequelize }),
142
- logger: console
143
- });
144
-
145
- reportDebug({
146
- namespace,
147
- message: `Rolling back migrations up to: ${rollbackUntil.name}`,
148
- data: { path }
149
- });
150
-
151
- await migrator.down({ to: rollbackUntil.name });
152
- });
153
- }
154
-
155
- /**
156
- * Recreate the whole database
157
- * Quick way to make sure that we are working on a clean database
158
- * /!\ Should only be used when running tests
159
- */
160
- export async function testRecreateDB(
161
- options: RecreateDbOptions = {}
162
- ): Promise<void> {
163
- if (!sequelize)
164
- throw new EngineError({ message: 'Sequelize is not initialized' });
165
- await sequelize.query(
166
- `DROP SCHEMA public${process.env.SQL_TYPE === 'postgres' ? ' CASCADE' : ''}`
167
- );
168
- await sequelize.query(`CREATE SCHEMA public`);
169
- if (!options.clean) await runPendingMigrations();
170
- }
171
-
172
- /**
173
- * Empty all the schemas in the database
174
- * Quick way to flush the database data while keep the structure
175
- * /!\ Should only be used when running tests
176
- */
177
- export async function testClearDB(options: ClearDbOptions = {}): Promise<void> {
178
- if (!sequelize)
179
- throw new EngineError({ message: 'Sequelize is not initialized' });
180
- await sequelize.transaction(clearDbTransaction(sequelize, options));
181
- }
182
-
183
- /** DB clearing transaction */
184
- function clearDbTransaction(sequelize: Sequelize, options: ClearDbOptions) {
185
- return async (t: Transaction): Promise<void> => {
186
- for (const model of Object.keys(sequelize.models)) {
187
- // We ignore the migration metadata schema
188
- if (!options.includeMetadata && model === 'sequelizeMeta') continue;
189
- const table = sequelize.models[model].tableName;
190
- await sequelize.query(
191
- `TRUNCATE ${table}${process.env.SQL_TYPE === 'postgres' ? ' CASCADE' : ''};`,
192
- {
193
- raw: true,
194
- transaction: t
195
- }
196
- );
197
- }
198
- };
199
- }
@@ -1,11 +0,0 @@
1
- /** Options to recreate the database */
2
- export interface RecreateDbOptions {
3
- /** Do not run the migrations, leave the DB empty */
4
- clean?: boolean;
5
- }
6
-
7
- /** Options to clear the database */
8
- export interface ClearDbOptions {
9
- /** Also truncate the migration metadata table. This should only be used when testing on the metadata table itself */
10
- includeMetadata?: boolean;
11
- }
@@ -1,2 +0,0 @@
1
- export * from './dbMigration';
2
- export * from './dbMigration.types';
@@ -1 +0,0 @@
1
- export * from './migrateMetadataTable';