@emilgroup/insurance-sdk-node 1.0.0 → 1.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.
package/README.md CHANGED
@@ -1,11 +1,6 @@
1
- ## @emilgroup/insurance-sdk-node@1.0.0
1
+ # Emil Insurance SDK for Nodejs
2
2
 
3
- This TypeScript/JavaScript client utilizes [axios](https://github.com/axios/axios). The generated Node module can be used in the following environments:
4
-
5
- Environment
6
- * Node.js
7
- * Webpack
8
- * Browserify
3
+ This TypeScript/JavaScript client utilizes [axios](https://github.com/axios/axios). The generated Node module can be used with Nodejs based applications.
9
4
 
10
5
  Language level
11
6
  * ES5 - you must have a Promises/A+ library installed
@@ -15,15 +10,20 @@ Module system
15
10
  * CommonJS
16
11
  * ES6 module system
17
12
 
18
- It can be used in both TypeScript and JavaScript. In TypeScript, the definition should be automatically resolved via `package.json`. ([Reference](http://www.typescriptlang.org/docs/handbook/typings-for-npm-packages.html))
13
+ Although this package can be used in both TypeScript and JavaScript, it is intended to be used with TypeScript. The definition should be automatically resolved via `package.json`. ([Reference](http://www.typescriptlang.org/docs/handbook/typings-for-npm-packages.html))
19
14
 
20
- ### Consuming
15
+ ## Consuming
21
16
 
22
- navigate to the folder of your consuming project and run one of the following commands.
17
+ Navigate to the folder of your consuming project and run one of the following commands:
23
18
 
24
19
  ```
25
- npm install @emilgroup/insurance-sdk-node@1.0.0 --save
20
+ npm install @emilgroup/insurance-sdk-node@1.1.0 --save
21
+ ```
22
+ or
23
+ ```
24
+ yarn add @emilgroup/insurance-sdk-node@1.1.0
26
25
  ```
26
+
27
27
  And then you can import `PoliciesApi`.
28
28
 
29
29
  ```ts
@@ -31,15 +31,32 @@ import { PoliciesApi } from '@emilgroup/insurance-sdk-node'
31
31
 
32
32
  const policiesApi = new PoliciesApi();
33
33
  ```
34
+ ## Credentials
35
+
36
+ To use authentication protected endpoints, you have to first authorize. To do so, the easiest way is to provide a configuration file under `~/.emil/credentials` with the following content:
37
+
38
+ ```shell
39
+ emil_username=XXXXX@XXXX.XXX
40
+ emil_password=XXXXXXXXXXXXXX
41
+ ```
42
+
43
+ It is also possible to provide environment variables instead:
44
+
45
+ ```shell
46
+ export EMIL_USERNAME=XXXXX@XXXX.XXX
47
+ export EMIL_PASSWORD=XXXXXXXXXXXXXX
48
+ ```
49
+
50
+ ## Example
34
51
 
35
- To use authentication protected endpoints, you have to first authorize. To do so, use the `authorize` function in `PoliciesApi`:
52
+ Here is a basic functionning example:
36
53
 
37
54
  ```ts
38
55
  async function listPolicies(): Promise<Void> {
39
56
  try {
40
57
  const policiesApi = new PoliciesApi();
41
58
 
42
- await policiesApi.authorize('username', 'password');
59
+ await policiesApi.initialize(); // should be called only once per Api.
43
60
 
44
61
  const { data: { items } } = await policiesApi.listPolicies();
45
62
 
package/base.ts CHANGED
@@ -17,9 +17,17 @@ import { Configuration } from "./configuration";
17
17
  // Some imports not used depending on template conditions
18
18
  // @ts-ignore
19
19
  import globalAxios, { AxiosPromise, AxiosInstance, AxiosRequestConfig, AxiosResponse } from 'axios';
20
+ import * as fs from 'fs';
21
+ import * as path from 'path';
22
+ import * as os from 'os';
20
23
 
21
24
  export const BASE_PATH = "http://localhost".replace(/\/+$/, "");
25
+ const CONFIG_DIRECTORY = '.emil';
26
+ const CONFIG_FILENAME = 'credentials';
27
+ const KEY_USERNAME = 'emil_username';
28
+ const KEY_PASSWORD = 'emil_password';
22
29
 
30
+ const filePath = os.homedir() + path.sep + CONFIG_DIRECTORY + path.sep + CONFIG_FILENAME;
23
31
  /**
24
32
  *
25
33
  * @export
@@ -59,6 +67,8 @@ export interface RequestArgs {
59
67
  */
60
68
  export class BaseAPI {
61
69
  protected configuration: Configuration;
70
+ private username?: string;
71
+ private password?: string;
62
72
 
63
73
  constructor(configuration?: Configuration, protected basePath: string = BASE_PATH, protected axios: AxiosInstance = globalAxios) {
64
74
  if (configuration) {
@@ -70,51 +80,61 @@ export class BaseAPI {
70
80
  });
71
81
  }
72
82
 
73
- axios.interceptors.response.use(
74
- (res) => {
75
- return res;
76
- },
77
- async (err) => {
78
- const originalConfig = err.config;
79
- if (err.response) {
80
- // Access Token was expired
81
- if (err.response.status === 401 && !originalConfig._retry) {
82
- originalConfig._retry = true;
83
- try {
84
- const tokenString = await this.refreshToken();
85
- const accessToken = `Bearer ${tokenString}`;
83
+ this.attachInterceptor(axios);
84
+ }
86
85
 
87
- const localVarHeaderParameter = {} as any;
88
- localVarHeaderParameter['Authorization'] = accessToken;
86
+ async initialize(env: Environment = Environment.Production) {
87
+ this.configuration.basePath = env;
89
88
 
90
- originalConfig.headers = {
91
- ...originalConfig.headers,
92
- ...localVarHeaderParameter,
93
- };
89
+ await this.loadCredentials();
94
90
 
95
- this.configuration.accessToken = accessToken;
91
+ if (this.username) {
92
+ await this.authorize(this.username, this.password);
93
+ this.password = null; // to avoid keeping password loaded in memory.
94
+ }
95
+ }
96
96
 
97
- return axios(originalConfig);
98
- } catch (_error) {
99
- if (_error.response && _error.response.data) {
100
- return Promise.reject(_error.response.data);
101
- }
102
- return Promise.reject(_error);
103
- }
104
- }
105
- if (err.response.status === 403 && err.response.data) {
106
- return Promise.reject(err.response.data);
107
- }
108
- }
109
- return Promise.reject(err);
110
- }
111
- );
97
+ private async loadCredentials() {
98
+ try {
99
+ await this.readConfigFile();
100
+ } catch (error) {
101
+ console.warn(`No credentials file found. Check that ${filePath} exists.`);
102
+ }
103
+
104
+ this.readEnvVariables();
105
+
106
+ if (!this.username) {
107
+ console.info(`No credentials found in credentials file or environment variables. Either provide some or use
108
+ authorize() function.`);
109
+ }
112
110
  }
113
111
 
114
- getConfiguration(): Configuration {
115
- return this.configuration;
112
+ private async readConfigFile() {
113
+ const file = await fs.promises.readFile(filePath, 'utf-8');
114
+
115
+ const lines = file.split(os.EOL)
116
+ .filter(Boolean);
117
+
118
+ lines.forEach((line: string) => {
119
+ if (line.startsWith(KEY_USERNAME)) {
120
+ this.username = line.length > KEY_USERNAME.length + 1 ? line.substring(KEY_USERNAME.length + 1) : '';
121
+ } else if (line.startsWith(KEY_PASSWORD)) {
122
+ this.password = line.length > KEY_PASSWORD.length + 1 ? line.substring(KEY_PASSWORD.length + 1) : '';
123
+ }
124
+ });
116
125
  }
117
126
 
127
+ private readEnvVariables(): boolean {
128
+ if (process.env.EMIL_USERNAME) {
129
+ this.username = process.env.EMIL_USERNAME;
130
+ this.password = process.env.EMIL_PASSWORD || '';
131
+
132
+ return true;
133
+ }
134
+
135
+ return false;
136
+ }
137
+
118
138
  selectEnvironment(env: Environment) {
119
139
  this.configuration.basePath = env;
120
140
  }
@@ -123,16 +143,16 @@ export class BaseAPI {
123
143
  const options: AxiosRequestConfig = {
124
144
  method: 'POST',
125
145
  url: `${this.configuration.basePath}/authservice/v1/login`,
126
- headers: {'Content-Type': 'application/json'},
146
+ headers: { 'Content-Type': 'application/json' },
127
147
  data: {
128
- username,
148
+ username,
129
149
  password,
130
150
  },
131
151
  withCredentials: true,
132
152
  };
133
153
 
134
154
  const response = await globalAxios.request<LoginClass>(options);
135
-
155
+
136
156
  const { data: { accessToken } } = response;
137
157
  const refreshToken = this.extractRefreshToken(response)
138
158
 
@@ -152,10 +172,10 @@ export class BaseAPI {
152
172
  method: 'POST',
153
173
  url: `${this.configuration.basePath}/authservice/v1/refresh-token`,
154
174
  headers: {
155
- 'Content-Type': 'application/json',
175
+ 'Content-Type': 'application/json',
156
176
  Cookie: refreshToken,
157
177
  },
158
- data: {username: username},
178
+ data: { username: username },
159
179
  withCredentials: true,
160
180
  };
161
181
 
@@ -165,14 +185,60 @@ export class BaseAPI {
165
185
  }
166
186
 
167
187
  private extractRefreshToken(response: AxiosResponse): string {
168
- if (response.headers && response.headers['set-cookie']
169
- && response.headers['set-cookie'].length > 0) {
188
+ if (response.headers && response.headers['set-cookie']
189
+ && response.headers['set-cookie'].length > 0) {
170
190
 
171
191
  return `${response.headers['set-cookie'][0].split(';')[0]};`;
172
192
  }
173
193
 
174
194
  return '';
175
195
  }
196
+
197
+ getConfiguration(): Configuration {
198
+ return this.configuration;
199
+ }
200
+
201
+ private attachInterceptor(axios: AxiosInstance) {
202
+ axios.interceptors.response.use(
203
+ (res) => {
204
+ return res;
205
+ },
206
+ async (err) => {
207
+ const originalConfig = err.config;
208
+ if (err.response) {
209
+ // Access Token was expired
210
+ if (err.response.status === 401 && !originalConfig._retry) {
211
+ originalConfig._retry = true;
212
+ try {
213
+ const tokenString = await this.refreshToken();
214
+ const accessToken = `Bearer ${tokenString}`;
215
+
216
+ const localVarHeaderParameter = {} as any;
217
+ localVarHeaderParameter['Authorization'] = accessToken;
218
+
219
+ originalConfig.headers = {
220
+ ...originalConfig.headers,
221
+ ...localVarHeaderParameter,
222
+ };
223
+
224
+ this.configuration.accessToken = accessToken;
225
+
226
+ return axios(originalConfig);
227
+ } catch (_error) {
228
+ if (_error.response && _error.response.data) {
229
+ return Promise.reject(_error.response.data);
230
+ }
231
+ return Promise.reject(_error);
232
+ }
233
+ }
234
+ if (err.response.status === 403 && err.response.data) {
235
+ return Promise.reject(err.response.data);
236
+ }
237
+ }
238
+ return Promise.reject(err);
239
+ }
240
+ );
241
+ }
176
242
  };
177
243
 
178
244
  /**
package/dist/base.d.ts CHANGED
@@ -49,12 +49,19 @@ export declare class BaseAPI {
49
49
  protected basePath: string;
50
50
  protected axios: AxiosInstance;
51
51
  protected configuration: Configuration;
52
+ private username?;
53
+ private password?;
52
54
  constructor(configuration?: Configuration, basePath?: string, axios?: AxiosInstance);
53
- getConfiguration(): Configuration;
55
+ initialize(env?: Environment): Promise<void>;
56
+ private loadCredentials;
57
+ private readConfigFile;
58
+ private readEnvVariables;
54
59
  selectEnvironment(env: Environment): void;
55
60
  authorize(username: string, password: string): Promise<void>;
56
61
  refreshToken(): Promise<string>;
57
62
  private extractRefreshToken;
63
+ getConfiguration(): Configuration;
64
+ private attachInterceptor;
58
65
  }
59
66
  /**
60
67
  *
package/dist/base.js CHANGED
@@ -38,6 +38,29 @@ var __assign = (this && this.__assign) || function () {
38
38
  };
39
39
  return __assign.apply(this, arguments);
40
40
  };
41
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
42
+ if (k2 === undefined) k2 = k;
43
+ var desc = Object.getOwnPropertyDescriptor(m, k);
44
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
45
+ desc = { enumerable: true, get: function() { return m[k]; } };
46
+ }
47
+ Object.defineProperty(o, k2, desc);
48
+ }) : (function(o, m, k, k2) {
49
+ if (k2 === undefined) k2 = k;
50
+ o[k2] = m[k];
51
+ }));
52
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
53
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
54
+ }) : function(o, v) {
55
+ o["default"] = v;
56
+ });
57
+ var __importStar = (this && this.__importStar) || function (mod) {
58
+ if (mod && mod.__esModule) return mod;
59
+ var result = {};
60
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
61
+ __setModuleDefault(result, mod);
62
+ return result;
63
+ };
41
64
  var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
42
65
  function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
43
66
  return new (P || (P = Promise))(function (resolve, reject) {
@@ -83,7 +106,15 @@ var configuration_1 = require("./configuration");
83
106
  // Some imports not used depending on template conditions
84
107
  // @ts-ignore
85
108
  var axios_1 = __importDefault(require("axios"));
109
+ var fs = __importStar(require("fs"));
110
+ var path = __importStar(require("path"));
111
+ var os = __importStar(require("os"));
86
112
  exports.BASE_PATH = "http://localhost".replace(/\/+$/, "");
113
+ var CONFIG_DIRECTORY = '.emil';
114
+ var CONFIG_FILENAME = 'credentials';
115
+ var KEY_USERNAME = 'emil_username';
116
+ var KEY_PASSWORD = 'emil_password';
117
+ var filePath = os.homedir() + path.sep + CONFIG_DIRECTORY + path.sep + CONFIG_FILENAME;
87
118
  /**
88
119
  *
89
120
  * @export
@@ -108,7 +139,6 @@ var BaseAPI = /** @class */ (function () {
108
139
  function BaseAPI(configuration, basePath, axios) {
109
140
  if (basePath === void 0) { basePath = exports.BASE_PATH; }
110
141
  if (axios === void 0) { axios = axios_1.default; }
111
- var _this = this;
112
142
  this.basePath = basePath;
113
143
  this.axios = axios;
114
144
  if (configuration) {
@@ -120,47 +150,85 @@ var BaseAPI = /** @class */ (function () {
120
150
  basePath: this.basePath,
121
151
  });
122
152
  }
123
- axios.interceptors.response.use(function (res) {
124
- return res;
125
- }, function (err) { return __awaiter(_this, void 0, void 0, function () {
126
- var originalConfig, tokenString, accessToken, localVarHeaderParameter, _error_1;
153
+ this.attachInterceptor(axios);
154
+ }
155
+ BaseAPI.prototype.initialize = function (env) {
156
+ if (env === void 0) { env = Environment.Production; }
157
+ return __awaiter(this, void 0, void 0, function () {
127
158
  return __generator(this, function (_a) {
128
159
  switch (_a.label) {
129
160
  case 0:
130
- originalConfig = err.config;
131
- if (!err.response) return [3 /*break*/, 5];
132
- if (!(err.response.status === 401 && !originalConfig._retry)) return [3 /*break*/, 4];
133
- originalConfig._retry = true;
134
- _a.label = 1;
161
+ this.configuration.basePath = env;
162
+ return [4 /*yield*/, this.loadCredentials()];
135
163
  case 1:
136
- _a.trys.push([1, 3, , 4]);
137
- return [4 /*yield*/, this.refreshToken()];
164
+ _a.sent();
165
+ if (!this.username) return [3 /*break*/, 3];
166
+ return [4 /*yield*/, this.authorize(this.username, this.password)];
138
167
  case 2:
139
- tokenString = _a.sent();
140
- accessToken = "Bearer ".concat(tokenString);
141
- localVarHeaderParameter = {};
142
- localVarHeaderParameter['Authorization'] = accessToken;
143
- originalConfig.headers = __assign(__assign({}, originalConfig.headers), localVarHeaderParameter);
144
- this.configuration.accessToken = accessToken;
145
- return [2 /*return*/, axios(originalConfig)];
168
+ _a.sent();
169
+ this.password = null; // to avoid keeping password loaded in memory.
170
+ _a.label = 3;
171
+ case 3: return [2 /*return*/];
172
+ }
173
+ });
174
+ });
175
+ };
176
+ BaseAPI.prototype.loadCredentials = function () {
177
+ return __awaiter(this, void 0, void 0, function () {
178
+ var error_1;
179
+ return __generator(this, function (_a) {
180
+ switch (_a.label) {
181
+ case 0:
182
+ _a.trys.push([0, 2, , 3]);
183
+ return [4 /*yield*/, this.readConfigFile()];
184
+ case 1:
185
+ _a.sent();
186
+ return [3 /*break*/, 3];
187
+ case 2:
188
+ error_1 = _a.sent();
189
+ console.warn("No credentials file found. Check that ".concat(filePath, " exists."));
190
+ return [3 /*break*/, 3];
146
191
  case 3:
147
- _error_1 = _a.sent();
148
- if (_error_1.response && _error_1.response.data) {
149
- return [2 /*return*/, Promise.reject(_error_1.response.data)];
150
- }
151
- return [2 /*return*/, Promise.reject(_error_1)];
152
- case 4:
153
- if (err.response.status === 403 && err.response.data) {
154
- return [2 /*return*/, Promise.reject(err.response.data)];
192
+ this.readEnvVariables();
193
+ if (!this.username) {
194
+ console.info("No credentials found in credentials file or environment variables. Either provide some or use \n authorize() function.");
155
195
  }
156
- _a.label = 5;
157
- case 5: return [2 /*return*/, Promise.reject(err)];
196
+ return [2 /*return*/];
158
197
  }
159
198
  });
160
- }); });
161
- }
162
- BaseAPI.prototype.getConfiguration = function () {
163
- return this.configuration;
199
+ });
200
+ };
201
+ BaseAPI.prototype.readConfigFile = function () {
202
+ return __awaiter(this, void 0, void 0, function () {
203
+ var file, lines;
204
+ var _this = this;
205
+ return __generator(this, function (_a) {
206
+ switch (_a.label) {
207
+ case 0: return [4 /*yield*/, fs.promises.readFile(filePath, 'utf-8')];
208
+ case 1:
209
+ file = _a.sent();
210
+ lines = file.split(os.EOL)
211
+ .filter(Boolean);
212
+ lines.forEach(function (line) {
213
+ if (line.startsWith(KEY_USERNAME)) {
214
+ _this.username = line.length > KEY_USERNAME.length + 1 ? line.substring(KEY_USERNAME.length + 1) : '';
215
+ }
216
+ else if (line.startsWith(KEY_PASSWORD)) {
217
+ _this.password = line.length > KEY_PASSWORD.length + 1 ? line.substring(KEY_PASSWORD.length + 1) : '';
218
+ }
219
+ });
220
+ return [2 /*return*/];
221
+ }
222
+ });
223
+ });
224
+ };
225
+ BaseAPI.prototype.readEnvVariables = function () {
226
+ if (process.env.EMIL_USERNAME) {
227
+ this.username = process.env.EMIL_USERNAME;
228
+ this.password = process.env.EMIL_PASSWORD || '';
229
+ return true;
230
+ }
231
+ return false;
164
232
  };
165
233
  BaseAPI.prototype.selectEnvironment = function (env) {
166
234
  this.configuration.basePath = env;
@@ -229,6 +297,50 @@ var BaseAPI = /** @class */ (function () {
229
297
  }
230
298
  return '';
231
299
  };
300
+ BaseAPI.prototype.getConfiguration = function () {
301
+ return this.configuration;
302
+ };
303
+ BaseAPI.prototype.attachInterceptor = function (axios) {
304
+ var _this = this;
305
+ axios.interceptors.response.use(function (res) {
306
+ return res;
307
+ }, function (err) { return __awaiter(_this, void 0, void 0, function () {
308
+ var originalConfig, tokenString, accessToken, localVarHeaderParameter, _error_1;
309
+ return __generator(this, function (_a) {
310
+ switch (_a.label) {
311
+ case 0:
312
+ originalConfig = err.config;
313
+ if (!err.response) return [3 /*break*/, 5];
314
+ if (!(err.response.status === 401 && !originalConfig._retry)) return [3 /*break*/, 4];
315
+ originalConfig._retry = true;
316
+ _a.label = 1;
317
+ case 1:
318
+ _a.trys.push([1, 3, , 4]);
319
+ return [4 /*yield*/, this.refreshToken()];
320
+ case 2:
321
+ tokenString = _a.sent();
322
+ accessToken = "Bearer ".concat(tokenString);
323
+ localVarHeaderParameter = {};
324
+ localVarHeaderParameter['Authorization'] = accessToken;
325
+ originalConfig.headers = __assign(__assign({}, originalConfig.headers), localVarHeaderParameter);
326
+ this.configuration.accessToken = accessToken;
327
+ return [2 /*return*/, axios(originalConfig)];
328
+ case 3:
329
+ _error_1 = _a.sent();
330
+ if (_error_1.response && _error_1.response.data) {
331
+ return [2 /*return*/, Promise.reject(_error_1.response.data)];
332
+ }
333
+ return [2 /*return*/, Promise.reject(_error_1)];
334
+ case 4:
335
+ if (err.response.status === 403 && err.response.data) {
336
+ return [2 /*return*/, Promise.reject(err.response.data)];
337
+ }
338
+ _a.label = 5;
339
+ case 5: return [2 /*return*/, Promise.reject(err)];
340
+ }
341
+ });
342
+ }); });
343
+ };
232
344
  return BaseAPI;
233
345
  }());
234
346
  exports.BaseAPI = BaseAPI;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@emilgroup/insurance-sdk-node",
3
- "version": "1.0.0",
3
+ "version": "1.1.0",
4
4
  "description": "OpenAPI client for @emilgroup/insurance-sdk-node",
5
5
  "author": "OpenAPI-Generator Contributors",
6
6
  "keywords": [