@almatar/branding 0.1.9-alpha → 1.0.0-beta.2

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.
package/lib/index.js CHANGED
@@ -1,9 +1,12 @@
1
1
  "use strict";
2
- var Storage_1 = require("./lib/Storage");
3
- var MultiTenant_1 = require("./lib/TenantModel/Mongoose/MultiTenant");
4
- var TenantMongooseModule_1 = require("./lib/TenantModel/NestMongoose/TenantMongooseModule");
5
- var TenantRequest_1 = require("./lib/request/TenantRequest");
6
- var AlmatarBranding_1 = require("./lib/AlmatarBranding");
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ var Storage_1 = __importDefault(require("./lib/Storage"));
6
+ var MultiTenant_1 = __importDefault(require("./lib/TenantModel/Mongoose/MultiTenant"));
7
+ var TenantMongooseModule_1 = __importDefault(require("./lib/TenantModel/NestMongoose/TenantMongooseModule"));
8
+ var TenantRequest_1 = __importDefault(require("./lib/request/TenantRequest"));
9
+ var AlmatarBranding_1 = __importDefault(require("./lib/AlmatarBranding"));
7
10
  module.exports = {
8
11
  ContextNamespace: Storage_1.default,
9
12
  MultiTenant: MultiTenant_1.default,
@@ -1,8 +1,8 @@
1
1
  export declare class BrandIdentifier {
2
2
  private readonly type;
3
3
  constructor(type: string);
4
- getBrand(req: any): Promise<string | string[] | null | Error>;
5
- getBrands(): Promise<string[] | null | Error>;
4
+ getBrand(req: any): Promise<string | string[] | null>;
5
+ getBrands(): Promise<string[] | null>;
6
6
  getDefaultBrand(): string;
7
7
  private error;
8
8
  }
@@ -1,4 +1,23 @@
1
1
  "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
5
+ }) : (function(o, m, k, k2) {
6
+ if (k2 === undefined) k2 = k;
7
+ o[k2] = m[k];
8
+ }));
9
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
10
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
11
+ }) : function(o, v) {
12
+ o["default"] = v;
13
+ });
14
+ var __importStar = (this && this.__importStar) || function (mod) {
15
+ if (mod && mod.__esModule) return mod;
16
+ var result = {};
17
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
18
+ __setModuleDefault(result, mod);
19
+ return result;
20
+ };
2
21
  var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
22
  function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
23
  return new (P || (P = Promise))(function (resolve, reject) {
@@ -14,7 +33,7 @@ var __generator = (this && this.__generator) || function (thisArg, body) {
14
33
  function verb(n) { return function (v) { return step([n, v]); }; }
15
34
  function step(op) {
16
35
  if (f) throw new TypeError("Generator is already executing.");
17
- while (g && (g = 0, op[0] && (_ = 0)), _) try {
36
+ while (_) try {
18
37
  if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
19
38
  if (y = 0, t) op = [op[0] & 2, t.value];
20
39
  switch (op[0]) {
@@ -37,7 +56,7 @@ var __generator = (this && this.__generator) || function (thisArg, body) {
37
56
  };
38
57
  Object.defineProperty(exports, "__esModule", { value: true });
39
58
  exports.BrandIdentifier = void 0;
40
- var Boom = require("@hapi/boom");
59
+ var Boom = __importStar(require("@hapi/boom"));
41
60
  var BrandManager_1 = require("./BrandManager");
42
61
  var BrandIdentifier = /** @class */ (function () {
43
62
  function BrandIdentifier(type) {
@@ -45,7 +64,7 @@ var BrandIdentifier = /** @class */ (function () {
45
64
  }
46
65
  BrandIdentifier.prototype.getBrand = function (req) {
47
66
  return __awaiter(this, void 0, void 0, function () {
48
- var brandManager, brand;
67
+ var brandManager, brand, tokenBrands;
49
68
  return __generator(this, function (_a) {
50
69
  switch (_a.label) {
51
70
  case 0:
@@ -63,7 +82,17 @@ var BrandIdentifier = /** @class */ (function () {
63
82
  }
64
83
  return [2 /*return*/, brandManager.getDefaultBrand()];
65
84
  }
66
- return [2 /*return*/, this.error('Unauthorized!')];
85
+ // If no brand found but we have authorization, try extracting from token directly
86
+ if (req.headers.authorization) {
87
+ tokenBrands = brandManager.extractBrandFromToken(req.headers.authorization);
88
+ if (tokenBrands && tokenBrands.length > 0) {
89
+ return [2 /*return*/, tokenBrands];
90
+ }
91
+ }
92
+ // Return empty array instead of null when no brand found in token
93
+ // tslint:disable-next-line no-console
94
+ console.log('[BrandIdentifier] No brand found in token, returning empty array');
95
+ return [2 /*return*/, []];
67
96
  case 3: return [2 /*return*/, brandManager.getDefaultBrand()];
68
97
  }
69
98
  });
@@ -71,18 +100,29 @@ var BrandIdentifier = /** @class */ (function () {
71
100
  };
72
101
  BrandIdentifier.prototype.getBrands = function () {
73
102
  return __awaiter(this, void 0, void 0, function () {
74
- var brandManager, brands;
103
+ var brandManager, brands, err_1;
75
104
  return __generator(this, function (_a) {
76
105
  switch (_a.label) {
77
106
  case 0:
78
107
  brandManager = new BrandManager_1.BrandManager(this.type);
79
- return [4 /*yield*/, brandManager.getBrands()];
108
+ _a.label = 1;
80
109
  case 1:
110
+ _a.trys.push([1, 3, , 4]);
111
+ return [4 /*yield*/, brandManager.getBrands()];
112
+ case 2:
81
113
  brands = _a.sent();
82
114
  if (!brands) {
83
- this.error('error while fetching brands list from dictionary service');
115
+ // tslint:disable-next-line no-console
116
+ console.log('[BrandIdentifier] Could not fetch brands list from dictionary service, continuing without it');
117
+ return [2 /*return*/, null];
84
118
  }
85
119
  return [2 /*return*/, brands];
120
+ case 3:
121
+ err_1 = _a.sent();
122
+ // tslint:disable-next-line no-console
123
+ console.log('[BrandIdentifier] Error fetching brands list, continuing without it:', err_1);
124
+ return [2 /*return*/, null];
125
+ case 4: return [2 /*return*/];
86
126
  }
87
127
  });
88
128
  });
@@ -3,6 +3,11 @@ export declare class BrandManager {
3
3
  private readonly defaultBrand;
4
4
  constructor(type: string);
5
5
  getB2CBrand(req: any): string;
6
+ /**
7
+ * Extract brand from JWT token payload
8
+ * @param token - JWT token string (with or without Bearer prefix)
9
+ */
10
+ extractBrandFromToken(token: string): string[] | null;
6
11
  getConsoleBrands(req: any): Promise<string[] | null>;
7
12
  loadBrands(req: any): Promise<string[] | null>;
8
13
  /**
@@ -14,7 +14,7 @@ var __generator = (this && this.__generator) || function (thisArg, body) {
14
14
  function verb(n) { return function (v) { return step([n, v]); }; }
15
15
  function step(op) {
16
16
  if (f) throw new TypeError("Generator is already executing.");
17
- while (g && (g = 0, op[0] && (_ = 0)), _) try {
17
+ while (_) try {
18
18
  if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
19
19
  if (y = 0, t) op = [op[0] & 2, t.value];
20
20
  switch (op[0]) {
@@ -35,15 +35,14 @@ var __generator = (this && this.__generator) || function (thisArg, body) {
35
35
  if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
36
36
  }
37
37
  };
38
+ var __importDefault = (this && this.__importDefault) || function (mod) {
39
+ return (mod && mod.__esModule) ? mod : { "default": mod };
40
+ };
38
41
  Object.defineProperty(exports, "__esModule", { value: true });
39
42
  exports.BrandManager = void 0;
40
- var AlmatarBranding_1 = require("./AlmatarBranding");
41
- var Storage_1 = require("./Storage");
43
+ var AlmatarBranding_1 = __importDefault(require("./AlmatarBranding"));
44
+ var Storage_1 = __importDefault(require("./Storage"));
42
45
  var PromiseRequest_1 = require("./request/PromiseRequest");
43
- var NodeCahe = require("node-cache");
44
- var cacheManager = new NodeCahe({
45
- stdTTL: 86400
46
- });
47
46
  var BrandManager = /** @class */ (function () {
48
47
  function BrandManager(type) {
49
48
  this.defaultBrand = 'almatar';
@@ -52,39 +51,99 @@ var BrandManager = /** @class */ (function () {
52
51
  BrandManager.prototype.getB2CBrand = function (req) {
53
52
  return req.headers['x-brand'];
54
53
  };
54
+ /**
55
+ * Extract brand from JWT token payload
56
+ * @param token - JWT token string (with or without Bearer prefix)
57
+ */
58
+ BrandManager.prototype.extractBrandFromToken = function (token) {
59
+ try {
60
+ // Remove 'Bearer ' prefix if present
61
+ var cleanToken = token.replace(/^Bearer\s+/i, '');
62
+ // JWT format: header.payload.signature
63
+ var parts = cleanToken.split('.');
64
+ if (parts.length !== 3) {
65
+ // tslint:disable-next-line no-console
66
+ console.log('[BrandManager] Invalid JWT token format - expected 3 parts');
67
+ return null;
68
+ }
69
+ // Decode payload (base64url)
70
+ var payload = parts[1];
71
+ // Replace URL-safe base64 characters
72
+ var base64 = payload.replace(/-/g, '+').replace(/_/g, '/');
73
+ // Add padding if needed
74
+ var padded = base64 + '='.repeat((4 - (base64.length % 4)) % 4);
75
+ var decoded = Buffer.from(padded, 'base64').toString('utf-8');
76
+ var tokenPayload = JSON.parse(decoded);
77
+ // Extract brand from token payload
78
+ if (tokenPayload.brand) {
79
+ // Brand can be array or single string
80
+ var brands = void 0;
81
+ if (Array.isArray(tokenPayload.brand)) {
82
+ brands = tokenPayload.brand;
83
+ }
84
+ else if (typeof tokenPayload.brand === 'string') {
85
+ brands = [tokenPayload.brand];
86
+ }
87
+ else {
88
+ // tslint:disable-next-line no-console
89
+ console.log('[BrandManager] Brand in token is neither array nor string:', typeof tokenPayload.brand);
90
+ return null;
91
+ }
92
+ // tslint:disable-next-line no-console
93
+ console.log('[BrandManager] Successfully extracted brands from token:', brands);
94
+ return brands;
95
+ }
96
+ // tslint:disable-next-line no-console
97
+ console.log('[BrandManager] No brand field found in token payload');
98
+ return null;
99
+ }
100
+ catch (err) {
101
+ // tslint:disable-next-line no-console
102
+ console.log('[BrandManager] Error extracting brand from token:', err);
103
+ return null;
104
+ }
105
+ };
55
106
  BrandManager.prototype.getConsoleBrands = function (req) {
56
107
  return __awaiter(this, void 0, void 0, function () {
57
- var reqBody, brands;
108
+ var brands, tokenBrands;
58
109
  return __generator(this, function (_a) {
59
- switch (_a.label) {
60
- case 0:
61
- if (req.headers['x-employee-brands']) {
62
- return [2 /*return*/, req.headers['x-employee-brands'].split(',')];
63
- }
64
- reqBody = req.payload ? req.payload : req.body;
65
- return [4 /*yield*/, this.loadBrands(req)];
66
- case 1:
67
- brands = _a.sent();
68
- if (reqBody && reqBody.brand) {
69
- Storage_1.default.setBrand(reqBody.brand);
70
- }
110
+ // Priority 1: Check x-employee-brands header first
111
+ if (req.headers['x-employee-brands']) {
112
+ brands = req.headers['x-employee-brands'].split(',').map(function (b) { return b.trim(); }).filter(function (b) { return b; });
113
+ // tslint:disable-next-line no-console
114
+ console.log('[BrandManager] Extracted brands from x-employee-brands header:', brands);
115
+ if (brands.length > 0) {
71
116
  return [2 /*return*/, brands];
117
+ }
118
+ }
119
+ // Priority 2: Try to extract brand from JWT token
120
+ if (req.headers.authorization) {
121
+ tokenBrands = this.extractBrandFromToken(req.headers.authorization);
122
+ if (tokenBrands && tokenBrands.length > 0) {
123
+ // tslint:disable-next-line no-console
124
+ console.log('[BrandManager] Using brands extracted from token:', tokenBrands);
125
+ return [2 /*return*/, tokenBrands];
126
+ }
72
127
  }
128
+ // DO NOT call loadBrands() here - it makes HTTP requests that can cause infinite loops
129
+ // If we don't have brand from token/header, return null instead
130
+ // tslint:disable-next-line no-console
131
+ console.log('[BrandManager] No brand found in token or headers, returning null (skipping loadBrands to prevent loops)');
132
+ return [2 /*return*/, null];
73
133
  });
74
134
  });
75
135
  };
76
136
  BrandManager.prototype.loadBrands = function (req) {
77
137
  return __awaiter(this, void 0, void 0, function () {
78
- var reqBody, employeeBrands, options, brands, err_1;
138
+ var reqBody, options, employeeBrands, brandsData, brands, err_1;
79
139
  return __generator(this, function (_a) {
80
140
  switch (_a.label) {
81
141
  case 0:
82
- _a.trys.push([0, 4, , 5]);
142
+ _a.trys.push([0, 2, , 3]);
83
143
  reqBody = req.payload ? req.payload : req.body;
84
- employeeBrands = cacheManager.get('employee_brands');
85
- if (!!(employeeBrands === null || employeeBrands === void 0 ? void 0 : employeeBrands.status)) return [3 /*break*/, 3];
86
144
  options = {
87
145
  url: AlmatarBranding_1.default.employeeAuthService + '/v1/user/brands',
146
+ method: 'GET',
88
147
  headers: {
89
148
  authorization: req.headers.authorization,
90
149
  },
@@ -92,25 +151,43 @@ var BrandManager = /** @class */ (function () {
92
151
  return [4 /*yield*/, PromiseRequest_1.PromiseRequest.request(options)];
93
152
  case 1:
94
153
  employeeBrands = _a.sent();
95
- return [4 /*yield*/, cacheManager.set('employee_brands', employeeBrands)];
96
- case 2:
97
- _a.sent();
98
- _a.label = 3;
99
- case 3:
100
- if (employeeBrands.status === 200) {
101
- brands = employeeBrands.data.map(function (brand) { return brand.slug; });
102
- if (reqBody && reqBody.brand) {
103
- return [2 /*return*/, brands.indexOf(reqBody.brand) > -1 ? brands : null];
154
+ // Check if response is valid and has the expected structure
155
+ if (employeeBrands && employeeBrands.status === 200 && employeeBrands.data) {
156
+ brandsData = Array.isArray(employeeBrands.data)
157
+ ? employeeBrands.data
158
+ : (employeeBrands.data.data || employeeBrands.data.list || []);
159
+ if (Array.isArray(brandsData) && brandsData.length > 0) {
160
+ brands = brandsData
161
+ .map(function (brand) {
162
+ if (typeof brand === 'string') {
163
+ return brand;
164
+ }
165
+ return (brand === null || brand === void 0 ? void 0 : brand.slug) || '';
166
+ })
167
+ .filter(function (b) { return !!b; });
168
+ if (reqBody && reqBody.brand) {
169
+ return [2 /*return*/, brands.indexOf(reqBody.brand) > -1 ? brands : null];
170
+ }
171
+ // tslint:disable-next-line no-console
172
+ console.log('[BrandManager] Successfully loaded brands from employee auth service:', brands);
173
+ return [2 /*return*/, brands];
104
174
  }
105
- return [2 /*return*/, brands];
175
+ else {
176
+ // tslint:disable-next-line no-console
177
+ console.log('[BrandManager] Invalid response structure from employee auth service, expected array but got:', typeof brandsData);
178
+ }
179
+ }
180
+ else {
181
+ // tslint:disable-next-line no-console
182
+ console.log('[BrandManager] Failed to load brands from employee auth service, status:', employeeBrands === null || employeeBrands === void 0 ? void 0 : employeeBrands.status, 'data:', employeeBrands === null || employeeBrands === void 0 ? void 0 : employeeBrands.data);
106
183
  }
107
184
  return [2 /*return*/, null];
108
- case 4:
185
+ case 2:
109
186
  err_1 = _a.sent();
110
187
  // tslint:disable-next-line no-console
111
- console.log(err_1);
188
+ console.log('[BrandManager] Error loading brands:', err_1);
112
189
  return [2 /*return*/, null];
113
- case 5: return [2 /*return*/];
190
+ case 3: return [2 /*return*/];
114
191
  }
115
192
  });
116
193
  });
@@ -120,38 +197,54 @@ var BrandManager = /** @class */ (function () {
120
197
  * @param req
121
198
  */
122
199
  BrandManager.prototype.getBrands = function () {
200
+ var _a;
123
201
  return __awaiter(this, void 0, void 0, function () {
124
- var brandsResponse, option, brands, err_2;
125
- return __generator(this, function (_a) {
126
- switch (_a.label) {
202
+ var option, brandsResponse, brandsList, brands, err_2;
203
+ return __generator(this, function (_b) {
204
+ switch (_b.label) {
127
205
  case 0:
128
- _a.trys.push([0, 4, , 5]);
129
- brandsResponse = cacheManager.get('cachedBrands');
130
- if (!!(brandsResponse === null || brandsResponse === void 0 ? void 0 : brandsResponse.status)) return [3 /*break*/, 3];
206
+ _b.trys.push([0, 2, , 3]);
131
207
  option = {
132
208
  url: AlmatarBranding_1.default.dictionaryService + 'brands',
209
+ method: 'GET',
133
210
  };
134
211
  return [4 /*yield*/, PromiseRequest_1.PromiseRequest.request(option)];
135
212
  case 1:
136
- brandsResponse = _a.sent();
137
- return [4 /*yield*/, cacheManager.set('cachedBrands', brandsResponse)];
138
- case 2:
139
- _a.sent();
140
- _a.label = 3;
141
- case 3:
142
- if (brandsResponse.status === 200) {
143
- Storage_1.default.setBrandsList(brandsResponse.data.list);
144
- brands = brandsResponse.data.list.map(function (brand) { return brand.key; });
145
- Storage_1.default.setBrands(brands);
146
- return [2 /*return*/, brands];
213
+ brandsResponse = _b.sent();
214
+ // Check if response is valid and has the expected structure
215
+ if (brandsResponse && brandsResponse.status === 200 && brandsResponse.data) {
216
+ brandsList = brandsResponse.data.list || ((_a = brandsResponse.data.data) === null || _a === void 0 ? void 0 : _a.list) || brandsResponse.data;
217
+ if (Array.isArray(brandsList) && brandsList.length > 0) {
218
+ Storage_1.default.setBrandsList(brandsList);
219
+ brands = brandsList
220
+ .map(function (brand) {
221
+ if (typeof brand === 'string') {
222
+ return brand;
223
+ }
224
+ return (brand === null || brand === void 0 ? void 0 : brand.key) || '';
225
+ })
226
+ .filter(function (b) { return !!b; });
227
+ Storage_1.default.setBrands(brands);
228
+ // tslint:disable-next-line:no-console
229
+ console.log('[BrandManager] Successfully loaded brands from dictionary service:', brands);
230
+ return [2 /*return*/, brands];
231
+ }
232
+ else {
233
+ // tslint:disable-next-line:no-console
234
+ console.log('[BrandManager] Invalid response structure from dictionary service, expected array but got:', typeof brandsList);
235
+ }
236
+ }
237
+ else {
238
+ // tslint:disable-next-line:no-console
239
+ console.log('[BrandManager] Failed to get brands from dictionary service, status:', brandsResponse === null || brandsResponse === void 0 ? void 0 : brandsResponse.status, 'data:', brandsResponse === null || brandsResponse === void 0 ? void 0 : brandsResponse.data);
147
240
  }
148
241
  return [2 /*return*/, null];
149
- case 4:
150
- err_2 = _a.sent();
242
+ case 2:
243
+ err_2 = _b.sent();
151
244
  // tslint:disable-next-line:no-console
152
- console.log(err_2);
245
+ console.log('[BrandManager] Error getting brands from dictionary service:', err_2);
153
246
  return [2 /*return*/, null];
154
- case 5: return [2 /*return*/];
247
+ case 3: return [2 /*return*/];
155
248
  }
156
249
  });
157
250
  });
@@ -14,7 +14,7 @@ var __generator = (this && this.__generator) || function (thisArg, body) {
14
14
  function verb(n) { return function (v) { return step([n, v]); }; }
15
15
  function step(op) {
16
16
  if (f) throw new TypeError("Generator is already executing.");
17
- while (g && (g = 0, op[0] && (_ = 0)), _) try {
17
+ while (_) try {
18
18
  if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
19
19
  if (y = 0, t) op = [op[0] & 2, t.value];
20
20
  switch (op[0]) {
@@ -74,15 +74,23 @@ var ContextNamespace = /** @class */ (function () {
74
74
  case 1:
75
75
  brand = _a.sent();
76
76
  if (Array.isArray(brand)) {
77
+ // tslint:disable-next-line no-console
78
+ console.log('[ContextNamespace] Setting employeeBrands in context:', brand);
77
79
  ns.set('employeeBrands', brand);
78
80
  next();
79
81
  }
80
82
  else if (typeof brand === 'string') {
83
+ // tslint:disable-next-line no-console
84
+ console.log('[ContextNamespace] Setting brand in context:', brand);
81
85
  ns.set('brand', brand);
82
86
  next();
83
87
  }
84
88
  else {
85
- next(brand);
89
+ // Brand is null or undefined - set empty array for employeeBrands
90
+ // tslint:disable-next-line no-console
91
+ console.log('[ContextNamespace] No brand found, setting empty array for employeeBrands');
92
+ ns.set('employeeBrands', []);
93
+ next();
86
94
  }
87
95
  return [2 /*return*/];
88
96
  }
@@ -1,7 +1,10 @@
1
1
  "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
2
5
  Object.defineProperty(exports, "__esModule", { value: true });
3
6
  exports.MongooseModel = void 0;
4
- var Storage_1 = require("../Storage");
7
+ var Storage_1 = __importDefault(require("../Storage"));
5
8
  var MongooseModel = /** @class */ (function () {
6
9
  function MongooseModel(mongoose) {
7
10
  this.mongoose = mongoose;
@@ -18,7 +21,7 @@ var MongooseModel = /** @class */ (function () {
18
21
  this.addPreSaveQueries(schema);
19
22
  this.addPreInsertManyQueries(schema);
20
23
  }
21
- var modelName = skipBrand || !Array.isArray(brands) ? name : "".concat(name, "-").concat(brands.join('-'));
24
+ var modelName = skipBrand || !Array.isArray(brands) ? name : name + "-" + brands.join('-');
22
25
  if (!existingModels[modelName]) {
23
26
  existingModels[modelName] = this.mongoose.model(modelName, schema, options);
24
27
  }
@@ -3,12 +3,10 @@ var __extends = (this && this.__extends) || (function () {
3
3
  var extendStatics = function (d, b) {
4
4
  extendStatics = Object.setPrototypeOf ||
5
5
  ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
6
- function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
6
+ function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
7
7
  return extendStatics(d, b);
8
8
  };
9
9
  return function (d, b) {
10
- if (typeof b !== "function" && b !== null)
11
- throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
12
10
  extendStatics(d, b);
13
11
  function __() { this.constructor = d; }
14
12
  d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
@@ -31,8 +29,8 @@ var TenantMongooseModule = /** @class */ (function (_super) {
31
29
  }
32
30
  TenantMongooseModule.forFeature = function (models, connectionName) {
33
31
  if (models === void 0) { models = []; }
34
- connectionName = connectionName ? "".concat(connectionName, "Connection") : 'MongooseConnectionName';
35
- var modelProviders = (0, mongoose_providers_1.createMongooseProviders)(connectionName, models);
32
+ connectionName = connectionName ? connectionName + "Connection" : 'MongooseConnectionName';
33
+ var modelProviders = mongoose_providers_1.createMongooseProviders(connectionName, models);
36
34
  return {
37
35
  module: mongoose_1.MongooseModule,
38
36
  providers: modelProviders,
@@ -40,7 +38,7 @@ var TenantMongooseModule = /** @class */ (function (_super) {
40
38
  };
41
39
  };
42
40
  TenantMongooseModule = __decorate([
43
- (0, common_1.Module)({})
41
+ common_1.Module({})
44
42
  ], TenantMongooseModule);
45
43
  return TenantMongooseModule;
46
44
  }(mongoose_1.MongooseModule));
@@ -5,12 +5,12 @@ var MongooseModel_1 = require("../MongooseModel");
5
5
  function createMongooseProviders(connectionName, models) {
6
6
  if (models === void 0) { models = []; }
7
7
  var providers = (models || []).map(function (model) { return ({
8
- provide: "".concat(model.name, "Model"),
8
+ provide: model.name + "Model",
9
9
  useFactory: function (connection) {
10
10
  var mongooseModel = new MongooseModel_1.MongooseModel(connection);
11
11
  return mongooseModel.createModel(model.name, model.schema, model.collection, {});
12
12
  },
13
- inject: ["".concat(connectionName, "Connection")],
13
+ inject: [connectionName + "Connection"],
14
14
  }); });
15
15
  return providers;
16
16
  }
@@ -1,4 +1,15 @@
1
1
  "use strict";
2
+ var __assign = (this && this.__assign) || function () {
3
+ __assign = Object.assign || function(t) {
4
+ for (var s, i = 1, n = arguments.length; i < n; i++) {
5
+ s = arguments[i];
6
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
7
+ t[p] = s[p];
8
+ }
9
+ return t;
10
+ };
11
+ return __assign.apply(this, arguments);
12
+ };
2
13
  var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
14
  function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
15
  return new (P || (P = Promise))(function (resolve, reject) {
@@ -14,7 +25,7 @@ var __generator = (this && this.__generator) || function (thisArg, body) {
14
25
  function verb(n) { return function (v) { return step([n, v]); }; }
15
26
  function step(op) {
16
27
  if (f) throw new TypeError("Generator is already executing.");
17
- while (g && (g = 0, op[0] && (_ = 0)), _) try {
28
+ while (_) try {
18
29
  if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
19
30
  if (y = 0, t) op = [op[0] & 2, t.value];
20
31
  switch (op[0]) {
@@ -37,22 +48,54 @@ var __generator = (this && this.__generator) || function (thisArg, body) {
37
48
  };
38
49
  Object.defineProperty(exports, "__esModule", { value: true });
39
50
  exports.PromiseRequest = void 0;
40
- var request = require("request");
41
51
  var PromiseRequest = /** @class */ (function () {
42
52
  function PromiseRequest() {
43
53
  }
44
54
  PromiseRequest.request = function (options) {
45
55
  return __awaiter(this, void 0, void 0, function () {
56
+ var url, method, headers, body, response, responseData, parsedBody, err_1;
46
57
  return __generator(this, function (_a) {
47
- return [2 /*return*/, new Promise(function (resolve, reject) {
48
- request(options, function (err, response, body) {
49
- if (err) {
50
- reject(err);
51
- }
52
- body = body ? JSON.parse(body) : null;
53
- resolve(body);
54
- });
55
- })];
58
+ switch (_a.label) {
59
+ case 0:
60
+ _a.trys.push([0, 3, , 4]);
61
+ url = options.url || options.uri;
62
+ method = options.method || 'GET';
63
+ headers = options.headers || {};
64
+ body = options.body ? JSON.stringify(options.body) : undefined;
65
+ // tslint:disable-next-line no-console
66
+ console.log('[PromiseRequest] Making request:', { url: url, method: method, headers: __assign(__assign({}, headers), { authorization: headers.authorization ? 'Bearer ***' : undefined }) });
67
+ return [4 /*yield*/, fetch(url, {
68
+ method: method,
69
+ headers: __assign({ 'Content-Type': 'application/json' }, headers),
70
+ body: body,
71
+ })];
72
+ case 1:
73
+ response = _a.sent();
74
+ return [4 /*yield*/, response.text()];
75
+ case 2:
76
+ responseData = _a.sent();
77
+ parsedBody = void 0;
78
+ try {
79
+ parsedBody = responseData ? JSON.parse(responseData) : null;
80
+ }
81
+ catch (parseError) {
82
+ // tslint:disable-next-line no-console
83
+ console.log('[PromiseRequest] Failed to parse response as JSON:', parseError);
84
+ parsedBody = responseData;
85
+ }
86
+ // Return in the same format as the old request library
87
+ return [2 /*return*/, {
88
+ status: response.status,
89
+ data: parsedBody,
90
+ body: parsedBody,
91
+ }];
92
+ case 3:
93
+ err_1 = _a.sent();
94
+ // tslint:disable-next-line no-console
95
+ console.log('[PromiseRequest] Request error:', err_1);
96
+ throw err_1;
97
+ case 4: return [2 /*return*/];
98
+ }
56
99
  });
57
100
  });
58
101
  };
@@ -1,4 +1,7 @@
1
1
  declare class TenantRequest {
2
- static request(options: any): Promise<any>;
2
+ static request(options: any): Promise<{
3
+ status: number;
4
+ data: any;
5
+ } | null>;
3
6
  }
4
7
  export default TenantRequest;
@@ -1,4 +1,15 @@
1
1
  "use strict";
2
+ var __assign = (this && this.__assign) || function () {
3
+ __assign = Object.assign || function(t) {
4
+ for (var s, i = 1, n = arguments.length; i < n; i++) {
5
+ s = arguments[i];
6
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
7
+ t[p] = s[p];
8
+ }
9
+ return t;
10
+ };
11
+ return __assign.apply(this, arguments);
12
+ };
2
13
  var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
14
  function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
15
  return new (P || (P = Promise))(function (resolve, reject) {
@@ -14,7 +25,7 @@ var __generator = (this && this.__generator) || function (thisArg, body) {
14
25
  function verb(n) { return function (v) { return step([n, v]); }; }
15
26
  function step(op) {
16
27
  if (f) throw new TypeError("Generator is already executing.");
17
- while (g && (g = 0, op[0] && (_ = 0)), _) try {
28
+ while (_) try {
18
29
  if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
19
30
  if (y = 0, t) op = [op[0] & 2, t.value];
20
31
  switch (op[0]) {
@@ -35,35 +46,56 @@ var __generator = (this && this.__generator) || function (thisArg, body) {
35
46
  if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
36
47
  }
37
48
  };
49
+ var __importDefault = (this && this.__importDefault) || function (mod) {
50
+ return (mod && mod.__esModule) ? mod : { "default": mod };
51
+ };
38
52
  Object.defineProperty(exports, "__esModule", { value: true });
39
- var Storage_1 = require("../Storage");
40
- var node_fetch_1 = require("node-fetch");
53
+ var Storage_1 = __importDefault(require("../Storage"));
41
54
  var TenantRequest = /** @class */ (function () {
42
55
  function TenantRequest() {
43
56
  }
44
57
  TenantRequest.request = function (options) {
58
+ var _a, _b, _c;
45
59
  return __awaiter(this, void 0, void 0, function () {
46
- var brand, employeeBrands;
47
- return __generator(this, function (_a) {
48
- switch (_a.label) {
60
+ var brand, employeeBrands, headers, fetchOptions, response, data, e_1;
61
+ return __generator(this, function (_d) {
62
+ switch (_d.label) {
49
63
  case 0:
64
+ _d.trys.push([0, 3, , 4]);
50
65
  brand = Storage_1.default.getBrand();
51
66
  employeeBrands = Storage_1.default.getEmployeeBrands();
52
- if (!options.reqObject.headers) {
53
- options.reqObject.headers = {};
67
+ headers = __assign({ 'Content-Type': 'application/json' }, (((_a = options.reqObject) === null || _a === void 0 ? void 0 : _a.headers) || {}));
68
+ if (brand) {
69
+ headers['x-brand'] = brand;
70
+ }
71
+ if (employeeBrands && employeeBrands.length > 0) {
72
+ headers['x-employee-brands'] = employeeBrands.join(',');
73
+ }
74
+ fetchOptions = {
75
+ method: ((_b = options.reqObject) === null || _b === void 0 ? void 0 : _b.method) || 'GET',
76
+ headers: headers,
77
+ };
78
+ if ((_c = options.reqObject) === null || _c === void 0 ? void 0 : _c.body) {
79
+ fetchOptions.body = typeof options.reqObject.body === 'string'
80
+ ? options.reqObject.body
81
+ : JSON.stringify(options.reqObject.body);
54
82
  }
55
- options.reqObject.headers['Content-Type'] = 'application/json';
56
- options.reqObject.headers['x-brand'] = brand;
57
- // tslint:disable-next-line:no-unused-expression
58
- employeeBrands ? (options.reqObject.headers['x-employee-brands'] = employeeBrands.join(',')) : null;
59
- return [4 /*yield*/, (0, node_fetch_1.default)(options.url, options.reqObject)
60
- .then(function (res) {
61
- return res.json();
62
- })
63
- .catch(function (e) {
64
- return null;
65
- })];
66
- case 1: return [2 /*return*/, _a.sent()];
83
+ return [4 /*yield*/, fetch(options.url, fetchOptions)];
84
+ case 1:
85
+ response = _d.sent();
86
+ return [4 /*yield*/, response.json()];
87
+ case 2:
88
+ data = _d.sent();
89
+ return [2 /*return*/, {
90
+ status: response.status,
91
+ data: data,
92
+ }];
93
+ case 3:
94
+ e_1 = _d.sent();
95
+ // tslint:disable-next-line no-console
96
+ console.log('[TenantRequest] Request error:', e_1);
97
+ return [2 /*return*/, null];
98
+ case 4: return [2 /*return*/];
67
99
  }
68
100
  });
69
101
  });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@almatar/branding",
3
- "version": "0.1.9-alpha",
3
+ "version": "1.0.0-beta.2",
4
4
  "description": "",
5
5
  "main": "lib/index.js",
6
6
  "types": "lib/index.d.ts",
@@ -8,12 +8,14 @@
8
8
  "lib/**/*"
9
9
  ],
10
10
  "scripts": {
11
- "build": "tsc",
11
+ "build": "node scripts/build.js",
12
12
  "format": "prettier --write \"src/**/*.ts\" \"src/**/*.js\"",
13
13
  "lint": "tslint -p tsconfig.json",
14
14
  "test": "jest --config jestconfig.json",
15
15
  "prepare": "npm run build",
16
16
  "prepublishOnly": "npm test && npm run lint",
17
+ "publish:beta": "npm publish --tag beta",
18
+ "publish:latest": "npm publish --tag latest",
17
19
  "preversion": "npm run lint",
18
20
  "version": "npm run format && git add -A && git commit -m \"Setup Package\"",
19
21
  "postversion": "git push && git push --tags"
@@ -27,11 +29,9 @@
27
29
  "@nestjs/core": "^6.8.2",
28
30
  "@nestjs/mongoose": "^6.1.2",
29
31
  "@types/mongoose": "^5.5.19",
30
- "@types/node-cache": "^4.2.5",
31
32
  "@types/request": "^2.48.3",
32
33
  "cls-hooked": "^4.2.2",
33
34
  "mongoose": "^5.7.3",
34
- "node-cache": "^5.1.2",
35
35
  "node-fetch": "^2.6.1",
36
36
  "reflect-metadata": "^0.1.13",
37
37
  "request": "^2.88.0",
@@ -53,7 +53,6 @@
53
53
  "ts-jest": "^24.1.0",
54
54
  "tslint": "^5.20.0",
55
55
  "tslint-config-prettier": "^1.18.0",
56
- "ts-node": "^10.8.1",
57
- "typescript": "^4.6.3"
56
+ "typescript": "^3.6.3"
58
57
  }
59
- }
58
+ }