b2b-platform-utils 1.1.23 → 1.1.25

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 (3) hide show
  1. package/errorsMap.js +87 -71
  2. package/fileSystem.js +158 -135
  3. package/package.json +1 -1
package/errorsMap.js CHANGED
@@ -2,7 +2,7 @@
2
2
 
3
3
  // Purpose: Static error map with backward compatibility and dynamic shortcuts.
4
4
  // - Old style calls like errorsMap.mailTemplateNotFound?.() continue to work.
5
- // - Any property access matching an errorKey returns a function that yields JSON.stringify(error).
5
+ // - Any property access matching an errorKey returns a function that yields the error OBJECT.
6
6
  // - New API: get(), getString(), getCode(), list(), and legacy getSingleError().
7
7
  // - Cache-first: if localCache.errorsMap exists, it overrides static entries.
8
8
 
@@ -10,63 +10,67 @@ const { getValue } = require('./localCache');
10
10
 
11
11
  // ---- Static fallback (source of truth when cache is empty) ----
12
12
  const STATIC_ERRORS = [
13
- { errorCode: 1000, errorKey: 'userNotFound', httpCode: 404, description: 'User was not found' },
14
- { errorCode: 1001, errorKey: 'unauthorized', httpCode: 401, description: 'The server requires user authentication' },
15
- { errorCode: 1002, errorKey: 'gameCategoryNotFound', httpCode: 404, description: 'Game`s category was not found' },
16
- { errorCode: 1003, errorKey: 'mediaResourceNotFound', httpCode: 404, description: 'Media resource was not found' },
17
- { errorCode: 1004, errorKey: 'roleNotFound', httpCode: 404, description: 'Role or permission were not found' },
18
- { errorCode: 1005, errorKey: 'duplicatedUniqueField', httpCode: 422, description: 'Some of unique fields were duplicated.' },
19
- { errorCode: 1006, errorKey: 'gameCollectionNotFound', httpCode: 404, description: 'Game`s collection was not found' },
20
- { errorCode: 1007, errorKey: 'gameTagNotFound', httpCode: 404, description: 'Game`s tag was not found' },
21
- { errorCode: 1008, errorKey: 'invalidConstraintField', httpCode: 422, description: 'Some of foreign keys fields were invalid.' },
22
- { errorCode: 1009, errorKey: 'gameProviderNotFound', httpCode: 404, description: 'Game`s provider was not found' },
23
- { errorCode: 1010, errorKey: 'gameNotFound', httpCode: 404, description: 'Game was not found' },
24
- { errorCode: 1011, errorKey: 'undefinedRequest', httpCode: 422, description: 'Request data or format is undefined for handler.' },
25
- { errorCode: 1012, errorKey: 'widgetNotFound', httpCode: 404, description: 'Widget[CMS] was not found' },
26
- { errorCode: 1013, errorKey: 'segmentNotFound', httpCode: 404, description: 'User`s Segment was not found' },
27
- { errorCode: 1014, errorKey: 'bonusNotFound', httpCode: 404, description: 'Bonus was not found' },
28
- { errorCode: 1015, errorKey: 'userBonusNotFound', httpCode: 404, description: 'User`s bonus was not found' },
29
- { errorCode: 1016, errorKey: 'freeSpinsNotFound', httpCode: 404, description: 'Free spins was not found' },
30
- { errorCode: 1017, errorKey: 'gameWagerListNotFound', httpCode: 404, description: 'Game`s wager list was not found' },
31
- { errorCode: 1018, errorKey: 'bonusAlreadyInUse', httpCode: 422, description: 'Bonus is already use(d)' },
32
- { errorCode: 1019, errorKey: 'bonusRestrictForClaim', httpCode: 422, description: 'Bonus does not fit for user`s claiming' },
33
- { errorCode: 1020, errorKey: 'bonusRewardAttachError', httpCode: 422, description: 'Bonus reward can not be attached.' },
34
- { errorCode: 1021, errorKey: 'loyaltyLevelNotFound', httpCode: 404, description: 'Loyalty level was not found' },
35
- { errorCode: 1022, errorKey: 'loyaltyPointNotFound', httpCode: 404, description: 'Loyalty point was not found' },
36
- { errorCode: 1023, errorKey: 'notificationNotFound', httpCode: 404, description: 'Notification was not found' },
37
- { errorCode: 1024, errorKey: 'bannerNotFound', httpCode: 404, description: 'Banner was not found' },
38
- { errorCode: 1025, errorKey: 'paymentProviderNotFound', httpCode: 404, description: 'Payment provider was not found' },
39
- { errorCode: 1026, errorKey: 'paymentMethodNotFound', httpCode: 404, description: 'Payment method was not found' },
40
- { errorCode: 1027, errorKey: 'depositNotFound', httpCode: 404, description: 'Deposit was not found' },
41
- { errorCode: 1028, errorKey: 'withdrawalNotFound', httpCode: 404, description: 'Withdrawal was not found' },
42
- { errorCode: 1029, errorKey: 'noteNotFound', httpCode: 404, description: 'User`s Note was not found' },
43
- { errorCode: 1030, errorKey: 'promoCodeNotFound', httpCode: 404, description: 'Promo Code was not found' },
44
- { errorCode: 1031, errorKey: 'cashBackNotFound', httpCode: 404, description: 'Cash Back was not found' },
45
- { errorCode: 1032, errorKey: 'tournamentNotFound', httpCode: 404, description: 'Tournament was not found' },
46
- { errorCode: 1033, errorKey: 'pageNotFound', httpCode: 404, description: 'Page was not found' },
47
- { errorCode: 1034, errorKey: 'gameCashBackListNotFound', httpCode: 404, description: 'Game`s cash back list was not found' },
48
- { errorCode: 1035, errorKey: 'bonusDepositRequired', httpCode: 404, description: 'For bonus activation desposit requited.' },
49
- { errorCode: 1036, errorKey: 'taskNotFound', httpCode: 404, description: 'Task for schedule was not found.' },
13
+ { errorCode: 1000, errorKey: 'userNotFound', httpCode: 404, description: 'User was not found' },
14
+ { errorCode: 1001, errorKey: 'unauthorized', httpCode: 401, description: 'The server requires user authentication' },
15
+ { errorCode: 1002, errorKey: 'gameCategoryNotFound', httpCode: 404, description: 'Game`s category was not found' },
16
+ { errorCode: 1003, errorKey: 'mediaResourceNotFound', httpCode: 404, description: 'Media resource was not found' },
17
+ { errorCode: 1004, errorKey: 'roleNotFound', httpCode: 404, description: 'Role or permission were not found' },
18
+ { errorCode: 1005, errorKey: 'duplicatedUniqueField', httpCode: 422, description: 'Some of unique fields were duplicated.' },
19
+ { errorCode: 1006, errorKey: 'gameCollectionNotFound', httpCode: 404, description: 'Game`s collection was not found' },
20
+ { errorCode: 1007, errorKey: 'gameTagNotFound', httpCode: 404, description: 'Game`s tag was not found' },
21
+ { errorCode: 1008, errorKey: 'invalidConstraintField', httpCode: 422, description: 'Some of foreign keys fields were invalid.' },
22
+ { errorCode: 1009, errorKey: 'gameProviderNotFound', httpCode: 404, description: 'Game`s provider was not found' },
23
+ { errorCode: 1010, errorKey: 'gameNotFound', httpCode: 404, description: 'Game was not found' },
24
+ { errorCode: 1011, errorKey: 'undefinedRequest', httpCode: 422, description: 'Request data or format is undefined for handler.' },
25
+ { errorCode: 1012, errorKey: 'widgetNotFound', httpCode: 404, description: 'Widget[CMS] was not found' },
26
+ { errorCode: 1013, errorKey: 'segmentNotFound', httpCode: 404, description: 'User`s Segment was not found' },
27
+ { errorCode: 1014, errorKey: 'bonusNotFound', httpCode: 404, description: 'Bonus was not found' },
28
+ { errorCode: 1015, errorKey: 'userBonusNotFound', httpCode: 404, description: 'User`s bonus was not found' },
29
+ { errorCode: 1016, errorKey: 'freeSpinsNotFound', httpCode: 404, description: 'Free spins was not found' },
30
+ { errorCode: 1017, errorKey: 'gameWagerListNotFound', httpCode: 404, description: 'Game`s wager list was not found' },
31
+ { errorCode: 1018, errorKey: 'bonusAlreadyInUse', httpCode: 422, description: 'Bonus is already use(d)' },
32
+ { errorCode: 1019, errorKey: 'bonusRestrictForClaim', httpCode: 422, description: 'Bonus does not fit for user`s claiming' },
33
+ { errorCode: 1020, errorKey: 'bonusRewardAttachError', httpCode: 422, description: 'Bonus reward can not be attached.' },
34
+ { errorCode: 1021, errorKey: 'loyaltyLevelNotFound', httpCode: 404, description: 'Loyalty level was not found' },
35
+ { errorCode: 1022, errorKey: 'loyaltyPointNotFound', httpCode: 404, description: 'Loyalty point was not found' },
36
+ { errorCode: 1023, errorKey: 'notificationNotFound', httpCode: 404, description: 'Notification was not found' },
37
+ { errorCode: 1024, errorKey: 'bannerNotFound', httpCode: 404, description: 'Banner was not found' },
38
+ { errorCode: 1025, errorKey: 'paymentProviderNotFound', httpCode: 404, description: 'Payment provider was not found' },
39
+ { errorCode: 1026, errorKey: 'paymentMethodNotFound', httpCode: 404, description: 'Payment method was not found' },
40
+ { errorCode: 1027, errorKey: 'depositNotFound', httpCode: 404, description: 'Deposit was not found' },
41
+ { errorCode: 1028, errorKey: 'withdrawalNotFound', httpCode: 404, description: 'Withdrawal was not found' },
42
+ { errorCode: 1029, errorKey: 'noteNotFound', httpCode: 404, description: 'User`s Note was not found' },
43
+ { errorCode: 1030, errorKey: 'promoCodeNotFound', httpCode: 404, description: 'Promo Code was not found' },
44
+ { errorCode: 1031, errorKey: 'cashBackNotFound', httpCode: 404, description: 'Cash Back was not found' },
45
+ { errorCode: 1032, errorKey: 'tournamentNotFound', httpCode: 404, description: 'Tournament was not found' },
46
+ { errorCode: 1033, errorKey: 'pageNotFound', httpCode: 404, description: 'Page was not found' },
47
+ { errorCode: 1034, errorKey: 'gameCashBackListNotFound', httpCode: 404, description: 'Game`s cash back list was not found' },
48
+ { errorCode: 1035, errorKey: 'bonusDepositRequired', httpCode: 404, description: 'For bonus activation desposit requited.' },
49
+ { errorCode: 1036, errorKey: 'taskNotFound', httpCode: 404, description: 'Task for schedule was not found.' },
50
50
  { errorCode: 1037, errorKey: 'bonusConfirmationRequired', httpCode: 404, description: 'For bonus activation confirmation of personal user data requited.' },
51
- { errorCode: 1038, errorKey: 'promoNotFound', httpCode: 404, description: 'Promo was not found.' },
52
- { errorCode: 1039, errorKey: 'badSignature', httpCode: 401, description: 'Untrusted request, bad signature.' },
53
- { errorCode: 1040, errorKey: 'mailTemplateNotFound', httpCode: 404, description: 'Email template was not found.' },
54
- { errorCode: 1041, errorKey: 'domainNotFound', httpCode: 404, description: 'Domain was not found.' },
55
- { errorCode: 1042, errorKey: 'domainAlreadyExists', httpCode: 422, description: 'Domain already in use.' },
56
- { errorCode: 1043, errorKey: 'domainIsNotActivated', httpCode: 422, description: 'Current Domain is not activated yet.' },
57
- { errorCode: 1044, errorKey: 'domainCountriesNotFound', httpCode: 404, description: 'Domain`s Countries were not found for primary zone.' },
58
- { errorCode: 1045, errorKey: 'footerPartnersNotFound', httpCode: 404, description: 'Footer Partners block were not found.' },
59
- { errorCode: 1046, errorKey: 'footerBrandCoreNotFound', httpCode: 404, description: 'Footer Brand Core block were not found.' },
60
- { errorCode: 1047, errorKey: 'footerPaymentsNotFound', httpCode: 404, description: 'Footer Payments block were not found.' },
61
- { errorCode: 1048, errorKey: 'footerMainTextNotFound', httpCode: 404, description: 'Footer Main Text block were not found.' },
62
- { errorCode: 1049, errorKey: 'footerApplicationsNotFound',httpCode: 404, description: 'Footer Applications block were not found.' },
63
- { errorCode: 1050, errorKey: 'footerBlockAlreadyExists', httpCode: 422, description: 'Footer block item already exists.' },
64
- { errorCode: 1051, errorKey: 'invalidTwoFaCode', httpCode: 422, description: 'Two Factor Auth code is invalid or expired.' },
51
+ { errorCode: 1038, errorKey: 'promoNotFound', httpCode: 404, description: 'Promo was not found.' },
52
+ { errorCode: 1039, errorKey: 'badSignature', httpCode: 401, description: 'Untrusted request, bad signature.' },
53
+ { errorCode: 1040, errorKey: 'mailTemplateNotFound', httpCode: 404, description: 'Email template was not found.' },
54
+ { errorCode: 1041, errorKey: 'domainNotFound', httpCode: 404, description: 'Domain was not found.' },
55
+ { errorCode: 1042, errorKey: 'domainAlreadyExists', httpCode: 422, description: 'Domain already in use.' },
56
+ { errorCode: 1043, errorKey: 'domainIsNotActivated', httpCode: 422, description: 'Current Domain is not activated yet.' },
57
+ { errorCode: 1044, errorKey: 'domainCountriesNotFound', httpCode: 404, description: 'Domain`s Countries were not found for primary zone.' },
58
+ { errorCode: 1045, errorKey: 'footerPartnersNotFound', httpCode: 404, description: 'Footer Partners block were not found.' },
59
+ { errorCode: 1046, errorKey: 'footerBrandCoreNotFound', httpCode: 404, description: 'Footer Brand Core block were not found.' },
60
+ { errorCode: 1047, errorKey: 'footerPaymentsNotFound', httpCode: 404, description: 'Footer Payments block were not found.' },
61
+ { errorCode: 1048, errorKey: 'footerMainTextNotFound', httpCode: 404, description: 'Footer Main Text block were not found.' },
62
+ { errorCode: 1049, errorKey: 'footerApplicationsNotFound', httpCode: 404, description: 'Footer Applications block were not found.' },
63
+ { errorCode: 1050, errorKey: 'footerBlockAlreadyExists', httpCode: 422, description: 'Footer block item already exists.' },
64
+ { errorCode: 1051, errorKey: 'invalidTwoFaCode', httpCode: 422, description: 'Two Factor Auth code is invalid or expired.' }
65
65
  ];
66
66
 
67
- const STATIC_BY_KEY = Object.fromEntries(STATIC_ERRORS.map(e => [e.errorKey, e]));
67
+ const STATIC_BY_KEY = Object.fromEntries(STATIC_ERRORS.map((e) => [e.errorKey, e]));
68
68
 
69
- /** Resolve error by key from cache (if any) or static table. */
69
+ /**
70
+ * Resolve error by key from cache (if any) or static table.
71
+ * @param {string} errorKey
72
+ * @returns {object|undefined}
73
+ */
70
74
  function resolveErrorByKey(errorKey) {
71
75
  const cached = getValue('errorsMap');
72
76
  if (Array.isArray(cached) && cached.length) {
@@ -78,29 +82,48 @@ function resolveErrorByKey(errorKey) {
78
82
 
79
83
  // --- Base API object (do not export directly; we wrap it in a Proxy) ---
80
84
  const api = {
81
- /** Legacy accessor kept for compatibility. */
85
+ /**
86
+ * Legacy accessor kept for compatibility (returns JSON string).
87
+ * @param {string} errorKey
88
+ * @returns {string|undefined}
89
+ */
82
90
  getSingleError: (errorKey) => {
83
91
  const obj = resolveErrorByKey(errorKey);
84
92
  return obj ? JSON.stringify(obj) : undefined;
85
93
  },
86
94
 
87
- /** New API: get full error object. */
95
+ /**
96
+ * New API: get full error object.
97
+ * @param {string} errorKey
98
+ * @returns {object|undefined}
99
+ */
88
100
  get: (errorKey) => resolveErrorByKey(errorKey),
89
101
 
90
- /** New API: get JSON version (same as legacy). */
102
+ /**
103
+ * New API: get JSON string version (same shape as legacy).
104
+ * @param {string} errorKey
105
+ * @returns {string|undefined}
106
+ */
91
107
  getString: (errorKey) => {
92
108
  const obj = resolveErrorByKey(errorKey);
93
109
  return obj ? JSON.stringify(obj) : undefined;
94
110
  },
95
111
 
96
- /** New API: get numeric error code. */
112
+ /**
113
+ * New API: get numeric error code.
114
+ * @param {string} errorKey
115
+ * @returns {number|undefined}
116
+ */
97
117
  getCode: (errorKey) => resolveErrorByKey(errorKey)?.errorCode,
98
118
 
99
- /** New API: list all static errors (useful for diagnostics). */
119
+ /**
120
+ * New API: list all static errors (useful for diagnostics).
121
+ * @returns {object[]}
122
+ */
100
123
  list: () => [...STATIC_ERRORS]
101
124
  };
102
125
 
103
- // --- Dynamic shortcuts: errorsMap.<errorKey>() returns STRING (JSON) ---
126
+ // --- Dynamic shortcuts: errorsMap.<errorKey>() returns OBJECT (same as get()) ---
104
127
  module.exports = new Proxy(api, {
105
128
  get(target, prop, receiver) {
106
129
  // If method exists (get, getString, etc.) → return it
@@ -108,15 +131,11 @@ module.exports = new Proxy(api, {
108
131
  return Reflect.get(target, prop, receiver);
109
132
  }
110
133
 
111
- // If property is a known errorKey → return a function () => getString(errorKey)
134
+ // If property is a known errorKey → return a function () => get(errorKey) (OBJECT)
112
135
  if (typeof prop === 'string' && STATIC_BY_KEY[prop]) {
113
- // Legacy behavior: errorsMap.userNotFound() -> JSON string
114
136
  return function () {
115
- const obj = target.get(prop);
116
- return obj ? JSON.stringify(obj) : undefined;
137
+ return target.get(prop);
117
138
  };
118
- // Или короче:
119
- // return () => target.getString(prop);
120
139
  }
121
140
 
122
141
  // Otherwise undefined
@@ -124,9 +143,6 @@ module.exports = new Proxy(api, {
124
143
  },
125
144
 
126
145
  has(target, prop) {
127
- return (
128
- prop in target ||
129
- (typeof prop === 'string' && !!STATIC_BY_KEY[prop])
130
- );
146
+ return prop in target || (typeof prop === 'string' && !!STATIC_BY_KEY[prop]);
131
147
  }
132
- });
148
+ });
package/fileSystem.js CHANGED
@@ -1,4 +1,4 @@
1
- 'use strict';
1
+ "use strict";
2
2
 
3
3
  /**
4
4
  * @module fileSystem
@@ -19,10 +19,11 @@
19
19
  * It is NOT recommended in hot request/response paths.
20
20
  */
21
21
 
22
- const fs = require('fs');
23
- const path = require('path');
24
- const { warningNote } = require('./logger');
25
- const { getValue } = require('./localCache');
22
+ const fs = require("fs");
23
+ const fsPromises = require("fs/promises");
24
+ const path = require("path");
25
+ const { warningNote } = require("./logger");
26
+ const { getValue } = require("./localCache");
26
27
 
27
28
  // -----------------------------------------------------------------------------
28
29
  // Internal helpers
@@ -36,9 +37,9 @@ const { getValue } = require('./localCache');
36
37
  * @returns {string} Absolute path.
37
38
  */
38
39
  function resolvePath(fileName) {
39
- return path.isAbsolute(fileName)
40
- ? fileName
41
- : path.resolve(process.cwd(), fileName);
40
+ return path.isAbsolute(fileName)
41
+ ? fileName
42
+ : path.resolve(process.cwd(), fileName);
42
43
  }
43
44
 
44
45
  /**
@@ -47,7 +48,7 @@ function resolvePath(fileName) {
47
48
  * @param {string} absolutePath
48
49
  */
49
50
  function ensureDirForFile(absolutePath) {
50
- fs.mkdirSync(path.dirname(absolutePath), { recursive: true });
51
+ fs.mkdirSync(path.dirname(absolutePath), { recursive: true });
51
52
  }
52
53
 
53
54
  /**
@@ -59,11 +60,11 @@ function ensureDirForFile(absolutePath) {
59
60
  * @returns {string} extension without dot, e.g. "png"
60
61
  */
61
62
  function extractCleanExtension(filename) {
62
- // remove query/hash if passed like "avatar.png?ts=123" or "file.pdf#v2"
63
- const cleanName = filename.split('?')[0].split('#')[0];
64
- const parts = cleanName.split('.');
65
- if (parts.length < 2) return '';
66
- return parts.pop().toLowerCase();
63
+ // remove query/hash if passed like "avatar.png?ts=123" or "file.pdf#v2"
64
+ const cleanName = filename.split("?")[0].split("#")[0];
65
+ const parts = cleanName.split(".");
66
+ if (parts.length < 2) return "";
67
+ return parts.pop().toLowerCase();
67
68
  }
68
69
 
69
70
  // -----------------------------------------------------------------------------
@@ -80,13 +81,13 @@ function extractCleanExtension(filename) {
80
81
  * @param {number} [options.spaces=0] - JSON indentation level, e.g. 2 for pretty debug output.
81
82
  */
82
83
  function saveFile(fileName, data, options = {}) {
83
- const absPath = resolvePath(fileName);
84
- ensureDirForFile(absPath);
84
+ const absPath = resolvePath(fileName);
85
+ ensureDirForFile(absPath);
85
86
 
86
- const spaces = Number.isInteger(options.spaces) ? options.spaces : 0;
87
- const json = JSON.stringify(data, null, spaces);
87
+ const spaces = Number.isInteger(options.spaces) ? options.spaces : 0;
88
+ const json = JSON.stringify(data, null, spaces);
88
89
 
89
- fs.writeFileSync(absPath, json, { encoding: 'utf-8' });
90
+ fs.writeFileSync(absPath, json, { encoding: "utf-8" });
90
91
  }
91
92
 
92
93
  /**
@@ -97,8 +98,8 @@ function saveFile(fileName, data, options = {}) {
97
98
  * @returns {string} File contents.
98
99
  */
99
100
  function readFile(fileName) {
100
- const absPath = resolvePath(fileName);
101
- return fs.readFileSync(absPath, 'utf-8');
101
+ const absPath = resolvePath(fileName);
102
+ return fs.readFileSync(absPath, "utf-8");
102
103
  }
103
104
 
104
105
  /**
@@ -110,14 +111,14 @@ function readFile(fileName) {
110
111
  * @returns {any|null}
111
112
  */
112
113
  function readJsonFile(fileName) {
113
- const absPath = resolvePath(fileName);
114
+ const absPath = resolvePath(fileName);
114
115
 
115
- if (!fs.existsSync(absPath)) {
116
- return null;
117
- }
116
+ if (!fs.existsSync(absPath)) {
117
+ return null;
118
+ }
118
119
 
119
- const raw = fs.readFileSync(absPath, 'utf-8');
120
- return JSON.parse(raw);
120
+ const raw = fs.readFileSync(absPath, "utf-8");
121
+ return JSON.parse(raw);
121
122
  }
122
123
 
123
124
  /**
@@ -127,13 +128,34 @@ function readJsonFile(fileName) {
127
128
  * @param {string} fileName
128
129
  */
129
130
  function removeFile(fileName) {
130
- const absPath = resolvePath(fileName);
131
+ const absPath = resolvePath(fileName);
131
132
 
132
- if (!fs.existsSync(absPath)) {
133
- return;
134
- }
133
+ if (!fs.existsSync(absPath)) {
134
+ return;
135
+ }
135
136
 
136
- fs.unlinkSync(absPath);
137
+ fs.unlinkSync(absPath);
138
+ }
139
+
140
+ /**
141
+ * Remove a file from the filesystem if it exists (async).
142
+ * Safe no-op if the file is already missing.
143
+ *
144
+ * @param {string} fileName - Target file path (absolute or relative).
145
+ * @returns {Promise<boolean>} True if removed, false if file did not exist.
146
+ */
147
+ async function unlinkIfExists(fileName) {
148
+ const absPath = resolvePath(fileName);
149
+
150
+ try {
151
+ await fsPromises.unlink(absPath);
152
+ return true;
153
+ } catch (err) {
154
+ if (err?.code === "ENOENT") {
155
+ return false;
156
+ }
157
+ throw err;
158
+ }
137
159
  }
138
160
 
139
161
  // -----------------------------------------------------------------------------
@@ -149,58 +171,58 @@ function removeFile(fileName) {
149
171
  * @returns {{ extension: string|null, error: string }}
150
172
  */
151
173
  function getImageExtension(mimetype) {
152
- let extension = null;
153
- let error = '';
154
-
155
- switch (mimetype) {
156
- case 'image/png':
157
- extension = 'png';
158
- break;
159
- case 'image/jpeg':
160
- extension = 'jpeg';
161
- break;
162
- case 'image/jpg':
163
- extension = 'jpg';
164
- break;
165
- case 'image/svg+xml':
166
- extension = 'svg';
167
- break;
168
- case 'image/webp':
169
- extension = 'webp';
170
- break;
171
- case 'image/gif':
172
- extension = 'gif';
173
- break;
174
- case 'image/vnd.microsoft.icon':
175
- extension = 'ico';
176
- break;
177
- case 'font/ttf':
178
- extension = 'ttf';
179
- break;
180
- case 'text/plain':
181
- extension = 'txt';
182
- break;
183
- case 'text/csv':
184
- extension = 'csv';
185
- break;
186
- case 'application/pdf':
187
- extension = 'pdf';
188
- break;
189
- case 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet':
190
- extension = 'xlsx';
191
- break;
192
- default:
193
- error = `Undefined file mimetype: ${mimetype}`;
194
- extension = null;
195
-
196
- // Emit a non-fatal warning. Service can still decide what to do.
197
- if (typeof warningNote === 'function') {
198
- warningNote(error);
199
- }
200
- break;
201
- }
174
+ let extension = null;
175
+ let error = "";
176
+
177
+ switch (mimetype) {
178
+ case "image/png":
179
+ extension = "png";
180
+ break;
181
+ case "image/jpeg":
182
+ extension = "jpeg";
183
+ break;
184
+ case "image/jpg":
185
+ extension = "jpg";
186
+ break;
187
+ case "image/svg+xml":
188
+ extension = "svg";
189
+ break;
190
+ case "image/webp":
191
+ extension = "webp";
192
+ break;
193
+ case "image/gif":
194
+ extension = "gif";
195
+ break;
196
+ case "image/vnd.microsoft.icon":
197
+ extension = "ico";
198
+ break;
199
+ case "font/ttf":
200
+ extension = "ttf";
201
+ break;
202
+ case "text/plain":
203
+ extension = "txt";
204
+ break;
205
+ case "text/csv":
206
+ extension = "csv";
207
+ break;
208
+ case "application/pdf":
209
+ extension = "pdf";
210
+ break;
211
+ case "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet":
212
+ extension = "xlsx";
213
+ break;
214
+ default:
215
+ error = `Undefined file mimetype: ${mimetype}`;
216
+ extension = null;
217
+
218
+ // Emit a non-fatal warning. Service can still decide what to do.
219
+ if (typeof warningNote === "function") {
220
+ warningNote(error);
221
+ }
222
+ break;
223
+ }
202
224
 
203
- return { extension, error };
225
+ return { extension, error };
204
226
  }
205
227
 
206
228
  /**
@@ -211,43 +233,43 @@ function getImageExtension(mimetype) {
211
233
  * @returns {string} MIME type string or "" if unknown.
212
234
  */
213
235
  function getMimeTypeByFileExtension(filename) {
214
- const ext = extractCleanExtension(filename);
215
-
216
- switch (ext) {
217
- case 'png':
218
- return 'image/png';
219
- case 'gif':
220
- return 'image/gif';
221
- case 'jpeg':
222
- case 'jpg':
223
- return 'image/jpeg';
224
- case 'webp':
225
- return 'image/webp';
226
- case 'ico':
227
- return 'image/vnd.microsoft.icon';
228
- case 'svg':
229
- return 'image/svg+xml';
230
- case 'csv':
231
- return 'text/csv';
232
- case 'txt':
233
- return 'text/plain';
234
- case 'xml':
235
- return 'application/xml';
236
- case 'pdf':
237
- return 'application/pdf';
238
- case 'xls':
239
- return 'application/vnd.ms-excel';
240
- case 'xlsx':
241
- return 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
242
- case 'doc':
243
- return 'application/msword';
244
- case 'docx':
245
- return 'application/vnd.openxmlformats-officedocument.wordprocessingml.document';
246
- case 'mp4':
247
- return 'video/mp4';
248
- default:
249
- return '';
250
- }
236
+ const ext = extractCleanExtension(filename);
237
+
238
+ switch (ext) {
239
+ case "png":
240
+ return "image/png";
241
+ case "gif":
242
+ return "image/gif";
243
+ case "jpeg":
244
+ case "jpg":
245
+ return "image/jpeg";
246
+ case "webp":
247
+ return "image/webp";
248
+ case "ico":
249
+ return "image/vnd.microsoft.icon";
250
+ case "svg":
251
+ return "image/svg+xml";
252
+ case "csv":
253
+ return "text/csv";
254
+ case "txt":
255
+ return "text/plain";
256
+ case "xml":
257
+ return "application/xml";
258
+ case "pdf":
259
+ return "application/pdf";
260
+ case "xls":
261
+ return "application/vnd.ms-excel";
262
+ case "xlsx":
263
+ return "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
264
+ case "doc":
265
+ return "application/msword";
266
+ case "docx":
267
+ return "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
268
+ case "mp4":
269
+ return "video/mp4";
270
+ default:
271
+ return "";
272
+ }
251
273
  }
252
274
 
253
275
  // -----------------------------------------------------------------------------
@@ -273,8 +295,8 @@ function getMimeTypeByFileExtension(filename) {
273
295
  * @returns {string} Absolute URL.
274
296
  */
275
297
  function getAbsoluteMediaResourceUrl(service, instance, fileName) {
276
- const baseUrl = getValue('baseApiURL') || '';
277
- return `${baseUrl}/file/${service}/${instance}/${fileName}`;
298
+ const baseUrl = getValue("baseApiURL") || "";
299
+ return `${baseUrl}/file/${service}/${instance}/${fileName}`;
278
300
  }
279
301
 
280
302
  // -----------------------------------------------------------------------------
@@ -282,17 +304,18 @@ function getAbsoluteMediaResourceUrl(service, instance, fileName) {
282
304
  // -----------------------------------------------------------------------------
283
305
 
284
306
  module.exports = {
285
- // Filesystem I/O
286
- resolvePath,
287
- saveFile,
288
- readFile,
289
- readJsonFile,
290
- removeFile,
291
-
292
- // MIME helpers
293
- getImageExtension,
294
- getMimeTypeByFileExtension,
295
-
296
- // URL helpers
297
- getAbsoluteMediaResourceUrl
307
+ // Filesystem I/O
308
+ resolvePath,
309
+ saveFile,
310
+ readFile,
311
+ readJsonFile,
312
+ removeFile,
313
+ unlinkIfExists,
314
+
315
+ // MIME helpers
316
+ getImageExtension,
317
+ getMimeTypeByFileExtension,
318
+
319
+ // URL helpers
320
+ getAbsoluteMediaResourceUrl,
298
321
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "b2b-platform-utils",
3
- "version": "1.1.23",
3
+ "version": "1.1.25",
4
4
  "description": "Shared utilities for Node.js microservices: errors map, local cache, logger, numbers, dates, filesystem, media optimization, paginator, slugger, crypto wrapper, sanitize HTML, sorting.",
5
5
  "type": "commonjs",
6
6
  "license": "KingSizer",