@xrystal/core 3.8.4 → 3.8.7

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/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "author": "Yusuf Yasir KAYGUSUZ",
3
3
  "name": "@xrystal/core",
4
- "version": "3.8.4",
4
+ "version": "3.8.7",
5
5
  "description": "Project core for xrystal",
6
6
  "publishConfig": {
7
7
  "access": "public",
@@ -0,0 +1,10 @@
1
+ import { BaseApiClient } from '../../utils/index';
2
+ import ConfigsService from '../configs';
3
+ export default class ClientsService {
4
+ static services: Record<string, any>;
5
+ apiClient: BaseApiClient;
6
+ baseApiClientName: string;
7
+ load({ configs }: {
8
+ configs: ConfigsService;
9
+ }): Promise<void>;
10
+ }
@@ -0,0 +1,13 @@
1
+ import { BaseApiClient } from '../../utils/index';
2
+ export default class ClientsService {
3
+ static services = {};
4
+ apiClient;
5
+ baseApiClientName = 'base-api-client';
6
+ async load({ configs }) {
7
+ this.apiClient = new BaseApiClient({
8
+ clientName: this.baseApiClientName,
9
+ baseURL: configs.all.baseApiUri || ''
10
+ });
11
+ ClientsService.services[this.baseApiClientName] = this.apiClient;
12
+ }
13
+ }
@@ -12,6 +12,7 @@ export default class ConfigsService {
12
12
  serviceName: rawConfigs.service,
13
13
  port: process.env.PORT || rawConfigs.port || 3000,
14
14
  systemStaticFolderPath: path.resolve(rawConfigs.rootFolderPath, this.publicFolderName),
15
+ baseApiUri: process.env.HTTPS === 'true' ? process.env.SYSTEM_HTTPS_BASE_API_URI : process.env.SYSTEM_BASE_API_URI,
15
16
  env: process.env.NODE_ENV,
16
17
  ...rawConfigs
17
18
  };
@@ -1,6 +1,9 @@
1
+ import LoggerService from '../logger/index';
1
2
  export default class EventsService {
2
3
  private logger;
3
- load: ({}: {}) => any;
4
+ load: ({ logger, }: {
5
+ logger: LoggerService;
6
+ }) => any;
4
7
  private _globalLoader;
5
8
  get global(): any;
6
9
  }
@@ -1,8 +1,7 @@
1
- import LoggersLoader from '../logger/index';
2
- import { x, LoggerLayerEnum } from '../../utils/index';
1
+ import { LoggerLayerEnum } from '../../utils/index';
3
2
  export default class EventsService {
4
- logger = x.get(LoggersLoader);
5
- load = ({}) => {
3
+ logger;
4
+ load = ({ logger, }) => {
6
5
  this._globalLoader();
7
6
  };
8
7
  _globalLoader = () => {
@@ -1,5 +1,5 @@
1
- export declare const coreInit: ({ locales }: {
2
- locales: Record<string, any>;
1
+ export declare const coreInit: (params: {
2
+ locales?: Record<string, any>;
3
3
  }) => Promise<void>;
4
4
  declare const coreLoader: ({}: {}) => Promise<{
5
5
  _?: undefined;
@@ -2,10 +2,13 @@
2
2
  import path from 'path';
3
3
  import { SystemService, ConfigsService, LoggerService, EventsService, LocalizationsService } from '../loader/index';
4
4
  import { packageName, tmpFileDefaultName, tmpFileDefaultExt, findFileRecursively, TmpFileLoader, x, kafkaBrokers, systemLoggerLayer, } from '../utils/index';
5
+ import ClientsService from 'source/loader/clients';
5
6
  //
6
7
  let coreHasRun = false;
7
- export const coreInit = async ({ locales }) => {
8
- globalThis.__LOCAL_MESSAGES__ = locales;
8
+ export const coreInit = async (params) => {
9
+ const { locales } = params;
10
+ if (locales)
11
+ globalThis.__LOCAL_MESSAGES__ = locales;
9
12
  };
10
13
  const coreLoader = async ({}) => {
11
14
  if (coreHasRun)
@@ -32,8 +35,9 @@ const coreLoader = async ({}) => {
32
35
  const logger = x.get(LoggerService);
33
36
  const events = x.get(EventsService);
34
37
  const i18n = x.get(LocalizationsService);
38
+ const clientsService = x.get(ClientsService);
35
39
  await system.load({
36
- tmp: { _: r }
40
+ tmp: r
37
41
  });
38
42
  configService.load({
39
43
  tmp: r,
@@ -48,12 +52,17 @@ const coreLoader = async ({}) => {
48
52
  kafkaBrokers: kafkaBrokers ?? "",
49
53
  kafkaTopic: configs.loaders.loggers.topic
50
54
  });
51
- await events.load({});
55
+ await events.load({
56
+ logger
57
+ });
52
58
  await i18n.load({
53
59
  loadPath: path.resolve(rootFolderPath, configs.loaders.localization.loadPath),
54
60
  fallbackLang: configs.loaders.localization.fallbackLang,
55
61
  preloadLang: configs.loaders.localization.preloadLangs
56
62
  });
63
+ await clientsService.load({
64
+ configs: configService,
65
+ });
57
66
  coreHasRun = true;
58
67
  return { _: r };
59
68
  }
@@ -1,129 +1,62 @@
1
- import { AxiosInstance } from 'axios';
2
1
  import nodemailer from 'nodemailer';
3
- import { LoggerService } from '../../../loader/index';
4
- export interface IAuth {
5
- authentication: (params: any) => Promise<void> | any;
6
- }
7
- declare abstract class Service {
2
+ import { ConfigsService, LoggerService } from 'source/loader';
3
+ export declare abstract class Service {
4
+ protected configService: ConfigsService;
8
5
  protected logger: LoggerService;
9
6
  clientName: string;
10
7
  protected baseURL: string;
11
8
  protected version: string | null;
12
- protected headers: any;
13
9
  protected timeout: number;
14
- /***************
15
- * CONSTRUCTOR *
16
- ***************/
17
- protected constructor({ clientName, baseURL, version, timeout, headers, }: {
10
+ constructor({ clientName, baseURL, version, timeout }: {
18
11
  clientName: string;
19
12
  baseURL: string;
20
13
  version?: string;
21
14
  timeout?: number;
22
- headers?: {
23
- 'Content-Type'?: string;
24
- 'Lang'?: string;
25
- 'Authorization'?: string;
26
- };
27
15
  });
28
- /***********
29
- * HELPERS *
30
- ***********/
31
- protected interceptorErrorComplement(error: any): void;
32
- routeSlashChecker(route: string): string;
33
16
  static cryptoHashGenerate: ({ algorithm, input, digest }: {
34
17
  algorithm: string;
35
18
  input: string;
36
19
  digest?: string;
37
20
  }) => string;
38
- static cryptoHashDecrypt: ({ algorithm, input, keyEncoding, key, initializationVector, inputEncoding, outputEncoding, }: {
39
- algorithm: string;
40
- input: string;
41
- keyEncoding?: string;
42
- key: string;
43
- initializationVector: string;
44
- inputEncoding?: BufferEncoding;
45
- outputEncoding?: BufferEncoding;
46
- }) => string;
47
- static objectToFormData: (object: any) => FormData;
48
- static generateRandomNumber: ({ prefix, suffix, hyphen, length, totalLength }: {
49
- prefix?: string;
50
- suffix?: string;
51
- hyphen?: boolean;
21
+ static generateRandomNumber: ({ length }: {
52
22
  length?: number;
53
- totalLength?: number | null;
54
23
  }) => string;
55
24
  }
56
- export declare class ServiceStore {
57
- private static _instance;
58
- private _store;
59
- private constructor();
60
- static create(): ServiceStore;
61
- set setStore(callback: (store: Record<any, any>) => any);
62
- get instance(): Record<any, any> | null;
63
- get store(): Record<any, any>;
64
- }
65
- export declare class EmailClient extends Service {
66
- private _port;
67
- private _username;
68
- private _password;
69
- constructor({ clientName, baseURL, version, port, username, password, }: {
25
+ export declare class BaseApiClient extends Service {
26
+ constructor(config: {
70
27
  clientName: string;
71
28
  baseURL: string;
72
29
  version?: string;
73
- port?: number;
74
- username: string;
75
- password: string;
30
+ timeout?: number;
76
31
  });
77
- /***********
78
- * LOADERS *
79
- ***********/
80
- nodemailerLoader({ host, port, username, password, secure, }: {
81
- host?: string;
82
- port?: number;
83
- username?: string;
84
- password?: string;
85
- secure?: boolean;
86
- }): nodemailer.Transporter<import("nodemailer/lib/smtp-transport").SentMessageInfo, import("nodemailer/lib/smtp-transport").Options>;
32
+ request(path: string, options?: RequestInit): Promise<Response>;
87
33
  }
88
- export declare class AxiosClient extends Service {
89
- constructor({ clientName, baseURL, version }: {
34
+ export declare abstract class AuthenticatedApiClient extends BaseApiClient {
35
+ accessToken?: string;
36
+ constructor(config: {
90
37
  clientName: string;
91
38
  baseURL: string;
92
39
  version?: string;
40
+ timeout?: number;
93
41
  });
94
- /***********
95
- * LOADERS *
96
- ***********/
97
- protected axiosLoader(): AxiosInstance;
42
+ request(path: string, options?: RequestInit): Promise<Response>;
43
+ abstract authentication(): Promise<any>;
98
44
  }
99
- export declare class SoapClient extends Service {
100
- private client;
101
- constructor({ clientName, baseURL, version }: {
45
+ export declare class EmailClient extends Service {
46
+ constructor(config: {
102
47
  clientName: string;
103
48
  baseURL: string;
104
49
  version?: string;
50
+ timeout?: number;
105
51
  });
106
- getAsyncBaseClient(): Promise<{
107
- [key: string]: any;
108
- }>;
109
- createAsyncClient({ fullURL }: {
110
- fullURL: string;
111
- }): Promise<{
112
- [key: string]: any;
113
- }>;
114
- getAsyncMethod(methodName: string, pathname: string, args?: {
115
- [key: string | number]: any;
116
- }): Promise<{
117
- [key: string]: any;
118
- }>;
52
+ nodemailerLoader(config: any): nodemailer.Transporter<import("nodemailer/lib/smtp-transport").SentMessageInfo, import("nodemailer/lib/smtp-transport").Options>;
119
53
  }
120
- export declare class BaseApiClient extends AxiosClient implements IAuth {
121
- constructor({ clientName, baseURL, version }: {
54
+ export declare class SoapClient extends Service {
55
+ constructor(config: {
122
56
  clientName: string;
123
57
  baseURL: string;
124
- version: string;
58
+ version?: string;
59
+ timeout?: number;
125
60
  });
126
- protected axiosLoaderAuthMiddleware(): AxiosInstance;
127
- authentication: () => Promise<import("axios").AxiosResponse<any, any, {}>>;
61
+ call(methodName: string, args: any): Promise<any>;
128
62
  }
129
- export default Service;
@@ -1,344 +1,125 @@
1
- import path from 'path';
2
- import axios from 'axios';
3
- import soap from 'soap';
4
- // => special
1
+ import { createHash } from 'node:crypto';
2
+ import path from 'node:path';
5
3
  import nodemailer from 'nodemailer';
6
4
  import hbs from 'nodemailer-express-handlebars';
7
- //
8
- import { LoggerService } from '../../../loader/index';
9
- import { x, LoggerLayerEnum, TokensEnum } from '../../index';
10
- // => for cryptography
11
- import crypto from 'crypto';
12
- class Service {
5
+ import soap from 'soap';
6
+ import { ConfigsService, LoggerService } from 'source/loader';
7
+ import { TokensEnum, x } from '..';
8
+ export class Service {
9
+ configService = x.get(ConfigsService);
13
10
  logger = x.get(LoggerService);
14
- //private _instance: Record<string, any> = {}
15
11
  clientName;
16
12
  baseURL;
17
13
  version = null;
18
- headers; /* unknow */
19
- timeout = 10000;
20
- /***************
21
- * CONSTRUCTOR *
22
- ***************/
23
- constructor({ clientName, baseURL, version, timeout, headers, }) {
14
+ timeout = 15000;
15
+ constructor({ clientName, baseURL, version, timeout }) {
24
16
  this.clientName = clientName;
25
17
  this.baseURL = baseURL;
26
- version && this.version;
27
- if (timeout) {
18
+ this.version = version || null;
19
+ if (timeout)
28
20
  this.timeout = timeout;
29
- }
30
- if (headers) {
31
- this.headers = {
32
- ...headers
33
- };
34
- }
35
- }
36
- /***********
37
- * HELPERS *
38
- ***********/
39
- interceptorErrorComplement(error /* unknow */) {
40
- if (error.response) {
41
- this.logger.winston.info({
42
- level: LoggerLayerEnum[LoggerLayerEnum.ERROR].toLowerCase(),
43
- message: `${this.clientName} api service error: ${JSON.stringify(error.response)}`,
44
- });
45
- }
46
- else {
47
- this.logger.winston.info({
48
- level: LoggerLayerEnum[LoggerLayerEnum.CRITICAL].toLowerCase(),
49
- message: `${this.clientName} api service error: ${JSON.stringify(error.message)}`,
50
- });
51
- }
52
- }
53
- routeSlashChecker(route) {
54
- const splash = route.split('/');
55
- let withSplash;
56
- if (splash[0] === '') {
57
- withSplash = route.substring(1);
58
- }
59
- else {
60
- withSplash = route;
61
- }
62
- return withSplash;
63
21
  }
64
- static cryptoHashGenerate = ({ algorithm, input, digest = 'string' }) => {
65
- return crypto.createHash(algorithm).update(input).digest(digest);
66
- };
67
- static cryptoHashDecrypt = ({ algorithm, input, keyEncoding = 'hex', key, initializationVector, inputEncoding = 'base64', outputEncoding = 'utf8', }) => {
68
- const decipher = crypto.createDecipheriv(algorithm, Buffer.from(key, keyEncoding), Buffer.from(initializationVector, inputEncoding));
69
- let decrypted = decipher.update(input, inputEncoding, outputEncoding);
70
- decrypted += decipher.final(outputEncoding);
71
- return decrypted;
72
- };
73
- static objectToFormData = (object) => {
74
- const formData = new FormData();
75
- for (const [key, value] of Object.entries(object)) {
76
- let changedValue = null;
77
- changedValue = value;
78
- if (Array.isArray(value)) {
79
- changedValue = JSON.stringify(value);
80
- }
81
- formData.append(key, changedValue);
82
- }
83
- return formData;
22
+ static cryptoHashGenerate = ({ algorithm, input, digest = 'hex' }) => {
23
+ return createHash(algorithm).update(input).digest(digest);
84
24
  };
85
- static generateRandomNumber = ({ prefix, suffix, hyphen = true, length = 10, totalLength = null }) => {
86
- if (!Number.isInteger(length) || length <= 0) {
87
- throw new Error(`Invalid length.`);
88
- }
89
- if (totalLength) {
90
- const prefixLength = prefix ? Number(prefix?.length) : null;
91
- const suffixLength = suffix ? Number(suffix?.length) : null;
92
- if (prefixLength && !Number.isInteger(prefixLength) || length <= 0 ||
93
- suffixLength && !Number.isInteger(suffixLength) || length <= 0) {
94
- throw new Error(`Invalid type.`);
95
- }
96
- if (prefixLength) {
97
- totalLength -= prefixLength + 1;
98
- }
99
- if (suffixLength) {
100
- totalLength -= suffixLength + 1;
101
- }
102
- length = totalLength;
103
- }
104
- let randomNumber = '';
25
+ static generateRandomNumber = ({ length = 10 }) => {
26
+ let result = '';
105
27
  for (let i = 0; i < length; i++) {
106
- const randomDigit = Math.floor(Math.random() * 10);
107
- randomNumber += randomDigit.toString();
28
+ result += Math.floor(Math.random() * 10).toString();
108
29
  }
109
- return `${prefix && hyphen ? prefix + '-' : ''}${randomNumber}${suffix && hyphen ? '-' + suffix : ''}`;
30
+ return result;
110
31
  };
111
32
  }
112
- export class ServiceStore {
113
- static _instance = null;
114
- _store = {};
115
- constructor() { }
116
- static create() {
117
- if (!ServiceStore._instance) {
118
- ServiceStore._instance = new ServiceStore();
33
+ export class BaseApiClient extends Service {
34
+ constructor(config) {
35
+ super(config);
36
+ }
37
+ async request(path, options = {}) {
38
+ const base = this.baseURL.replace(/\/$/, '');
39
+ const ver = this.version ? `/${this.version.replace(/^\//, '')}` : '';
40
+ const url = `${base}${ver}${path}`;
41
+ const store = LoggerService.storage.getStore();
42
+ const correlationId = store?.get('correlationId');
43
+ const headers = new Headers(options.headers || {});
44
+ if (!headers.has('Content-Type'))
45
+ headers.set('Content-Type', 'application/json');
46
+ if (correlationId)
47
+ headers.set('x-correlation-id', correlationId);
48
+ if (process.env.INTERNAL_SECRET)
49
+ headers.set('X-Internal-Secret', process.env.INTERNAL_SECRET);
50
+ const controller = new AbortController();
51
+ const timeoutId = setTimeout(() => controller.abort(), this.timeout);
52
+ try {
53
+ const response = await fetch(url, { ...options, headers, signal: controller.signal });
54
+ clearTimeout(timeoutId);
55
+ return response;
56
+ }
57
+ catch (error) {
58
+ this.logger.winston.error(`${this.clientName} HTTP Request Failure: ${error.message}`, { url });
59
+ throw error;
119
60
  }
120
- return ServiceStore._instance;
121
- }
122
- set setStore(callback) {
123
- const returnCallback = callback(this._store);
124
- this._store = {
125
- ...this._store,
126
- ...returnCallback
127
- };
128
- }
129
- get instance() {
130
- return ServiceStore._instance;
131
61
  }
132
- get store() {
133
- return this._store;
62
+ }
63
+ export class AuthenticatedApiClient extends BaseApiClient {
64
+ accessToken;
65
+ constructor(config) {
66
+ super(config);
67
+ }
68
+ async request(path, options = {}) {
69
+ const injectToken = (h, t) => h.set('Cookie', `${TokensEnum.ACCESS_TOKEN}:${t}`);
70
+ const headers = new Headers(options.headers || {});
71
+ if (this.accessToken)
72
+ injectToken(headers, this.accessToken);
73
+ options.headers = headers;
74
+ let response = await super.request(path, options);
75
+ if (response.status === 401) {
76
+ await this.authentication();
77
+ if (this.accessToken) {
78
+ const retryHeaders = new Headers(options.headers);
79
+ injectToken(retryHeaders, this.accessToken);
80
+ return super.request(path, { ...options, headers: retryHeaders });
81
+ }
82
+ }
83
+ return response;
134
84
  }
135
85
  }
136
86
  export class EmailClient extends Service {
137
- _port = null;
138
- _username = null;
139
- _password = null;
140
- constructor({ clientName, baseURL, version, port, username, password, }) {
141
- super({ clientName, baseURL, version });
142
- this._username = username;
143
- this._password = password;
87
+ constructor(config) {
88
+ super(config);
144
89
  }
145
- /***********
146
- * LOADERS *
147
- ***********/
148
- nodemailerLoader({ host, port, username, password, secure = true, }) {
90
+ nodemailerLoader(config) {
149
91
  const transporter = nodemailer.createTransport({
150
- //@ts-ignore
151
- host: host ? host : this.baseURL,
152
- port: port ? port : this._port,
153
- secure,
154
- auth: {
155
- user: username ? username : this._username,
156
- pass: password ? password : this._password,
157
- },
92
+ host: config.host || this.baseURL,
93
+ port: config.port,
94
+ secure: config.secure ?? true,
95
+ auth: { user: config.username, pass: config.password }
158
96
  });
97
+ const staticPath = this.configService.all.systemStaticFolderPath || 'source/statics';
159
98
  transporter.use('compile', hbs({
160
99
  viewEngine: {
161
100
  extname: '.hbs',
162
- layoutsDir: path.resolve('source', 'static', 'email'),
163
- defaultLayout: 'index',
164
- partialsDir: path.resolve('source', 'static', 'email'),
101
+ layoutsDir: path.resolve(staticPath, 'email'),
102
+ defaultLayout: 'index'
165
103
  },
166
- viewPath: path.resolve('source', 'static', 'email', 'templates'),
104
+ viewPath: path.resolve(staticPath, 'email', 'templates'),
167
105
  extName: '.hbs'
168
106
  }));
169
107
  return transporter;
170
108
  }
171
109
  }
172
- export class AxiosClient extends Service {
173
- constructor({ clientName, baseURL, version }) {
174
- super({ clientName, baseURL, version });
175
- }
176
- /***********
177
- * LOADERS *
178
- ***********/
179
- axiosLoader() {
180
- const axiosInstance = axios.create({
181
- baseURL: this.baseURL,
182
- timeout: this.timeout,
183
- headers: {
184
- ...this.headers
185
- },
186
- });
187
- axiosInstance.interceptors.request.use((config /* unknow */) => {
188
- return config;
189
- }, (error) => {
190
- this.logger.winston.info({
191
- level: LoggerLayerEnum[LoggerLayerEnum.CRITICAL].toLowerCase(),
192
- message: `${this.clientName} api service error: ${JSON.stringify(error)}`,
193
- });
194
- return Promise.reject(error);
195
- });
196
- return axiosInstance;
197
- }
198
- }
199
110
  export class SoapClient extends Service {
200
- client;
201
- constructor({ clientName, baseURL, version }) {
202
- super({ clientName, baseURL, version });
203
- }
204
- async getAsyncBaseClient() {
205
- try {
206
- this.client = await soap.createClientAsync(this.baseURL);
207
- return this.client;
208
- }
209
- catch (exception) {
210
- this.logger.winston.error({
211
- level: LoggerLayerEnum[LoggerLayerEnum.ERROR].toLowerCase(),
212
- message: `${this.clientName} - soap client error: ${exception}`,
213
- });
214
- return null;
215
- }
111
+ constructor(config) {
112
+ super(config);
216
113
  }
217
- async createAsyncClient({ fullURL }) {
114
+ async call(methodName, args) {
218
115
  try {
219
- this.client = await soap.createClientAsync(fullURL);
220
- //console.log(this.client)
221
- return this.client;
222
- }
223
- catch (exception) {
224
- this.logger.winston.error({
225
- level: LoggerLayerEnum[LoggerLayerEnum.ERROR].toLowerCase(),
226
- message: `${this.clientName} - soap client error: ${exception}`,
227
- });
228
- return null;
229
- }
230
- }
231
- async getAsyncMethod(methodName, pathname, args) {
232
- let client = null;
233
- let result = null;
234
- if (pathname) {
235
- client = await this.createAsyncClient({ fullURL: `${this.baseURL}${pathname}` });
236
- }
237
- else {
238
- client = await this.getAsyncBaseClient();
239
- }
240
- //console.log('client: ', client)
241
- if (client) {
242
- try {
243
- let data = await client[`${methodName}Async`](args);
244
- result = data[0];
245
- }
246
- catch (exception) {
247
- this.logger.winston.error({
248
- level: LoggerLayerEnum[LoggerLayerEnum.ERROR].toLowerCase(),
249
- message: `${this.clientName} - soap client method error: ${exception}`,
250
- });
251
- return null;
252
- }
116
+ const client = await soap.createClientAsync(this.baseURL);
117
+ const result = await client[`${methodName}Async`](args);
118
+ return result[0];
253
119
  }
254
- else {
120
+ catch (error) {
121
+ this.logger.winston.error(`${this.clientName} SOAP Error: ${error.message}`);
255
122
  return null;
256
123
  }
257
- return result;
258
- }
259
- }
260
- export class BaseApiClient extends AxiosClient {
261
- constructor({ clientName, baseURL, version }) {
262
- super({
263
- clientName,
264
- baseURL,
265
- version
266
- });
267
- }
268
- axiosLoaderAuthMiddleware() {
269
- const axiosInstance = this.axiosLoader();
270
- let _retry = false;
271
- axiosInstance.interceptors.request.use((config) => {
272
- const accessToken = (ServiceStore.create()).store?.[this.clientName]?.accessToken;
273
- if (accessToken) {
274
- config.headers['Cookie'] = `${TokensEnum.ACCESS_TOKEN}:${accessToken}`;
275
- }
276
- return config;
277
- }, (error) => {
278
- return Promise.reject(error);
279
- });
280
- axiosInstance.interceptors.response.use(async (response) => {
281
- const originalRequest = response.config;
282
- if (!_retry && response.data?.success === false && response.data?.status_code === 101) {
283
- this.logger.winston.info({
284
- level: LoggerLayerEnum[LoggerLayerEnum.INFO].toLowerCase(),
285
- message: `${this.clientName} client - token refreshed!`,
286
- });
287
- try {
288
- await this.authentication();
289
- _retry = true;
290
- originalRequest.headers['Cookie'] = `${TokensEnum.ACCESS_TOKEN}:${(ServiceStore.create()).store?.[this.clientName]?.accessToken}`;
291
- //console.log(originalConfig)
292
- return axiosInstance(originalRequest);
293
- }
294
- catch (error) {
295
- this.logger.winston.info({
296
- level: LoggerLayerEnum[LoggerLayerEnum.INFO].toLowerCase(),
297
- message: `${this.clientName} client - token refresh request not initial!`,
298
- });
299
- return Promise.reject(error);
300
- }
301
- }
302
- return response;
303
- }, async (error) => {
304
- const originalConfig = error.config;
305
- if (error.response.status === 401 && !originalConfig._retry) {
306
- this.logger.winston.info({
307
- level: LoggerLayerEnum[LoggerLayerEnum.INFO].toLowerCase(),
308
- message: `${this.clientName} client - token refreshed!`,
309
- });
310
- originalConfig._retry = true;
311
- try {
312
- await this.authentication();
313
- const accessToken = (ServiceStore.create()).store?.[this.clientName]?.accessToken;
314
- originalConfig.headers['Cookie'] = `${TokensEnum.ACCESS_TOKEN}:${accessToken}`;
315
- //console.log(originalConfig)
316
- return axiosInstance(originalConfig);
317
- }
318
- catch (error) {
319
- this.logger.winston.info({
320
- level: LoggerLayerEnum[LoggerLayerEnum.INFO].toLowerCase(),
321
- message: `${this.clientName} client - token refresh request not initial!`,
322
- });
323
- return Promise.reject(error);
324
- }
325
- }
326
- return Promise.reject(error);
327
- });
328
- return axiosInstance;
329
124
  }
330
- authentication = async () => {
331
- const response = await this.axiosLoader().post(`/${this.version}/auth/sign-in`, {});
332
- if (response.data.success !== true) {
333
- throw new Error('Authorization not implemented');
334
- }
335
- const servicesStore = ServiceStore.create();
336
- servicesStore.setStore = ((prevState => ({
337
- [this.clientName]: {
338
- accessToken: response.data?.payload?.data?.token
339
- }
340
- })));
341
- return response;
342
- };
343
125
  }
344
- export default Service;