@devrev/ts-adaas 0.0.1 → 0.0.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.
Files changed (38) hide show
  1. package/README.md +16 -4
  2. package/dist/src/adapter/index.d.ts +35 -30
  3. package/dist/src/adapter/index.js +93 -56
  4. package/dist/src/common/constants.d.ts +2 -0
  5. package/dist/src/common/constants.js +10 -0
  6. package/dist/src/{adapter → common}/helpers.d.ts +4 -1
  7. package/dist/src/{adapter → common}/helpers.js +16 -4
  8. package/dist/src/demo-extractor/index.d.ts +8 -1
  9. package/dist/src/demo-extractor/index.js +64 -56
  10. package/dist/src/demo-extractor/initial_domain_mapping.json +107 -0
  11. package/dist/src/http/client.d.ts +1 -1
  12. package/dist/src/http/client.js +2 -2
  13. package/dist/src/http/index.d.ts +0 -1
  14. package/dist/src/http/index.js +0 -1
  15. package/dist/src/index.d.ts +1 -0
  16. package/dist/src/index.js +1 -0
  17. package/dist/src/logging/index.d.ts +5 -18
  18. package/dist/src/logging/index.js +20 -41
  19. package/dist/src/state/index.d.ts +23 -0
  20. package/dist/src/state/index.js +111 -0
  21. package/dist/src/types/extraction.d.ts +16 -5
  22. package/dist/src/uploader/index.d.ts +4 -2
  23. package/dist/src/uploader/index.js +61 -4
  24. package/dist/tests/adapter.helpers.test.js +60 -0
  25. package/dist/tests/adapter.test.js +106 -57
  26. package/dist/tests/demo-extractor.test.js +44 -81
  27. package/dist/tests/state.test.js +100 -0
  28. package/dist/tests/uploader.test.js +29 -0
  29. package/package.json +1 -1
  30. package/dist/src/adapter/index.test.js +0 -105
  31. package/dist/src/demo-extractor/recipe.json +0 -37
  32. package/dist/tests/helpers.test.js +0 -38
  33. package/dist/tests/test-helpers.d.ts +0 -2
  34. package/dist/tests/test-helpers.js +0 -33
  35. package/dist/tests/types.test.js +0 -71
  36. /package/dist/{src/adapter/index.test.d.ts → tests/adapter.helpers.test.d.ts} +0 -0
  37. /package/dist/tests/{helpers.test.d.ts → state.test.d.ts} +0 -0
  38. /package/dist/tests/{types.test.d.ts → uploader.test.d.ts} +0 -0
@@ -0,0 +1,107 @@
1
+ {
2
+ "initial_object_mappings": [
3
+ {
4
+ "external_type": "contacts",
5
+ "possible_targets": {
6
+ "rev_user": {
7
+ "initial_field_mappings": [
8
+ {
9
+ "destination_field": {
10
+ "id": "id",
11
+ "is_required": true
12
+ },
13
+ "selected_resolutions": ["id"],
14
+ "resolutions": {
15
+ "id": {
16
+ "source_field_description": {
17
+ "id": "id",
18
+ "is_required": true
19
+ }
20
+ }
21
+ },
22
+ "is_finished": true
23
+ },
24
+ {
25
+ "destination_field": {
26
+ "id": "display_name",
27
+ "is_required": true
28
+ },
29
+ "selected_resolutions": ["name"],
30
+ "resolutions": {
31
+ "name": {
32
+ "source_field_description": {
33
+ "id": "name",
34
+ "is_required": true
35
+ }
36
+ }
37
+ },
38
+ "is_finished": true
39
+ }
40
+ ]
41
+ }
42
+ },
43
+ "default_target": "rev_user",
44
+ "allow_item_type_decisions": true
45
+ },
46
+ {
47
+ "external_type": "users",
48
+ "possible_targets": {
49
+ "dev_user": {
50
+ "initial_field_mappings": [
51
+ {
52
+ "destination_field": {
53
+ "id": "id",
54
+ "is_required": true
55
+ },
56
+ "selected_resolutions": ["id"],
57
+ "resolutions": {
58
+ "id": {
59
+ "source_field_description": {
60
+ "id": "id",
61
+ "is_required": true
62
+ }
63
+ }
64
+ },
65
+ "is_finished": true
66
+ },
67
+ {
68
+ "destination_field": {
69
+ "id": "display_name",
70
+ "is_required": true
71
+ },
72
+ "selected_resolutions": ["name"],
73
+ "resolutions": {
74
+ "name": {
75
+ "source_field_description": {
76
+ "id": "name",
77
+ "is_required": true
78
+ }
79
+ }
80
+ },
81
+ "is_finished": true
82
+ }
83
+ ]
84
+ }
85
+ },
86
+ "default_target": "dev_user",
87
+ "allow_item_type_decisions": true
88
+ },
89
+ {
90
+ "external_type": "tickets",
91
+ "possible_targets": {
92
+ "work.ticket": {}
93
+ },
94
+ "default_target": "work.ticket",
95
+ "allow_item_type_decisions": true
96
+ },
97
+ {
98
+ "external_type": "conversations",
99
+ "possible_targets": {
100
+ "comment": {}
101
+ },
102
+ "default_target": "comment",
103
+ "allow_item_type_decisions": true
104
+ }
105
+ ],
106
+ "external_system_short_name": "Freshdesk"
107
+ }
@@ -1,6 +1,6 @@
1
1
  import { HTTPResponse } from './types';
2
2
  export declare const defaultResponse: HTTPResponse;
3
- export default class HTTPClient {
3
+ export declare class HTTPClient {
4
4
  private retryAfter;
5
5
  private retryAt;
6
6
  private axiosInstance;
@@ -23,7 +23,7 @@ var __importStar = (this && this.__importStar) || function (mod) {
23
23
  return result;
24
24
  };
25
25
  Object.defineProperty(exports, "__esModule", { value: true });
26
- exports.defaultResponse = void 0;
26
+ exports.HTTPClient = exports.defaultResponse = void 0;
27
27
  const axios_1 = __importStar(require("axios"));
28
28
  const constants_1 = require("./constants");
29
29
  exports.defaultResponse = {
@@ -144,4 +144,4 @@ class HTTPClient {
144
144
  }
145
145
  }
146
146
  }
147
- exports.default = HTTPClient;
147
+ exports.HTTPClient = HTTPClient;
@@ -1,3 +1,2 @@
1
1
  export * from './client';
2
2
  export * from './types';
3
- export * from './constants';
@@ -16,4 +16,3 @@ var __exportStar = (this && this.__exportStar) || function(m, exports) {
16
16
  Object.defineProperty(exports, "__esModule", { value: true });
17
17
  __exportStar(require("./client"), exports);
18
18
  __exportStar(require("./types"), exports);
19
- __exportStar(require("./constants"), exports);
@@ -2,3 +2,4 @@ export * from './adapter';
2
2
  export * from './demo-extractor';
3
3
  export * from './uploader';
4
4
  export * from './types';
5
+ export * from './http';
package/dist/src/index.js CHANGED
@@ -18,3 +18,4 @@ __exportStar(require("./adapter"), exports);
18
18
  __exportStar(require("./demo-extractor"), exports);
19
19
  __exportStar(require("./uploader"), exports);
20
20
  __exportStar(require("./types"), exports);
21
+ __exportStar(require("./http"), exports);
@@ -1,8 +1,8 @@
1
- declare enum LogLevel {
1
+ import { AirdropEvent } from '../types';
2
+ export declare enum LogLevel {
2
3
  INFO = "info",
3
4
  WARN = "warn",
4
- ERROR = "error",
5
- DEBUG = "debug"
5
+ ERROR = "error"
6
6
  }
7
7
  /**
8
8
  * Logger class to log messages based on the log level.
@@ -10,22 +10,9 @@ declare enum LogLevel {
10
10
  * - INFO
11
11
  * - WARN
12
12
  * - ERROR
13
- * - DEBUG
14
13
  *
15
14
  * The log tags can be set to any key-value pair.
16
15
  */
17
- declare class Logger {
18
- private level;
19
- private logTags;
20
- private static instance;
21
- private constructor();
22
- private log;
23
- static getInstance(level: LogLevel, logTags?: Record<string, any>): Logger;
24
- setTags(tags: Record<string, any>): void;
25
- addTags(tags: Record<string, any>): void;
26
- info(message: string): void;
27
- warn(message: string): void;
28
- error(message: string): void;
29
- debug(message: string): void;
16
+ export declare class Logger {
17
+ static init(event: AirdropEvent): void;
30
18
  }
31
- export default Logger;
@@ -1,60 +1,39 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.Logger = exports.LogLevel = void 0;
3
4
  var LogLevel;
4
5
  (function (LogLevel) {
5
6
  LogLevel["INFO"] = "info";
6
7
  LogLevel["WARN"] = "warn";
7
8
  LogLevel["ERROR"] = "error";
8
- LogLevel["DEBUG"] = "debug";
9
- })(LogLevel || (LogLevel = {}));
9
+ })(LogLevel || (exports.LogLevel = LogLevel = {}));
10
10
  /**
11
11
  * Logger class to log messages based on the log level.
12
12
  * The log level can be set to one of the following:
13
13
  * - INFO
14
14
  * - WARN
15
15
  * - ERROR
16
- * - DEBUG
17
16
  *
18
17
  * The log tags can be set to any key-value pair.
19
18
  */
20
19
  class Logger {
21
- // Private constructor to prevent instantiation
22
- constructor(level, logTags = {}) {
23
- this.logTags = {};
24
- this.level = level;
25
- this.logTags = logTags;
26
- }
27
- log(level, message) {
28
- if (this.level === level) {
29
- console.log(`[${level.toUpperCase()}]: ${message}`, this.logTags);
30
- }
31
- }
32
- // Singleton instance
33
- static getInstance(level, logTags = {}) {
34
- if (!Logger.instance) {
35
- Logger.instance = new Logger(level, logTags);
36
- }
37
- return Logger.instance;
38
- }
39
- // Set log tags destructively.
40
- setTags(tags) {
41
- this.logTags = tags;
42
- }
43
- // Add log tags. If the key already exists, it will be overwritten.
44
- addTags(tags) {
45
- this.logTags = Object.assign(Object.assign({}, this.logTags), tags);
46
- }
47
- info(message) {
48
- this.log(LogLevel.INFO, message);
49
- }
50
- warn(message) {
51
- this.log(LogLevel.WARN, message);
52
- }
53
- error(message) {
54
- this.log(LogLevel.ERROR, message);
55
- }
56
- debug(message) {
57
- this.log(LogLevel.DEBUG, message);
20
+ static init(event) {
21
+ const origLog = console.log;
22
+ console.log = (message) => {
23
+ origLog(`[${LogLevel.INFO.toUpperCase()}]: ${message}`, Object.assign({}, event.payload.event_context));
24
+ };
25
+ const origInfo = console.info;
26
+ console.info = (message) => {
27
+ origInfo(`[${LogLevel.INFO.toUpperCase()}]: ${message}`, Object.assign({}, event.payload.event_context));
28
+ };
29
+ const origWarn = console.warn;
30
+ console.warn = (message) => {
31
+ origWarn(`[${LogLevel.WARN.toUpperCase()}]: ${message}`, Object.assign({}, event.payload.event_context));
32
+ };
33
+ const origError = console.error;
34
+ console.error = (message) => {
35
+ origError(`[${LogLevel.ERROR.toUpperCase()}]: ${message}`, Object.assign({}, event.payload.event_context));
36
+ };
58
37
  }
59
38
  }
60
- exports.default = Logger;
39
+ exports.Logger = Logger;
@@ -0,0 +1,23 @@
1
+ import { AdapterState, AirdropEvent } from '../types';
2
+ export declare function createAdapterState<ExtractorState>(event: AirdropEvent, initialState: ExtractorState): Promise<State<ExtractorState>>;
3
+ export declare class State<ExtractorState> {
4
+ private _state;
5
+ private event;
6
+ private workerUrl;
7
+ private devrevToken;
8
+ constructor(event: AirdropEvent, initialState: ExtractorState);
9
+ get state(): AdapterState<ExtractorState>;
10
+ set state(value: AdapterState<ExtractorState>);
11
+ /**
12
+ * Updates the state of the adapter.
13
+ *
14
+ * @param {object} state - The state to be updated
15
+ */
16
+ postState(state: AdapterState<ExtractorState>): Promise<void>;
17
+ /**
18
+ * Fetches the state of the adapter.
19
+ *
20
+ * @return The state of the adapter
21
+ */
22
+ fetchState(initialState: ExtractorState): Promise<AdapterState<ExtractorState> | unknown>;
23
+ }
@@ -0,0 +1,111 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || function (mod) {
19
+ if (mod && mod.__esModule) return mod;
20
+ var result = {};
21
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
22
+ __setModuleDefault(result, mod);
23
+ return result;
24
+ };
25
+ Object.defineProperty(exports, "__esModule", { value: true });
26
+ exports.State = exports.createAdapterState = void 0;
27
+ const axios_1 = __importStar(require("axios"));
28
+ const constants_1 = require("../common/constants");
29
+ async function createAdapterState(event, initialState) {
30
+ const newInitialState = structuredClone(initialState);
31
+ const as = new State(event, newInitialState);
32
+ if (!constants_1.STATELESS_EVENT_TYPES.includes(event.payload.event_type)) {
33
+ console.log('Fetching state');
34
+ await as.fetchState(newInitialState);
35
+ }
36
+ return as;
37
+ }
38
+ exports.createAdapterState = createAdapterState;
39
+ class State {
40
+ constructor(event, initialState) {
41
+ this._state = Object.assign({ lastSyncStarted: '', lastSuccessfulSyncStarted: '' }, initialState);
42
+ this.event = event;
43
+ this.workerUrl = event.payload.event_context.worker_data_url;
44
+ this.devrevToken = event.context.secrets.service_account_token;
45
+ }
46
+ get state() {
47
+ return this._state;
48
+ }
49
+ set state(value) {
50
+ this._state = value;
51
+ }
52
+ /**
53
+ * Updates the state of the adapter.
54
+ *
55
+ * @param {object} state - The state to be updated
56
+ */
57
+ async postState(state) {
58
+ try {
59
+ await axios_1.default.post(this.workerUrl + '.update', {
60
+ state: JSON.stringify(state),
61
+ }, {
62
+ headers: {
63
+ Authorization: this.devrevToken,
64
+ },
65
+ params: {
66
+ sync_unit: this.event.payload.event_context.sync_unit_id,
67
+ },
68
+ });
69
+ this.state = state;
70
+ console.log('State updated successfully');
71
+ }
72
+ catch (error) {
73
+ console.error('Failed to update state, error:' + error);
74
+ }
75
+ }
76
+ /**
77
+ * Fetches the state of the adapter.
78
+ *
79
+ * @return The state of the adapter
80
+ */
81
+ async fetchState(initialState) {
82
+ var _a;
83
+ const state = Object.assign(Object.assign({}, initialState), { lastSyncStarted: '', lastSuccessfulSyncStarted: '' });
84
+ console.log('Fetching state with sync unit id: ' +
85
+ this.event.payload.event_context.sync_unit_id);
86
+ try {
87
+ const response = await axios_1.default.post(this.workerUrl + '.get', {}, {
88
+ headers: {
89
+ Authorization: this.devrevToken,
90
+ },
91
+ params: {
92
+ sync_unit: this.event.payload.event_context.sync_unit_id,
93
+ },
94
+ });
95
+ this.state = JSON.parse(response.data.state);
96
+ console.log('State fetched successfully');
97
+ return this.state;
98
+ }
99
+ catch (error) {
100
+ if ((0, axios_1.isAxiosError)(error) && ((_a = error.response) === null || _a === void 0 ? void 0 : _a.status) === 404) {
101
+ console.log('State not found, returning initial state');
102
+ this.state = state;
103
+ this.postState(this.state);
104
+ return this.state;
105
+ }
106
+ console.error('Failed to fetch state, error:' + error);
107
+ return error;
108
+ }
109
+ }
110
+ }
111
+ exports.State = State;
@@ -1,4 +1,4 @@
1
- import { InputData, Context, ExecutionMetadata } from '@devrev/typescript-sdk/dist/snap-ins';
1
+ import { InputData } from '@devrev/typescript-sdk/dist/snap-ins';
2
2
  import { Artifact, ErrorRecord } from './common';
3
3
  export declare enum EventType {
4
4
  ExtractionExternalSyncUnitsStart = "EXTRACTION_EXTERNAL_SYNC_UNITS_START",
@@ -43,7 +43,7 @@ export interface ExternalSyncUnit {
43
43
  id: string;
44
44
  name: string;
45
45
  description: string;
46
- item_count: number;
46
+ item_count?: number;
47
47
  }
48
48
  export interface EventContextIn {
49
49
  mode: string;
@@ -55,6 +55,7 @@ export interface EventContextIn {
55
55
  sync_run_id: string;
56
56
  external_system_id: string;
57
57
  uuid: string;
58
+ worker_data_url: string;
58
59
  }
59
60
  export interface EventContextOut {
60
61
  uuid: string;
@@ -85,9 +86,15 @@ export interface DomainObjectState {
85
86
  count: number;
86
87
  }
87
88
  export interface AirdropEvent {
88
- context: Context;
89
+ context: {
90
+ secrets: {
91
+ service_account_token: string;
92
+ };
93
+ };
89
94
  payload: AirdropMessage;
90
- execution_metadata: ExecutionMetadata;
95
+ execution_metadata: {
96
+ devrev_endpoint: string;
97
+ };
91
98
  input_data: InputData;
92
99
  }
93
100
  export interface AirdropMessage {
@@ -100,6 +107,10 @@ export interface AirdropMessage {
100
107
  export interface ExtractorEvent {
101
108
  event_type: string;
102
109
  event_context: EventContextOut;
103
- extractor_state: string;
110
+ extractor_state?: string;
104
111
  event_data?: EventData;
105
112
  }
113
+ export type AdapterState<ExtractorState> = ExtractorState & {
114
+ lastSyncStarted?: string;
115
+ lastSuccessfulSyncStarted?: string;
116
+ };
@@ -10,11 +10,12 @@ import { UploadResponse } from '../types/common';
10
10
  * @constructor
11
11
  * @param {string} endpoint - The endpoint of the DevRev platform
12
12
  * @param {string} token - The token to authenticate with the DevRev platform
13
+ * @param {boolean} local - Flag to indicate if the uploader should upload to the file-system.
13
14
  */
14
15
  export declare class Uploader {
15
16
  private betaDevrevSdk;
16
- private publicDevrevSdk;
17
- constructor(endpoint: string, token: string);
17
+ private local;
18
+ constructor(endpoint: string, token: string, local?: boolean);
18
19
  /**
19
20
  *
20
21
  * Uploads the file to the DevRev platform. The file is uploaded to the platform
@@ -29,4 +30,5 @@ export declare class Uploader {
29
30
  upload(filename: string, entity: string, fetchedObjects: object[] | object, filetype?: string): Promise<UploadResponse>;
30
31
  private prepareArtifact;
31
32
  private uploadToArtifact;
33
+ private downloadToLocal;
32
34
  }
@@ -1,4 +1,27 @@
1
1
  "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || function (mod) {
19
+ if (mod && mod.__esModule) return mod;
20
+ var result = {};
21
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
22
+ __setModuleDefault(result, mod);
23
+ return result;
24
+ };
2
25
  var __importDefault = (this && this.__importDefault) || function (mod) {
3
26
  return (mod && mod.__esModule) ? mod : { "default": mod };
4
27
  };
@@ -6,7 +29,8 @@ Object.defineProperty(exports, "__esModule", { value: true });
6
29
  exports.Uploader = void 0;
7
30
  const axios_1 = __importDefault(require("axios"));
8
31
  const typescript_sdk_1 = require("@devrev/typescript-sdk");
9
- const helpers_1 = require("../adapter/helpers");
32
+ const fs_1 = __importStar(require("fs"));
33
+ const helpers_1 = require("../common/helpers");
10
34
  /**
11
35
  * Uploader class is used to upload files to the DevRev platform.
12
36
  * The class provides utilities to
@@ -18,14 +42,15 @@ const helpers_1 = require("../adapter/helpers");
18
42
  * @constructor
19
43
  * @param {string} endpoint - The endpoint of the DevRev platform
20
44
  * @param {string} token - The token to authenticate with the DevRev platform
45
+ * @param {boolean} local - Flag to indicate if the uploader should upload to the file-system.
21
46
  */
22
47
  class Uploader {
23
- constructor(endpoint, token) {
48
+ constructor(endpoint, token, local = false) {
24
49
  this.betaDevrevSdk = typescript_sdk_1.client.setupBeta({
25
50
  endpoint,
26
51
  token,
27
52
  });
28
- this.publicDevrevSdk = typescript_sdk_1.client.setup({ endpoint, token });
53
+ this.local = local;
29
54
  }
30
55
  /**
31
56
  *
@@ -39,6 +64,9 @@ class Uploader {
39
64
  * @returns {Promise<UploadResponse>} - The response object containing the artifact information
40
65
  */
41
66
  async upload(filename, entity, fetchedObjects, filetype = 'application/jsonl+json') {
67
+ if (this.local) {
68
+ this.downloadToLocal(filename, fetchedObjects);
69
+ }
42
70
  const preparedArtifact = await this.prepareArtifact(filename, filetype);
43
71
  if (!preparedArtifact) {
44
72
  return {
@@ -60,6 +88,7 @@ class Uploader {
60
88
  item_type: entity,
61
89
  item_count: itemCount,
62
90
  };
91
+ console.log(`Artifact uploaded successfully: ${artifact.id}`);
63
92
  return { artifact, error: undefined };
64
93
  }
65
94
  async prepareArtifact(filename, filetype) {
@@ -71,7 +100,8 @@ class Uploader {
71
100
  return response.data;
72
101
  }
73
102
  catch (error) {
74
- throw new Error('Error while fetching upload url: ' + error);
103
+ console.error('Error while preparing artifact: ' + error);
104
+ return null;
75
105
  }
76
106
  }
77
107
  async uploadToArtifact(
@@ -91,5 +121,32 @@ class Uploader {
91
121
  return null;
92
122
  }
93
123
  }
124
+ async downloadToLocal(filePath, fetchedObjects) {
125
+ console.log(`Uploading ${filePath} to local file system`);
126
+ try {
127
+ if (!fs_1.default.existsSync('extracted_files')) {
128
+ fs_1.default.mkdirSync('extracted_files');
129
+ }
130
+ const timestamp = new Date().getTime();
131
+ const fileHandle = await fs_1.promises.open(`extracted_files/${timestamp}_${filePath}`, 'w');
132
+ let objArray = [];
133
+ if (!Array.isArray(fetchedObjects)) {
134
+ objArray.push(fetchedObjects);
135
+ }
136
+ else {
137
+ objArray = fetchedObjects;
138
+ }
139
+ for (const jsonObject of objArray) {
140
+ const jsonLine = JSON.stringify(jsonObject) + '\n';
141
+ await fileHandle.write(jsonLine);
142
+ }
143
+ await fileHandle.close();
144
+ console.log('Data successfully written to', filePath);
145
+ }
146
+ catch (error) {
147
+ console.error('Error writing data to file:', error);
148
+ return Promise.reject(error);
149
+ }
150
+ }
94
151
  }
95
152
  exports.Uploader = Uploader;
@@ -0,0 +1,60 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ const helpers_1 = require("../src/common/helpers");
4
+ const types_1 = require("../src/types");
5
+ describe('adapter.helpers.ts', () => {
6
+ it("should create a FormData object with the correct 'key' and 'value'", () => {
7
+ const preparedArtifact = {
8
+ form_data: [{ key: 'key', value: 'value' }],
9
+ };
10
+ const fetchedObjects = [{ key: 'value' }];
11
+ const formData = (0, helpers_1.createFormData)(preparedArtifact, fetchedObjects);
12
+ expect(formData).toBeInstanceOf(FormData);
13
+ expect(formData.get('key')).toBe('value');
14
+ });
15
+ it("should create a FormData object with the correct 'file' key", () => {
16
+ const preparedArtifact = {
17
+ form_data: [{ key: 'key', value: 'value' }],
18
+ };
19
+ const fetchedObjects = [{ key: 'value' }];
20
+ const formData = (0, helpers_1.createFormData)(preparedArtifact, fetchedObjects);
21
+ expect(formData.get('file')).toBeDefined();
22
+ });
23
+ it("should create an Artifact object with the correct 'item_count', 'id', and 'item_type'", () => {
24
+ const preparedArtifact = { id: 'id' };
25
+ const fetchedObjects = [{ key: 'value' }];
26
+ const entity = 'entity';
27
+ const artifact = (0, helpers_1.createArtifact)(preparedArtifact, fetchedObjects, entity);
28
+ expect(artifact).toEqual({
29
+ item_count: 1,
30
+ id: 'id',
31
+ item_type: 'entity',
32
+ });
33
+ });
34
+ it('should return the correct ExtractorEventType', () => {
35
+ expect((0, helpers_1.getTimeoutExtractorEventType)(types_1.EventType.ExtractionMetadataStart)).toStrictEqual({
36
+ eventType: types_1.ExtractorEventType.ExtractionMetadataError,
37
+ isError: true,
38
+ });
39
+ expect((0, helpers_1.getTimeoutExtractorEventType)(types_1.EventType.ExtractionDataStart)).toStrictEqual({
40
+ eventType: types_1.ExtractorEventType.ExtractionDataProgress,
41
+ isError: false,
42
+ });
43
+ expect((0, helpers_1.getTimeoutExtractorEventType)(types_1.EventType.ExtractionDataContinue)).toStrictEqual({
44
+ eventType: types_1.ExtractorEventType.ExtractionDataProgress,
45
+ isError: false,
46
+ });
47
+ expect((0, helpers_1.getTimeoutExtractorEventType)(types_1.EventType.ExtractionAttachmentsStart)).toStrictEqual({
48
+ eventType: types_1.ExtractorEventType.ExtractionAttachmentsProgress,
49
+ isError: false,
50
+ });
51
+ expect((0, helpers_1.getTimeoutExtractorEventType)(types_1.EventType.ExtractionAttachmentsContinue)).toStrictEqual({
52
+ eventType: types_1.ExtractorEventType.ExtractionAttachmentsProgress,
53
+ isError: false,
54
+ });
55
+ expect((0, helpers_1.getTimeoutExtractorEventType)(types_1.EventType.ExtractionExternalSyncUnitsStart)).toStrictEqual({
56
+ eventType: types_1.ExtractorEventType.ExtractionExternalSyncUnitsError,
57
+ isError: true,
58
+ });
59
+ });
60
+ });