@emilgroup/document-sdk-node 1.0.0 → 1.2.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.
@@ -1,5 +1,6 @@
1
1
  .gitignore
2
2
  .npmignore
3
+ .openapi-generator-ignore
3
4
  README.md
4
5
  api.ts
5
6
  api/document-templates-api.ts
package/README.md CHANGED
@@ -17,11 +17,11 @@ Although this package can be used in both TypeScript and JavaScript, it is inten
17
17
  Navigate to the folder of your consuming project and run one of the following commands:
18
18
 
19
19
  ```
20
- npm install @emilgroup/document-sdk-node@1.0.0 --save
20
+ npm install @emilgroup/document-sdk-node@1.2.0 --save
21
21
  ```
22
22
  or
23
23
  ```
24
- yarn add @emilgroup/document-sdk-node@1.0.0
24
+ yarn add @emilgroup/document-sdk-node@1.2.0
25
25
  ```
26
26
 
27
27
  And then you can import `DocumentsApi`.
package/api.ts CHANGED
@@ -37,8 +37,3 @@ export * from './api/layouts-api';
37
37
  export * from './api/searchable-document-owners-api';
38
38
  export * from './api/searchable-documents-api';
39
39
 
40
-
41
- export enum Environment {
42
- Production = 'https://apiv2.emil.de',
43
- Test = 'https://apiv2-test.emil.de',
44
- }
package/base.ts CHANGED
@@ -1,8 +1,8 @@
1
1
  /* tslint:disable */
2
2
  /* eslint-disable */
3
3
  /**
4
- * EMIL AccountService
5
- * The EMIL AccountService API description
4
+ * EMIL DocumentService
5
+ * The EMIL DocumentService API description
6
6
  *
7
7
  * The version of the OpenAPI document: 1.0
8
8
  *
@@ -13,243 +13,272 @@
13
13
  */
14
14
 
15
15
 
16
- import { Configuration } from "./configuration";
17
- // Some imports not used depending on template conditions
18
- // @ts-ignore
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';
23
-
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';
29
-
30
- const filePath = os.homedir() + path.sep + CONFIG_DIRECTORY + path.sep + CONFIG_FILENAME;
31
- /**
32
- *
33
- * @export
34
- */
35
- export const COLLECTION_FORMATS = {
36
- csv: ",",
37
- ssv: " ",
38
- tsv: "\t",
39
- pipes: "|",
40
- };
41
-
42
- export interface LoginClass {
43
- accessToken: string;
44
- permissions: Array<string>;
45
- newPasswordRequired: boolean;
46
- }
47
-
48
- export enum Environment {
49
- Production = 'https://apiv2.emil.de',
50
- Test = 'https://apiv2-test.emil.de',
51
- }
52
-
53
- /**
54
- *
55
- * @export
56
- * @interface RequestArgs
57
- */
58
- export interface RequestArgs {
59
- url: string;
60
- options: AxiosRequestConfig;
61
- }
62
-
63
- /**
64
- *
65
- * @export
66
- * @class BaseAPI
67
- */
68
- export class BaseAPI {
69
- protected configuration: Configuration;
70
- private username?: string;
71
- private password?: string;
72
-
73
- constructor(configuration?: Configuration, protected basePath: string = BASE_PATH, protected axios: AxiosInstance = globalAxios) {
74
- if (configuration) {
75
- this.configuration = configuration;
76
- this.basePath = configuration.basePath || this.basePath;
77
- } else {
78
- this.configuration = new Configuration({
79
- basePath: this.basePath,
80
- });
81
- }
82
-
83
- this.attachInterceptor(axios);
84
- }
85
-
86
- async initialize(env: Environment = Environment.Production) {
87
- this.configuration.basePath = env;
88
-
89
- await this.loadCredentials();
90
-
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
-
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
- }
110
- }
111
-
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
- });
125
- }
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
-
138
- selectEnvironment(env: Environment) {
139
- this.configuration.basePath = env;
140
- }
141
-
142
- async authorize(username: string, password: string): Promise<void> {
143
- const options: AxiosRequestConfig = {
144
- method: 'POST',
145
- url: `${this.configuration.basePath}/authservice/v1/login`,
146
- headers: { 'Content-Type': 'application/json' },
147
- data: {
148
- username,
149
- password,
150
- },
151
- withCredentials: true,
152
- };
153
-
154
- const response = await globalAxios.request<LoginClass>(options);
155
-
156
- const { data: { accessToken } } = response;
157
- const refreshToken = this.extractRefreshToken(response)
158
-
159
- this.configuration.username = username;
160
- this.configuration.accessToken = `Bearer ${accessToken}`;
161
- this.configuration.refreshToken = refreshToken;
162
- }
163
-
164
- async refreshToken(): Promise<string> {
165
- const { username, refreshToken } = this.configuration;
166
-
167
- if (!username || !refreshToken) {
168
- return '';
169
- }
170
-
171
- const options: AxiosRequestConfig = {
172
- method: 'POST',
173
- url: `${this.configuration.basePath}/authservice/v1/refresh-token`,
174
- headers: {
175
- 'Content-Type': 'application/json',
176
- Cookie: refreshToken,
177
- },
178
- data: { username: username },
179
- withCredentials: true,
180
- };
181
-
182
- const { data: { accessToken } } = await globalAxios.request<LoginClass>(options);
183
-
184
- return accessToken;
185
- }
186
-
187
- private extractRefreshToken(response: AxiosResponse): string {
188
- if (response.headers && response.headers['set-cookie']
189
- && response.headers['set-cookie'].length > 0) {
190
-
191
- return `${response.headers['set-cookie'][0].split(';')[0]};`;
192
- }
193
-
194
- return '';
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
- }
242
- };
243
-
244
- /**
245
- *
246
- * @export
247
- * @class RequiredError
248
- * @extends {Error}
249
- */
250
- export class RequiredError extends Error {
251
- name: "RequiredError" = "RequiredError";
252
- constructor(public field: string, msg?: string) {
253
- super(msg);
254
- }
255
- }
16
+ import { Configuration } from "./configuration";
17
+ // Some imports not used depending on template conditions
18
+ // @ts-ignore
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';
23
+
24
+ export const BASE_PATH = "https://apiv2.emil.de".replace(/\/+$/, "");
25
+ const CONFIG_DIRECTORY = '.emil';
26
+ const CONFIG_FILENAME = 'credentials';
27
+ const KEY_USERNAME = 'emil_username';
28
+ const KEY_PASSWORD = 'emil_password';
29
+
30
+ const filePath = os.homedir() + path.sep + CONFIG_DIRECTORY + path.sep + CONFIG_FILENAME;
31
+ /**
32
+ *
33
+ * @export
34
+ */
35
+ export const COLLECTION_FORMATS = {
36
+ csv: ",",
37
+ ssv: " ",
38
+ tsv: "\t",
39
+ pipes: "|",
40
+ };
41
+
42
+ export interface LoginClass {
43
+ accessToken: string;
44
+ permissions: Array<string>;
45
+ }
46
+
47
+ export enum Environment {
48
+ Production = 'https://apiv2.emil.de',
49
+ Test = 'https://apiv2-test.emil.de',
50
+ Development = 'https://apiv2-dev.emil.de',
51
+ }
52
+
53
+ let _retry_count = 0
54
+ let _retry = null
55
+
56
+ export function resetRetry() {
57
+ _retry_count = 0
58
+ }
59
+
60
+ /**
61
+ *
62
+ * @export
63
+ * @interface RequestArgs
64
+ */
65
+ export interface RequestArgs {
66
+ url: string;
67
+ options: AxiosRequestConfig;
68
+ }
69
+
70
+ const NETWORK_ERROR_MESSAGE = "Network Error";
71
+
72
+ /**
73
+ *
74
+ * @export
75
+ * @class BaseAPI
76
+ */
77
+ export class BaseAPI {
78
+ protected configuration: Configuration;
79
+ private username?: string;
80
+ private password?: string;
81
+
82
+ constructor(configuration?: Configuration, protected basePath: string = BASE_PATH, protected axios: AxiosInstance = globalAxios) {
83
+ if (configuration) {
84
+ this.configuration = configuration;
85
+ this.basePath = configuration.basePath || this.basePath;
86
+ } else {
87
+ this.configuration = new Configuration({
88
+ basePath: this.basePath,
89
+ });
90
+ }
91
+
92
+ this.attachInterceptor(axios);
93
+ }
94
+
95
+ async initialize(env: Environment = Environment.Production) {
96
+ this.configuration.basePath = env;
97
+
98
+ await this.loadCredentials();
99
+
100
+ if (this.username) {
101
+ await this.authorize(this.username, this.password);
102
+ this.password = null; // to avoid keeping password loaded in memory.
103
+ }
104
+ }
105
+
106
+ private async loadCredentials() {
107
+ try {
108
+ await this.readConfigFile();
109
+ } catch (error) {
110
+ console.warn(`No credentials file found. Check that ${filePath} exists.`);
111
+ }
112
+
113
+ this.readEnvVariables();
114
+
115
+ if (!this.username) {
116
+ console.info(`No credentials found in credentials file or environment variables. Either provide some or use
117
+ authorize() function.`);
118
+ }
119
+ }
120
+
121
+ private async readConfigFile() {
122
+ const file = await fs.promises.readFile(filePath, 'utf-8');
123
+
124
+ const lines = file.split(os.EOL)
125
+ .filter(Boolean);
126
+
127
+ lines.forEach((line: string) => {
128
+ if (line.startsWith(KEY_USERNAME)) {
129
+ this.username = line.length > KEY_USERNAME.length + 1 ? line.substring(KEY_USERNAME.length + 1) : '';
130
+ } else if (line.startsWith(KEY_PASSWORD)) {
131
+ this.password = line.length > KEY_PASSWORD.length + 1 ? line.substring(KEY_PASSWORD.length + 1) : '';
132
+ }
133
+ });
134
+ }
135
+
136
+ private readEnvVariables(): boolean {
137
+ if (process.env.EMIL_USERNAME) {
138
+ this.username = process.env.EMIL_USERNAME;
139
+ this.password = process.env.EMIL_PASSWORD || '';
140
+
141
+ return true;
142
+ }
143
+
144
+ return false;
145
+ }
146
+
147
+ selectEnvironment(env: Environment) {
148
+ this.configuration.basePath = env;
149
+ }
150
+
151
+ async authorize(username: string, password: string): Promise<void> {
152
+ const options: AxiosRequestConfig = {
153
+ method: 'POST',
154
+ url: `${this.configuration.basePath}/authservice/v1/login`,
155
+ headers: { 'Content-Type': 'application/json' },
156
+ data: {
157
+ username,
158
+ password,
159
+ },
160
+ withCredentials: true,
161
+ };
162
+
163
+ const response = await globalAxios.request<LoginClass>(options);
164
+
165
+ const { data: { accessToken } } = response;
166
+ this.configuration.username = username;
167
+ this.configuration.accessToken = `Bearer ${accessToken}`;
168
+
169
+ const refreshToken = this.extractRefreshToken(response)
170
+ this.configuration.refreshToken = refreshToken;
171
+ }
172
+
173
+ async refreshTokenInternal(): Promise<string> {
174
+ const { username, refreshToken } = this.configuration;
175
+
176
+
177
+ if (!username || !refreshToken) {
178
+ return '';
179
+ }
180
+
181
+ const options: AxiosRequestConfig = {
182
+ method: 'POST',
183
+ url: `${this.configuration.basePath}/authservice/v1/refresh-token`,
184
+ headers: {
185
+ 'Content-Type': 'application/json',
186
+ Cookie: refreshToken,
187
+ },
188
+ data: { username: username },
189
+ withCredentials: true,
190
+ };
191
+
192
+ const { data: { accessToken } } = await globalAxios.request<LoginClass>(options);
193
+
194
+ return accessToken;
195
+ }
196
+
197
+ private extractRefreshToken(response: AxiosResponse): string {
198
+ if (response.headers && response.headers['set-cookie']
199
+ && response.headers['set-cookie'].length > 0) {
200
+
201
+ return `${response.headers['set-cookie'][0].split(';')[0]};`;
202
+ }
203
+
204
+ return '';
205
+ }
206
+
207
+ getConfiguration(): Configuration {
208
+ return this.configuration;
209
+ }
210
+
211
+ private attachInterceptor(axios: AxiosInstance) {
212
+ axios.interceptors.response.use(
213
+ (res) => {
214
+ return res;
215
+ },
216
+ async (err) => {
217
+ let originalConfig = err.config;
218
+ if (err.response) {
219
+ // Access Token was expired
220
+ if (err.response.status === 401 && !originalConfig._retry) {
221
+ originalConfig._retry = true;
222
+ try {
223
+ const tokenString = await this.refreshTokenInternal();
224
+ const accessToken = `Bearer ${tokenString}`;
225
+
226
+ originalConfig.headers['Authorization'] = `Bearer ${accessToken}`
227
+
228
+ this.configuration.accessToken = accessToken;
229
+
230
+ return axios.request(originalConfig);
231
+ } catch (_error) {
232
+ if (_error.response && _error.response.data) {
233
+ return Promise.reject(_error.response.data);
234
+ }
235
+ return Promise.reject(_error);
236
+ }
237
+ }
238
+ if (err.response.status === 403 && err.response.data) {
239
+ return Promise.reject(err.response.data);
240
+ }
241
+ } else if(err.message === NETWORK_ERROR_MESSAGE
242
+ && err.isAxiosError
243
+ && originalConfig.headers.hasOwnProperty('Authorization')
244
+ && _retry_count < 4
245
+ ){
246
+ _retry_count++;
247
+ try {
248
+ const tokenString = await this.refreshTokenInternal();
249
+ const accessToken = `Bearer ${tokenString}`;
250
+
251
+ _retry = true;
252
+ originalConfig.headers['Authorization'] = accessToken;
253
+
254
+ this.configuration.accessToken = accessToken;
255
+
256
+ return axios.request({
257
+ ...originalConfig,
258
+ });
259
+ } catch (_error) {
260
+ if (_error.response && _error.response.data) {
261
+ return Promise.reject(_error.response.data);
262
+ }
263
+ return Promise.reject(_error);
264
+ }
265
+ }
266
+ return Promise.reject(err);
267
+ }
268
+ );
269
+ }
270
+ };
271
+
272
+ /**
273
+ *
274
+ * @export
275
+ * @class RequiredError
276
+ * @extends {Error}
277
+ */
278
+ export class RequiredError extends Error {
279
+ name: "RequiredError" = "RequiredError";
280
+ constructor(public field: string, msg?: string) {
281
+ super(msg);
282
+ }
283
+ }
284
+
package/common.ts CHANGED
@@ -136,3 +136,64 @@ export const createRequestFunction = function (axiosArgs: RequestArgs, globalAxi
136
136
  return axios.request<T, R>(axiosRequestArgs);
137
137
  };
138
138
  }
139
+
140
+ /* tslint:disable */
141
+ /* eslint-disable */
142
+ /**
143
+ * EMIL DocumentService
144
+ * The EMIL DocumentService API description
145
+ *
146
+ * The version of the OpenAPI document: 1.0
147
+ *
148
+ *
149
+ * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
150
+ * https://openapi-generator.tech
151
+ * Do not edit the class manually.
152
+ */
153
+
154
+
155
+ export interface IStorageConverter<D, SD> {
156
+ toStorageData( data: D ): SD;
157
+ fromStorageData( storageData: SD ): D;
158
+ }
159
+
160
+ export interface IStorage {
161
+ get<T>( key: string, converter?: IStorageConverter<T, any> ): T | null;
162
+ set<T>( key: string, value: T, converter?: IStorageConverter<T, any> ): void;
163
+ }
164
+
165
+ export class LocalStorage implements IStorage {
166
+ readonly storage: Storage;
167
+
168
+ constructor() {
169
+ this.storage = localStorage;
170
+ }
171
+
172
+ get<T>( key: string, converter?: IStorageConverter<T, any> ): T | null {
173
+ const jsonValue = this.storage.getItem( key );
174
+ if ( jsonValue === null ) {
175
+ return null;
176
+ }
177
+ const value = JSON.parse( jsonValue );
178
+ if ( converter !== undefined ) {
179
+ return converter.fromStorageData( value );
180
+ } else {
181
+ return value as T;
182
+ }
183
+ }
184
+
185
+ set<T>( key: string, value: T, converter?: IStorageConverter<T, any> ): void {
186
+ let valueToStore: any = value;
187
+ if ( converter !== undefined ) {
188
+ valueToStore = converter.toStorageData( value );
189
+ }
190
+ const jsonValue = JSON.stringify( valueToStore );
191
+ this.storage.setItem( key, jsonValue );
192
+ }
193
+ }
194
+
195
+ let _defaultStorage: IStorage = null;
196
+
197
+ export const defaultStorage = (): IStorage => {
198
+ return _defaultStorage || (_defaultStorage = new LocalStorage());
199
+ };
@@ -53,7 +53,7 @@ var __generator = (this && this.__generator) || function (thisArg, body) {
53
53
  function verb(n) { return function (v) { return step([n, v]); }; }
54
54
  function step(op) {
55
55
  if (f) throw new TypeError("Generator is already executing.");
56
- while (_) try {
56
+ while (g && (g = 0, op[0] && (_ = 0)), _) try {
57
57
  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;
58
58
  if (y = 0, t) op = [op[0] & 2, t.value];
59
59
  switch (op[0]) {
@@ -53,7 +53,7 @@ var __generator = (this && this.__generator) || function (thisArg, body) {
53
53
  function verb(n) { return function (v) { return step([n, v]); }; }
54
54
  function step(op) {
55
55
  if (f) throw new TypeError("Generator is already executing.");
56
- while (_) try {
56
+ while (g && (g = 0, op[0] && (_ = 0)), _) try {
57
57
  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;
58
58
  if (y = 0, t) op = [op[0] & 2, t.value];
59
59
  switch (op[0]) {
@@ -53,7 +53,7 @@ var __generator = (this && this.__generator) || function (thisArg, body) {
53
53
  function verb(n) { return function (v) { return step([n, v]); }; }
54
54
  function step(op) {
55
55
  if (f) throw new TypeError("Generator is already executing.");
56
- while (_) try {
56
+ while (g && (g = 0, op[0] && (_ = 0)), _) try {
57
57
  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;
58
58
  if (y = 0, t) op = [op[0] & 2, t.value];
59
59
  switch (op[0]) {