mock-config-server 3.0.1 → 3.1.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 (146) hide show
  1. package/LICENSE +21 -21
  2. package/README.md +614 -502
  3. package/dist/bin/bin.js +8 -3
  4. package/dist/bin/build.js +51 -45
  5. package/dist/bin/cli.js +37 -44
  6. package/dist/bin/helpers/index.js +36 -17
  7. package/dist/bin/helpers/resolveConfigFile.js +20 -17
  8. package/dist/bin/helpers/resolveConfigFilePath.js +12 -35
  9. package/dist/bin/helpers/resolveExportsFromSourceCode.js +11 -8
  10. package/dist/bin/resolveConfigFilePath/resolveConfigFilePath.js +12 -35
  11. package/dist/bin/run.js +17 -12
  12. package/dist/bin/validateMockServerConfig/helpers/index.js +25 -16
  13. package/dist/bin/validateMockServerConfig/helpers/isCheckModeValid/index.js +14 -15
  14. package/dist/bin/validateMockServerConfig/helpers/isCheckModeValid/isCheckModeValid.js +8 -6
  15. package/dist/bin/validateMockServerConfig/helpers/isDescriptorValueValid/index.js +14 -15
  16. package/dist/bin/validateMockServerConfig/helpers/isDescriptorValueValid/isDescriptorValueValid.js +15 -18
  17. package/dist/bin/validateMockServerConfig/validateBaseUrl/validateBaseUrl.js +12 -9
  18. package/dist/bin/validateMockServerConfig/validateCors/validateCors.js +75 -73
  19. package/dist/bin/validateMockServerConfig/validateDatabaseConfig/validateDatabaseConfig.d.ts +1 -0
  20. package/dist/bin/validateMockServerConfig/validateDatabaseConfig/validateDatabaseConfig.js +45 -0
  21. package/dist/bin/validateMockServerConfig/validateGraphqlConfig/validateGraphqlConfig.js +47 -43
  22. package/dist/bin/validateMockServerConfig/validateGraphqlConfig/validateRoutes/validateRoutes.js +90 -83
  23. package/dist/bin/validateMockServerConfig/validateInterceptors/validateInterceptors.js +22 -16
  24. package/dist/bin/validateMockServerConfig/validateMockServerConfig.js +29 -27
  25. package/dist/bin/validateMockServerConfig/validatePort/validatePort.js +9 -6
  26. package/dist/bin/validateMockServerConfig/validateRestConfig/validateRestConfig.js +52 -47
  27. package/dist/bin/validateMockServerConfig/validateRestConfig/validateRoutes/validateRoutes.js +94 -87
  28. package/dist/bin/validateMockServerConfig/validateStaticPath/validateStaticPath.js +43 -34
  29. package/dist/src/core/database/createDatabaseRoutes/createDatabaseRoutes.d.ts +3 -0
  30. package/dist/src/core/database/createDatabaseRoutes/createDatabaseRoutes.js +33 -0
  31. package/dist/src/core/database/createDatabaseRoutes/helpers/array/createNewId/createNewId.d.ts +4 -0
  32. package/dist/src/core/database/createDatabaseRoutes/helpers/array/createNewId/createNewId.js +16 -0
  33. package/dist/src/core/database/createDatabaseRoutes/helpers/array/findIndexById/findIndexById.d.ts +4 -0
  34. package/dist/src/core/database/createDatabaseRoutes/helpers/array/findIndexById/findIndexById.js +8 -0
  35. package/dist/src/core/database/createDatabaseRoutes/helpers/array/index.d.ts +3 -0
  36. package/dist/src/core/database/createDatabaseRoutes/helpers/array/index.js +38 -0
  37. package/dist/src/core/database/createDatabaseRoutes/helpers/array/isIndex/isIndex.d.ts +1 -0
  38. package/dist/src/core/database/createDatabaseRoutes/helpers/array/isIndex/isIndex.js +8 -0
  39. package/dist/src/core/database/createDatabaseRoutes/helpers/createNestedDatabaseRoutes/createNestedDatabaseRoutes.d.ts +4 -0
  40. package/dist/src/core/database/createDatabaseRoutes/helpers/createNestedDatabaseRoutes/createNestedDatabaseRoutes.js +88 -0
  41. package/dist/src/core/database/createDatabaseRoutes/helpers/createRewrittenDatabaseRoutes/createRewrittenDatabaseRoutes.d.ts +2 -0
  42. package/dist/src/core/database/createDatabaseRoutes/helpers/createRewrittenDatabaseRoutes/createRewrittenDatabaseRoutes.js +12 -0
  43. package/dist/src/core/database/createDatabaseRoutes/helpers/createShallowDatabaseRoutes/createShallowDatabaseRoutes.d.ts +4 -0
  44. package/dist/src/core/database/createDatabaseRoutes/helpers/createShallowDatabaseRoutes/createShallowDatabaseRoutes.js +38 -0
  45. package/dist/src/core/database/createDatabaseRoutes/helpers/index.d.ts +5 -0
  46. package/dist/src/core/database/createDatabaseRoutes/helpers/index.js +60 -0
  47. package/dist/src/core/database/createDatabaseRoutes/helpers/splitDatabaseByNesting/splitDatabaseByNesting.d.ts +5 -0
  48. package/dist/src/core/database/createDatabaseRoutes/helpers/splitDatabaseByNesting/splitDatabaseByNesting.js +30 -0
  49. package/dist/src/core/database/createDatabaseRoutes/storages/File/FileStorage.d.ts +11 -0
  50. package/dist/src/core/database/createDatabaseRoutes/storages/File/FileStorage.js +64 -0
  51. package/dist/src/core/database/createDatabaseRoutes/storages/File/FileWriter.d.ts +11 -0
  52. package/dist/src/core/database/createDatabaseRoutes/storages/File/FileWriter.js +58 -0
  53. package/dist/src/core/database/createDatabaseRoutes/storages/Memory/MemoryStorage.d.ts +10 -0
  54. package/dist/src/core/database/createDatabaseRoutes/storages/Memory/MemoryStorage.js +54 -0
  55. package/dist/src/core/database/createDatabaseRoutes/storages/index.d.ts +2 -0
  56. package/dist/src/core/database/createDatabaseRoutes/storages/index.js +27 -0
  57. package/dist/src/core/database/index.d.ts +1 -0
  58. package/dist/src/core/database/index.js +16 -0
  59. package/dist/src/core/graphql/createGraphQLRoutes/createGraphQLRoutes.js +96 -83
  60. package/dist/src/core/graphql/createGraphQLRoutes/helpers/index.js +14 -15
  61. package/dist/src/core/graphql/createGraphQLRoutes/helpers/prepareGraphQLRequestConfigs/prepareGraphQLRequestConfigs.js +36 -30
  62. package/dist/src/core/graphql/index.js +14 -15
  63. package/dist/src/core/middlewares/cookieParseMiddleware/cookieParseMiddleware.js +15 -13
  64. package/dist/src/core/middlewares/cookieParseMiddleware/helpers/index.js +14 -15
  65. package/dist/src/core/middlewares/cookieParseMiddleware/helpers/parseCookie/parseCookie.js +16 -14
  66. package/dist/src/core/middlewares/corsMiddleware/corsMiddleware.js +48 -41
  67. package/dist/src/core/middlewares/corsMiddleware/helpers/getAllowedOrigins/getAllowedOrigins.js +13 -10
  68. package/dist/src/core/middlewares/corsMiddleware/helpers/index.js +14 -15
  69. package/dist/src/core/middlewares/destroyerMiddleware/destroyerMiddleware.js +21 -18
  70. package/dist/src/core/middlewares/errorMiddleware/errorMiddleware.js +18 -15
  71. package/dist/src/core/middlewares/index.js +92 -23
  72. package/dist/src/core/middlewares/noCorsMiddleware/noCorsMiddleware.js +21 -21
  73. package/dist/src/core/middlewares/notFoundMiddleware/helpers/getGraphqlUrlSuggestions/getGraphqlUrlSuggestions.js +24 -16
  74. package/dist/src/core/middlewares/notFoundMiddleware/helpers/getLevenshteinDistance/getLevenshteinDistance.js +78 -74
  75. package/dist/src/core/middlewares/notFoundMiddleware/helpers/getRestUrlSuggestions/getRestUrlSuggestions.js +36 -31
  76. package/dist/src/core/middlewares/notFoundMiddleware/helpers/getRestUrlSuggestions/helpers/getActualRestUrlMeaningfulString/getActualRestUrlMeaningfulString.js +6 -5
  77. package/dist/src/core/middlewares/notFoundMiddleware/helpers/getRestUrlSuggestions/helpers/getPatternRestUrlMeaningfulString/getPatternRestUrlMeaningfulString.js +6 -3
  78. package/dist/src/core/middlewares/notFoundMiddleware/helpers/getRestUrlSuggestions/helpers/index.js +25 -16
  79. package/dist/src/core/middlewares/notFoundMiddleware/helpers/index.js +36 -17
  80. package/dist/src/core/middlewares/notFoundMiddleware/notFoundMiddleware.js +63 -48
  81. package/dist/src/core/middlewares/requestInterceptorMiddleware/requestInterceptorMiddleware.js +13 -7
  82. package/dist/src/core/middlewares/staticMiddleware/staticMiddleware.js +26 -25
  83. package/dist/src/core/rest/createRestRoutes/createRestRoutes.js +71 -56
  84. package/dist/src/core/rest/createRestRoutes/helpers/index.js +14 -15
  85. package/dist/src/core/rest/createRestRoutes/helpers/prepareRestRequestConfigs/prepareRestRequestConfigs.js +38 -32
  86. package/dist/src/core/rest/index.js +14 -15
  87. package/dist/src/index.js +36 -17
  88. package/dist/src/server/createMockServer/createMockServer.js +74 -53
  89. package/dist/src/server/index.js +25 -16
  90. package/dist/src/server/startMockServer/startMockServer.js +20 -17
  91. package/dist/src/static/views/assets/icons/scheme-dark.svg +3 -3
  92. package/dist/src/static/views/assets/icons/scheme-light.svg +3 -3
  93. package/dist/src/static/views/assets/styles/global.css +88 -88
  94. package/dist/src/static/views/components/header/index.css +55 -55
  95. package/dist/src/static/views/components/header/index.ejs +39 -39
  96. package/dist/src/static/views/components/header/index.js +1 -1
  97. package/dist/src/static/views/features/scheme/dark.css +12 -12
  98. package/dist/src/static/views/features/scheme/index.ejs +3 -3
  99. package/dist/src/static/views/features/scheme/index.js +31 -31
  100. package/dist/src/static/views/features/scheme/light.css +12 -12
  101. package/dist/src/static/views/features/tab/index.css +30 -30
  102. package/dist/src/static/views/features/tab/index.ejs +1 -1
  103. package/dist/src/static/views/features/tab/index.js +12 -12
  104. package/dist/src/static/views/pages/404/index.css +10 -10
  105. package/dist/src/static/views/pages/404/index.ejs +84 -84
  106. package/dist/src/utils/constants/appPath.js +6 -2
  107. package/dist/src/utils/constants/checkModes.js +21 -30
  108. package/dist/src/utils/constants/default.js +15 -11
  109. package/dist/src/utils/constants/index.js +36 -17
  110. package/dist/src/utils/helpers/asyncHandler.js +6 -3
  111. package/dist/src/utils/helpers/config/index.js +14 -15
  112. package/dist/src/utils/helpers/config/resolveEntityValues/resolveEntityValues.js +109 -122
  113. package/dist/src/utils/helpers/entities/convertToEntityDescriptor/convertToEntityDescriptor.js +10 -6
  114. package/dist/src/utils/helpers/entities/index.js +25 -16
  115. package/dist/src/utils/helpers/entities/isEntityDescriptor/isEntityDescriptor.js +7 -4
  116. package/dist/src/utils/helpers/graphql/getGraphQLInput/getGraphQLInput.js +28 -18
  117. package/dist/src/utils/helpers/graphql/index.js +36 -17
  118. package/dist/src/utils/helpers/graphql/parseGraphQLRequest/parseGraphQLRequest.js +11 -9
  119. package/dist/src/utils/helpers/graphql/parseQuery/parseQuery.js +20 -17
  120. package/dist/src/utils/helpers/index.js +114 -25
  121. package/dist/src/utils/helpers/interceptors/callRequestInterceptor/callRequestInterceptor.js +22 -16
  122. package/dist/src/utils/helpers/interceptors/callResponseInterceptors/callResponseInterceptors.js +56 -48
  123. package/dist/src/utils/helpers/interceptors/helpers/setDelay.js +8 -5
  124. package/dist/src/utils/helpers/interceptors/index.js +25 -16
  125. package/dist/src/utils/helpers/isPlainObject/isPlainObject.js +6 -6
  126. package/dist/src/utils/helpers/isPrimitive/isPrimitive.js +6 -3
  127. package/dist/src/utils/helpers/isRegExp/isRegExp.js +6 -3
  128. package/dist/src/utils/helpers/sleep.js +7 -4
  129. package/dist/src/utils/helpers/url/convertWin32PathToUnix/convertWin32PathToUnix.js +6 -6
  130. package/dist/src/utils/helpers/url/getUrlParts/getUrlParts.js +7 -4
  131. package/dist/src/utils/helpers/url/index.js +47 -18
  132. package/dist/src/utils/helpers/url/removeLeadingAndTrailingSlashes/removeLeadingAndTrailingSlashes.js +6 -3
  133. package/dist/src/utils/helpers/url/urlJoin/urlJoin.js +11 -10
  134. package/dist/src/utils/types/checkModes.js +1 -2
  135. package/dist/src/utils/types/database.d.ts +6 -0
  136. package/dist/src/utils/types/database.js +1 -0
  137. package/dist/src/utils/types/graphql.js +1 -2
  138. package/dist/src/utils/types/index.d.ts +1 -0
  139. package/dist/src/utils/types/index.js +80 -20
  140. package/dist/src/utils/types/interceptors.js +1 -2
  141. package/dist/src/utils/types/rest.js +1 -2
  142. package/dist/src/utils/types/server.d.ts +5 -0
  143. package/dist/src/utils/types/server.js +1 -2
  144. package/dist/src/utils/types/values.js +1 -2
  145. package/package.json +130 -113
  146. package/dist/index.js +0 -17
@@ -1,9 +1,12 @@
1
1
  "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
3
6
  exports.validatePort = void 0;
4
- const validatePort = (port) => {
5
- if (typeof port !== 'number' && typeof port !== 'undefined') {
6
- throw new Error('port');
7
- }
7
+ const validatePort = port => {
8
+ if (typeof port !== 'number' && typeof port !== 'undefined') {
9
+ throw new Error('port');
10
+ }
8
11
  };
9
- exports.validatePort = validatePort;
12
+ exports.validatePort = validatePort;
@@ -1,52 +1,57 @@
1
1
  "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
3
6
  exports.validateRestConfig = void 0;
4
- const helpers_1 = require("../../../src/utils/helpers");
5
- const validateBaseUrl_1 = require("../validateBaseUrl/validateBaseUrl");
6
- const validateInterceptors_1 = require("../validateInterceptors/validateInterceptors");
7
- const validateRoutes_1 = require("./validateRoutes/validateRoutes");
8
- const validateConfigs = (configs) => {
9
- const isConfigsArray = Array.isArray(configs);
10
- if (isConfigsArray) {
11
- configs.forEach((config, index) => {
12
- const { path, method } = config;
13
- const isPathStringWithLeadingSlash = typeof path === 'string' && path.startsWith('/');
14
- if (!isPathStringWithLeadingSlash && !(path instanceof RegExp)) {
15
- throw new Error(`configs[${index}].path`);
16
- }
17
- // important:
18
- // compare without 'toLowerCase' because Express methods names is case-sensitive
19
- const allowedMethods = ['get', 'post', 'delete', 'put', 'patch', 'options'];
20
- const isMethodAllowed = typeof method === 'string' && allowedMethods.includes(method);
21
- if (!isMethodAllowed) {
22
- throw new Error(`configs[${index}].method`);
23
- }
24
- try {
25
- (0, validateRoutes_1.validateRoutes)(config.routes, method);
26
- (0, validateInterceptors_1.validateInterceptors)(config.interceptors);
27
- }
28
- catch (error) {
29
- throw new Error(`configs[${index}].${error.message}`);
30
- }
31
- });
32
- return;
33
- }
34
- throw new Error('configs');
7
+ var _helpers = require("../../../src/utils/helpers");
8
+ var _validateBaseUrl = require("../validateBaseUrl/validateBaseUrl");
9
+ var _validateInterceptors = require("../validateInterceptors/validateInterceptors");
10
+ var _validateRoutes = require("./validateRoutes/validateRoutes");
11
+ const validateConfigs = configs => {
12
+ const isConfigsArray = Array.isArray(configs);
13
+ if (isConfigsArray) {
14
+ configs.forEach((config, index) => {
15
+ const {
16
+ path,
17
+ method
18
+ } = config;
19
+ const isPathStringWithLeadingSlash = typeof path === 'string' && path.startsWith('/');
20
+ if (!isPathStringWithLeadingSlash && !(path instanceof RegExp)) {
21
+ throw new Error(`configs[${index}].path`);
22
+ }
23
+
24
+ // important:
25
+ // compare without 'toLowerCase' because Express methods names is case-sensitive
26
+ const allowedMethods = ['get', 'post', 'delete', 'put', 'patch', 'options'];
27
+ const isMethodAllowed = typeof method === 'string' && allowedMethods.includes(method);
28
+ if (!isMethodAllowed) {
29
+ throw new Error(`configs[${index}].method`);
30
+ }
31
+ try {
32
+ (0, _validateRoutes.validateRoutes)(config.routes, method);
33
+ (0, _validateInterceptors.validateInterceptors)(config.interceptors);
34
+ } catch (error) {
35
+ throw new Error(`configs[${index}].${error.message}`);
36
+ }
37
+ });
38
+ return;
39
+ }
40
+ throw new Error('configs');
35
41
  };
36
- const validateRestConfig = (restConfig) => {
37
- const isRestConfigObject = (0, helpers_1.isPlainObject)(restConfig);
38
- if (isRestConfigObject) {
39
- try {
40
- (0, validateBaseUrl_1.validateBaseUrl)(restConfig.baseUrl);
41
- validateConfigs(restConfig.configs);
42
- }
43
- catch (error) {
44
- throw new Error(`rest.${error.message}`);
45
- }
46
- return;
47
- }
48
- if (typeof restConfig !== 'undefined') {
49
- throw new Error('rest');
42
+ const validateRestConfig = restConfig => {
43
+ const isRestConfigObject = (0, _helpers.isPlainObject)(restConfig);
44
+ if (isRestConfigObject) {
45
+ try {
46
+ (0, _validateBaseUrl.validateBaseUrl)(restConfig.baseUrl);
47
+ validateConfigs(restConfig.configs);
48
+ } catch (error) {
49
+ throw new Error(`rest.${error.message}`);
50
50
  }
51
+ return;
52
+ }
53
+ if (typeof restConfig !== 'undefined') {
54
+ throw new Error('rest');
55
+ }
51
56
  };
52
- exports.validateRestConfig = validateRestConfig;
57
+ exports.validateRestConfig = validateRestConfig;
@@ -1,101 +1,108 @@
1
1
  "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
3
6
  exports.validateRoutes = void 0;
4
- const helpers_1 = require("../../../../src/utils/helpers");
5
- const helpers_2 = require("../../helpers");
6
- const validateInterceptors_1 = require("../../validateInterceptors/validateInterceptors");
7
+ var _helpers = require("../../../../src/utils/helpers");
8
+ var _helpers2 = require("../../helpers");
9
+ var _validateInterceptors = require("../../validateInterceptors/validateInterceptors");
7
10
  const ALLOWED_ENTITIES_BY_METHOD = {
8
- get: ['headers', 'cookies', 'query', 'params'],
9
- delete: ['headers', 'cookies', 'query', 'params'],
10
- post: ['headers', 'cookies', 'query', 'params', 'body'],
11
- put: ['headers', 'cookies', 'query', 'params', 'body'],
12
- patch: ['headers', 'cookies', 'query', 'params', 'body'],
13
- options: ['headers', 'cookies', 'query', 'params']
11
+ get: ['headers', 'cookies', 'query', 'params'],
12
+ delete: ['headers', 'cookies', 'query', 'params'],
13
+ post: ['headers', 'cookies', 'query', 'params', 'body'],
14
+ put: ['headers', 'cookies', 'query', 'params', 'body'],
15
+ patch: ['headers', 'cookies', 'query', 'params', 'body'],
16
+ options: ['headers', 'cookies', 'query', 'params']
14
17
  };
15
18
  const validateEntity = (entity, entityName) => {
16
- const { checkMode: topLevelCheckMode, value: topLevelValue } = (0, helpers_1.convertToEntityDescriptor)(entity);
17
- const isBody = entityName === 'body';
18
- const isTopLevelDescriptor = (0, helpers_1.isEntityDescriptor)(entity);
19
- if (isTopLevelDescriptor && isBody) {
20
- if (!(0, helpers_2.isCheckModeValid)(topLevelCheckMode, 'body')) {
21
- throw new Error('body.checkMode');
22
- }
23
- if (!(0, helpers_2.isDescriptorValueValid)(topLevelCheckMode, topLevelValue, 'body')) {
24
- const errorMessage = 'body.value';
25
- throw new Error(errorMessage);
26
- }
19
+ const {
20
+ checkMode: topLevelCheckMode,
21
+ value: topLevelValue
22
+ } = (0, _helpers.convertToEntityDescriptor)(entity);
23
+ const isBody = entityName === 'body';
24
+ const isTopLevelDescriptor = (0, _helpers.isEntityDescriptor)(entity);
25
+ if (isTopLevelDescriptor && isBody) {
26
+ if (!(0, _helpers2.isCheckModeValid)(topLevelCheckMode, 'body')) {
27
+ throw new Error('body.checkMode');
28
+ }
29
+ if (!(0, _helpers2.isDescriptorValueValid)(topLevelCheckMode, topLevelValue, 'body')) {
30
+ const errorMessage = 'body.value';
31
+ throw new Error(errorMessage);
27
32
  }
28
- const isEntityObject = (0, helpers_1.isPlainObject)(entity) && !(entity instanceof RegExp);
29
- const isEntityArray = Array.isArray(entity) && isBody;
30
- if (isEntityObject || isEntityArray) {
31
- Object.entries(topLevelValue).forEach(([key, valueOrDescriptor]) => {
32
- const { checkMode, value } = (0, helpers_1.convertToEntityDescriptor)(valueOrDescriptor);
33
- if (!(0, helpers_2.isCheckModeValid)(checkMode)) {
34
- throw new Error(`${entityName}.${key}.checkMode`);
35
- }
36
- const isDescriptor = (0, helpers_1.isEntityDescriptor)(valueOrDescriptor);
37
- const errorMessage = `${entityName}.${key}${isDescriptor ? '.value' : ''}`;
38
- const isValueArray = Array.isArray(value);
39
- if (isValueArray && !isBody) {
40
- value.forEach((element, index) => {
41
- if (!(0, helpers_2.isDescriptorValueValid)(checkMode, element)) {
42
- throw new Error(`${errorMessage}[${index}]`);
43
- }
44
- });
45
- return;
46
- }
47
- if (!(0, helpers_2.isDescriptorValueValid)(checkMode, value)) {
48
- throw new Error(errorMessage);
49
- }
33
+ }
34
+ const isEntityObject = (0, _helpers.isPlainObject)(entity) && !(entity instanceof RegExp);
35
+ const isEntityArray = Array.isArray(entity) && isBody;
36
+ if (isEntityObject || isEntityArray) {
37
+ Object.entries(topLevelValue).forEach(([key, valueOrDescriptor]) => {
38
+ const {
39
+ checkMode,
40
+ value
41
+ } = (0, _helpers.convertToEntityDescriptor)(valueOrDescriptor);
42
+ if (!(0, _helpers2.isCheckModeValid)(checkMode)) {
43
+ throw new Error(`${entityName}.${key}.checkMode`);
44
+ }
45
+ const isDescriptor = (0, _helpers.isEntityDescriptor)(valueOrDescriptor);
46
+ const errorMessage = `${entityName}.${key}${isDescriptor ? '.value' : ''}`;
47
+ const isValueArray = Array.isArray(value);
48
+ if (isValueArray && !isBody) {
49
+ value.forEach((element, index) => {
50
+ if (!(0, _helpers2.isDescriptorValueValid)(checkMode, element)) {
51
+ throw new Error(`${errorMessage}[${index}]`);
52
+ }
50
53
  });
51
54
  return;
52
- }
53
- throw new Error(entityName);
55
+ }
56
+ if (!(0, _helpers2.isDescriptorValueValid)(checkMode, value)) {
57
+ throw new Error(errorMessage);
58
+ }
59
+ });
60
+ return;
61
+ }
62
+ throw new Error(entityName);
54
63
  };
55
64
  const validateEntities = (entities, method) => {
56
- const isEntitiesObject = (0, helpers_1.isPlainObject)(entities);
57
- if (isEntitiesObject) {
58
- Object.keys(entities).forEach((entityName) => {
59
- const isEntityAllowed = ALLOWED_ENTITIES_BY_METHOD[method].includes(entityName);
60
- if (!isEntityAllowed) {
61
- throw new Error(`entities.${entityName}`);
62
- }
63
- try {
64
- validateEntity(entities[entityName], entityName);
65
- }
66
- catch (error) {
67
- throw new Error(`entities.${error.message}`);
68
- }
69
- });
70
- return;
71
- }
72
- if (typeof entities !== 'undefined') {
73
- throw new Error('entities');
74
- }
65
+ const isEntitiesObject = (0, _helpers.isPlainObject)(entities);
66
+ if (isEntitiesObject) {
67
+ Object.keys(entities).forEach(entityName => {
68
+ const isEntityAllowed = ALLOWED_ENTITIES_BY_METHOD[method].includes(entityName);
69
+ if (!isEntityAllowed) {
70
+ throw new Error(`entities.${entityName}`);
71
+ }
72
+ try {
73
+ validateEntity(entities[entityName], entityName);
74
+ } catch (error) {
75
+ throw new Error(`entities.${error.message}`);
76
+ }
77
+ });
78
+ return;
79
+ }
80
+ if (typeof entities !== 'undefined') {
81
+ throw new Error('entities');
82
+ }
75
83
  };
76
84
  const validateRoutes = (routes, method) => {
77
- const isRoutesArray = Array.isArray(routes);
78
- if (isRoutesArray) {
79
- routes.forEach((route, index) => {
80
- const isRouteObject = (0, helpers_1.isPlainObject)(route);
81
- if (isRouteObject) {
82
- const isRouteHasDataProperty = 'data' in route;
83
- if (!isRouteHasDataProperty) {
84
- throw new Error(`routes[${index}]`);
85
- }
86
- try {
87
- validateEntities(route.entities, method);
88
- (0, validateInterceptors_1.validateInterceptors)(route.interceptors);
89
- }
90
- catch (error) {
91
- throw new Error(`routes[${index}].${error.message}`);
92
- }
93
- return;
94
- }
95
- throw new Error(`routes[${index}]`);
96
- });
85
+ const isRoutesArray = Array.isArray(routes);
86
+ if (isRoutesArray) {
87
+ routes.forEach((route, index) => {
88
+ const isRouteObject = (0, _helpers.isPlainObject)(route);
89
+ if (isRouteObject) {
90
+ const isRouteHasDataProperty = ('data' in route);
91
+ if (!isRouteHasDataProperty) {
92
+ throw new Error(`routes[${index}]`);
93
+ }
94
+ try {
95
+ validateEntities(route.entities, method);
96
+ (0, _validateInterceptors.validateInterceptors)(route.interceptors);
97
+ } catch (error) {
98
+ throw new Error(`routes[${index}].${error.message}`);
99
+ }
97
100
  return;
98
- }
99
- throw new Error('routes');
101
+ }
102
+ throw new Error(`routes[${index}]`);
103
+ });
104
+ return;
105
+ }
106
+ throw new Error('routes');
100
107
  };
101
- exports.validateRoutes = validateRoutes;
108
+ exports.validateRoutes = validateRoutes;
@@ -1,44 +1,53 @@
1
1
  "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
3
6
  exports.validateStaticPath = void 0;
4
- const helpers_1 = require("../../../src/utils/helpers");
5
- const validateStaticPath = (staticPath) => {
6
- const isStaticPathArray = Array.isArray(staticPath);
7
- if (isStaticPathArray) {
8
- staticPath.forEach((staticPathElement, index) => {
9
- const isStaticPathElementObject = (0, helpers_1.isPlainObject)(staticPathElement);
10
- if (isStaticPathElementObject) {
11
- const { prefix, path } = staticPathElement;
12
- if (typeof prefix !== 'string' || !prefix.startsWith('/')) {
13
- throw new Error(`staticPath[${index}].prefix`);
14
- }
15
- if (typeof path !== 'string' || !path.startsWith('/')) {
16
- throw new Error(`staticPath[${index}].path`);
17
- }
18
- return;
19
- }
20
- if (typeof staticPathElement !== 'string' || !staticPathElement.startsWith('/')) {
21
- throw new Error(`staticPath[${index}]`);
22
- }
23
- });
24
- return;
25
- }
26
- const isStaticPathObject = (0, helpers_1.isPlainObject)(staticPath);
27
- if (isStaticPathObject) {
28
- const { prefix, path } = staticPath;
7
+ var _helpers = require("../../../src/utils/helpers");
8
+ const validateStaticPath = staticPath => {
9
+ const isStaticPathArray = Array.isArray(staticPath);
10
+ if (isStaticPathArray) {
11
+ staticPath.forEach((staticPathElement, index) => {
12
+ const isStaticPathElementObject = (0, _helpers.isPlainObject)(staticPathElement);
13
+ if (isStaticPathElementObject) {
14
+ const {
15
+ prefix,
16
+ path
17
+ } = staticPathElement;
29
18
  if (typeof prefix !== 'string' || !prefix.startsWith('/')) {
30
- throw new Error('staticPath.prefix');
19
+ throw new Error(`staticPath[${index}].prefix`);
31
20
  }
32
21
  if (typeof path !== 'string' || !path.startsWith('/')) {
33
- throw new Error('staticPath.path');
22
+ throw new Error(`staticPath[${index}].path`);
34
23
  }
35
24
  return;
25
+ }
26
+ if (typeof staticPathElement !== 'string' || !staticPathElement.startsWith('/')) {
27
+ throw new Error(`staticPath[${index}]`);
28
+ }
29
+ });
30
+ return;
31
+ }
32
+ const isStaticPathObject = (0, _helpers.isPlainObject)(staticPath);
33
+ if (isStaticPathObject) {
34
+ const {
35
+ prefix,
36
+ path
37
+ } = staticPath;
38
+ if (typeof prefix !== 'string' || !prefix.startsWith('/')) {
39
+ throw new Error('staticPath.prefix');
36
40
  }
37
- if (typeof staticPath !== 'string' && typeof staticPath !== 'undefined') {
38
- throw new Error('staticPath');
39
- }
40
- if (typeof staticPath === 'string' && !staticPath.startsWith('/')) {
41
- throw new Error('staticPath');
41
+ if (typeof path !== 'string' || !path.startsWith('/')) {
42
+ throw new Error('staticPath.path');
42
43
  }
44
+ return;
45
+ }
46
+ if (typeof staticPath !== 'string' && typeof staticPath !== 'undefined') {
47
+ throw new Error('staticPath');
48
+ }
49
+ if (typeof staticPath === 'string' && !staticPath.startsWith('/')) {
50
+ throw new Error('staticPath');
51
+ }
43
52
  };
44
- exports.validateStaticPath = validateStaticPath;
53
+ exports.validateStaticPath = validateStaticPath;
@@ -0,0 +1,3 @@
1
+ import type { IRouter } from 'express';
2
+ import type { DatabaseConfig } from '../../../utils/types';
3
+ export declare const createDatabaseRoutes: (router: IRouter, { data, routes }: DatabaseConfig) => IRouter;
@@ -0,0 +1,33 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.createDatabaseRoutes = void 0;
7
+ var _helpers = require("./helpers");
8
+ var _storages = require("./storages");
9
+ const isVariableJsonFile = variable => typeof variable === 'string' && variable.endsWith('.json');
10
+ const createDatabaseRoutes = (router, {
11
+ data,
12
+ routes
13
+ }) => {
14
+ if (routes) {
15
+ const storage = isVariableJsonFile(routes) ? new _storages.FileStorage(routes) : new _storages.MemoryStorage(routes);
16
+ (0, _helpers.createRewrittenDatabaseRoutes)(router, storage.read());
17
+ router.route('/__routes').get((_request, response) => {
18
+ response.json(storage.read());
19
+ });
20
+ }
21
+ const storage = isVariableJsonFile(data) ? new _storages.FileStorage(data) : new _storages.MemoryStorage(data);
22
+ const {
23
+ shallowDatabase,
24
+ nestedDatabase
25
+ } = (0, _helpers.splitDatabaseByNesting)(storage.read());
26
+ (0, _helpers.createShallowDatabaseRoutes)(router, shallowDatabase, storage);
27
+ (0, _helpers.createNestedDatabaseRoutes)(router, nestedDatabase, storage);
28
+ router.route('/__db').get((_request, response) => {
29
+ response.json(storage.read());
30
+ });
31
+ return router;
32
+ };
33
+ exports.createDatabaseRoutes = createDatabaseRoutes;
@@ -0,0 +1,4 @@
1
+ import type { NestedDatabaseId } from '../../../../../../utils/types';
2
+ export declare const createNewId: (array: {
3
+ id: NestedDatabaseId;
4
+ }[]) => number;
@@ -0,0 +1,16 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.createNewId = void 0;
7
+ const createNewId = array => {
8
+ let maxId = -1;
9
+ for (let i = 0; i < array.length; i += 1) {
10
+ if (typeof array[i].id === 'number' && array[i].id > maxId) {
11
+ maxId = array[i].id;
12
+ }
13
+ }
14
+ return maxId + 1;
15
+ };
16
+ exports.createNewId = createNewId;
@@ -0,0 +1,4 @@
1
+ import type { NestedDatabaseId } from '../../../../../../utils/types';
2
+ export declare const findIndexById: (array: {
3
+ id: NestedDatabaseId;
4
+ }[], id: NestedDatabaseId) => number;
@@ -0,0 +1,8 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.findIndexById = void 0;
7
+ const findIndexById = (array, id) => array.findIndex(item => item.id.toString() === id.toString());
8
+ exports.findIndexById = findIndexById;
@@ -0,0 +1,3 @@
1
+ export * from './createNewId/createNewId';
2
+ export * from './findIndexById/findIndexById';
3
+ export * from './isIndex/isIndex';
@@ -0,0 +1,38 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ var _createNewId = require("./createNewId/createNewId");
7
+ Object.keys(_createNewId).forEach(function (key) {
8
+ if (key === "default" || key === "__esModule") return;
9
+ if (key in exports && exports[key] === _createNewId[key]) return;
10
+ Object.defineProperty(exports, key, {
11
+ enumerable: true,
12
+ get: function () {
13
+ return _createNewId[key];
14
+ }
15
+ });
16
+ });
17
+ var _findIndexById = require("./findIndexById/findIndexById");
18
+ Object.keys(_findIndexById).forEach(function (key) {
19
+ if (key === "default" || key === "__esModule") return;
20
+ if (key in exports && exports[key] === _findIndexById[key]) return;
21
+ Object.defineProperty(exports, key, {
22
+ enumerable: true,
23
+ get: function () {
24
+ return _findIndexById[key];
25
+ }
26
+ });
27
+ });
28
+ var _isIndex = require("./isIndex/isIndex");
29
+ Object.keys(_isIndex).forEach(function (key) {
30
+ if (key === "default" || key === "__esModule") return;
31
+ if (key in exports && exports[key] === _isIndex[key]) return;
32
+ Object.defineProperty(exports, key, {
33
+ enumerable: true,
34
+ get: function () {
35
+ return _isIndex[key];
36
+ }
37
+ });
38
+ });
@@ -0,0 +1 @@
1
+ export declare const isIndex: (value: any) => value is number;
@@ -0,0 +1,8 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.isIndex = void 0;
7
+ const isIndex = value => Number.isInteger(value) && value >= 0;
8
+ exports.isIndex = isIndex;
@@ -0,0 +1,4 @@
1
+ import type { IRouter } from 'express';
2
+ import type { NestedDatabase } from '../../../../../utils/types';
3
+ import type { MemoryStorage } from '../../storages';
4
+ export declare const createNestedDatabaseRoutes: (router: IRouter, database: NestedDatabase, storage: MemoryStorage<NestedDatabase>) => IRouter;
@@ -0,0 +1,88 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.createNestedDatabaseRoutes = void 0;
7
+ var _array = require("../array");
8
+ const createNestedDatabaseRoutes = (router, database, storage) => {
9
+ Object.keys(database).forEach(key => {
10
+ const collectionPath = `/${key}`;
11
+ const itemPath = `/${key}/:id`;
12
+ router.route(collectionPath).get((_request, response) => {
13
+ // ✅ important:
14
+ // set 'Cache-Control' header for explicit browsers response revalidate
15
+ // https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cache-Control
16
+ response.set('Cache-control', 'max-age=0, must-revalidate');
17
+ response.json(storage.read(key));
18
+ });
19
+ router.route(collectionPath).post((request, response) => {
20
+ const collection = storage.read(key);
21
+ const newResourceId = (0, _array.createNewId)(collection);
22
+ const newResource = {
23
+ ...request.body,
24
+ id: newResourceId
25
+ };
26
+ storage.write([key, collection.length], newResource);
27
+ response.set('Location', `${request.url}/${newResourceId}`);
28
+ response.status(201).json(newResource);
29
+ });
30
+ router.route(itemPath).get((request, response) => {
31
+ const currentResourceCollection = storage.read(key);
32
+ const currentResourceIndex = (0, _array.findIndexById)(currentResourceCollection, request.params.id);
33
+ if (currentResourceIndex === -1) {
34
+ response.status(404).end();
35
+ return;
36
+ }
37
+
38
+ // ✅ important:
39
+ // set 'Cache-Control' header for explicit browsers response revalidate
40
+ // https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cache-Control
41
+ response.set('Cache-control', 'max-age=0, must-revalidate');
42
+ response.json(storage.read([key, currentResourceIndex]));
43
+ });
44
+ router.route(itemPath).put((request, response) => {
45
+ const currentResourceCollection = storage.read(key);
46
+ const currentResourceIndex = (0, _array.findIndexById)(currentResourceCollection, request.params.id);
47
+ if (currentResourceIndex === -1) {
48
+ response.status(404).end();
49
+ return;
50
+ }
51
+ const currentResource = storage.read([key, currentResourceIndex]);
52
+ const updatedResource = {
53
+ ...request.body,
54
+ id: currentResource.id
55
+ };
56
+ storage.write([key, currentResourceIndex], updatedResource);
57
+ response.json(updatedResource);
58
+ });
59
+ router.route(itemPath).patch((request, response) => {
60
+ const currentResourceCollection = storage.read(key);
61
+ const currentResourceIndex = (0, _array.findIndexById)(currentResourceCollection, request.params.id);
62
+ if (currentResourceIndex === -1) {
63
+ response.status(404).end();
64
+ return;
65
+ }
66
+ const currentResource = storage.read([key, currentResourceIndex]);
67
+ const updatedResource = {
68
+ ...currentResource,
69
+ ...request.body,
70
+ id: currentResource.id
71
+ };
72
+ storage.write([key, currentResourceIndex], updatedResource);
73
+ response.json(updatedResource);
74
+ });
75
+ router.route(itemPath).delete((request, response) => {
76
+ const currentResourceCollection = storage.read(key);
77
+ const currentResourceIndex = (0, _array.findIndexById)(currentResourceCollection, request.params.id);
78
+ if (currentResourceIndex === -1) {
79
+ response.status(404).end();
80
+ return;
81
+ }
82
+ storage.delete([key, currentResourceIndex]);
83
+ response.status(204).end();
84
+ });
85
+ });
86
+ return router;
87
+ };
88
+ exports.createNestedDatabaseRoutes = createNestedDatabaseRoutes;
@@ -0,0 +1,2 @@
1
+ import type { IRouter } from 'express';
2
+ export declare const createRewrittenDatabaseRoutes: (router: IRouter, rewrittenRoutes: Record<string, string>) => void;