@friggframework/core 0.1.0 → 0.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,330 +0,0 @@
1
- const Delegate = require('../Delegate');
2
- const Integration = require('@friggframework/models/Integration');
3
- const Entity = require('@friggframework/models/Entity');
4
- const Credential = require('@friggframework/models/Credential');
5
-
6
- class IntegrationManager extends Delegate {
7
- static Config = {
8
- name: 'Integration Name',
9
- version: '0.0.0', // Integration Version, used for migration and storage purposes, as well as display
10
- supportedVersions: [], // Eventually usable for deprecation and future test version purposes
11
-
12
- // an array of events that are process(able) by this Integration
13
- events: [],
14
- };
15
-
16
- constructor(params) {
17
- super(params);
18
- this.integrationMO = new Integration();
19
- }
20
-
21
- static getName() {
22
- return this.Config.name;
23
- }
24
-
25
- static getCurrentVersion() {
26
- return this.Config.version;
27
- }
28
-
29
- async validateConfig() {
30
- const configOptions = await this.getConfigOptions();
31
- const currentConfig = this.integration.config;
32
- let needsConfig = false;
33
- for (const option of configOptions) {
34
- if (option.required) {
35
- // For now, just make sure the key exists. We should add more dynamic/better validation later.
36
- if (
37
- !Object.prototype.hasOwnProperty.call(
38
- currentConfig,
39
- option.key
40
- )
41
- ) {
42
- needsConfig = true;
43
- this.integration.messages.warnings.push({
44
- title: 'Config Validation Error',
45
- message: `Missing required field of ${option.label}`,
46
- timestamp: Date.now(),
47
- });
48
- }
49
- }
50
- }
51
- if (needsConfig) {
52
- this.integration.status = 'NEEDS_CONFIG';
53
- await this.integration.save();
54
- }
55
- }
56
-
57
- async testAuth() {
58
- let didAuthPass = true;
59
-
60
- try {
61
- await this.primaryInstance.testAuth();
62
- } catch {
63
- didAuthPass = false;
64
- this.integration.messages.errors.push({
65
- title: 'Authentication Error',
66
- message: `There was an error with your ${this.primaryInstance.constructor.getName()} Entity.
67
- Please reconnect/re-authenticate, or reach out to Support for assistance.`,
68
- timestamp: Date.now(),
69
- });
70
- }
71
-
72
- try {
73
- await this.targetInstance.testAuth();
74
- } catch {
75
- didAuthPass = false;
76
- this.integration.messages.errors.push({
77
- title: 'Authentication Error',
78
- message: `There was an error with your ${this.targetInstance.constructor.getName()} Entity.
79
- Please reconnect/re-authenticate, or reach out to Support for assistance.`,
80
- timestamp: Date.now(),
81
- });
82
- }
83
-
84
- if (!didAuthPass) {
85
- this.integration.status = 'ERROR';
86
- this.integration.markModified('messages.error');
87
- await this.integration.save();
88
- }
89
- }
90
-
91
- static async getInstance(params) {
92
- const instance = new this(params);
93
-
94
- params.delegate = instance;
95
- instance.delegateTypes.push(...this.Config.events);
96
- return new this(params);
97
- }
98
-
99
- static getIntegrationManagerClasses(type = '') {
100
- const normalizedType = type.toLowerCase();
101
- const integrationManagerIndex =
102
- this.integrationTypes.indexOf(normalizedType);
103
- const integrationManagerClass =
104
- this.integrationManagerClasses[integrationManagerIndex];
105
-
106
- if (!integrationManagerClass) {
107
- throw new Error(
108
- `Could not find integration manager for type "${type}"`
109
- );
110
- }
111
-
112
- return integrationManagerClass;
113
- }
114
-
115
- // Takes entities, User, and Config, and returns an Instance of the IntegrationManager
116
- static async createIntegration(entities, userId, config) {
117
- // verify entity ids belong to the user
118
- const entityMO = new Entity();
119
-
120
- for (const id of entities) {
121
- const entity = await entityMO.get(id);
122
-
123
- if (!entity) {
124
- throw new Error(`Entity with ID ${id} does not exist.`);
125
- }
126
-
127
- if (entity.user.toString() !== userId.toString()) {
128
- throw new Error(
129
- 'one or more the entities do not belong to the user'
130
- );
131
- }
132
- }
133
-
134
- // build integration
135
- const integrationManagerClass = this.getIntegrationManagerClasses(
136
- config.type
137
- );
138
- const integrationMO = new Integration();
139
- const integration = await integrationMO.create({
140
- entities: entities,
141
- user: userId,
142
- config,
143
- version: integrationManagerClass.Config.version,
144
- });
145
-
146
- const instance = await integrationManagerClass.getInstance({
147
- userId,
148
- integrationId: integration.id,
149
- });
150
- instance.integration = integration;
151
- instance.delegateTypes.push(...integrationManagerClass.Config.events);
152
-
153
- // Need to get special primaryInstance because it has an extra param to pass in
154
- instance.primaryInstance =
155
- await this.EntityManagerClass.getEntityManagerInstanceFromEntityId(
156
- instance.integration.entities[0],
157
- instance.integration.user
158
- );
159
- // Now we can use the general ManagerGetter
160
- instance.targetInstance =
161
- await this.EntityManagerClass.getEntityManagerInstanceFromEntityId(
162
- instance.integration.entities[1],
163
- instance.integration.user
164
- );
165
-
166
- instance.delegate = instance;
167
-
168
- return instance;
169
- }
170
-
171
- static async getFormattedIntegration(integration) {
172
- const entityMO = new Entity();
173
- const integrationObj = {
174
- id: integration.id,
175
- status: integration.status,
176
- config: integration.config,
177
- entities: [],
178
- version: integration.version,
179
- messages: integration.messages,
180
- };
181
- for (const entityId of integration.entities) {
182
- // Only return non-internal fields. Leverages "select" and "options" to non-excepted fields and a pure object.
183
- const entity = await entityMO.get(
184
- entityId,
185
- '-dateCreated -dateUpdated -user -credentials -credential -_id -__t -__v',
186
- { lean: true }
187
- );
188
- integrationObj.entities.push({
189
- id: entityId,
190
- ...entity,
191
- });
192
- }
193
- return integrationObj;
194
- }
195
-
196
- static async getIntegrationsForUserId(userId) {
197
- const integrationMO = new Integration();
198
-
199
- const integrationList = await integrationMO.list({ user: userId });
200
-
201
- const entityMO = new Entity();
202
-
203
- const responseArray = [];
204
- for (const integration of integrationList) {
205
- const integrationObj =
206
- await IntegrationManager.getFormattedIntegration(integration);
207
- responseArray.push(integrationObj);
208
- }
209
- return responseArray;
210
- }
211
-
212
- static async getIntegrationForUserById(userId, integrationId) {
213
- const integrationMO = new Integration();
214
-
215
- const integrationList = await integrationMO.list({
216
- user: userId,
217
- _id: integrationId,
218
- });
219
-
220
- return integrationList[0];
221
- }
222
-
223
- static async deleteIntegrationForUserById(userId, integrationId) {
224
- const integrationMO = new Integration();
225
-
226
- const integrationList = await integrationMO.list({
227
- user: userId,
228
- _id: integrationId,
229
- });
230
- if (integrationList.length == 1) {
231
- await integrationMO.delete(integrationId);
232
- } else {
233
- throw new Error(
234
- `Integration with id of ${integrationId} does not exist for this user`
235
- );
236
- }
237
- }
238
-
239
- static async getIntegrationById(id) {
240
- const integrationMO = new Integration();
241
- return await integrationMO.get(id);
242
- }
243
-
244
- static async getFilteredIntegrationsForUserId(userId, filter) {
245
- const integrationMO = new Integration();
246
-
247
- const integrationList = await integrationMO.list({
248
- user: userId,
249
- ...filter,
250
- });
251
-
252
- return integrationList;
253
- }
254
-
255
- static async getCredentialById(credential_id) {
256
- const credentialMO = new Credential();
257
- return credentialMO.get(credential_id);
258
- }
259
-
260
- static async listCredentials(options) {
261
- const credentialMO = new Credential();
262
- return credentialMO.list(options);
263
- }
264
-
265
- static async getEntityById(entity_id) {
266
- const entityMO = new Entity();
267
- return entityMO.get(entity_id);
268
- }
269
-
270
- static async listEntities(options) {
271
- const entityMO = new Entity();
272
- return entityMO.list(options);
273
- }
274
-
275
- static async getInstanceFromIntegrationId(params) {
276
- const { integrationId } = params;
277
- const integration = await this.getIntegrationById(integrationId);
278
- const userId = integration.user;
279
-
280
- const instance = await this.getInstance({ userId, integrationId });
281
- instance.integration = integration;
282
-
283
- instance.primaryInstance =
284
- await this.EntityManagerClass.getEntityManagerInstanceFromEntityId(
285
- instance.integration.entities[0],
286
- instance.integration.user
287
- );
288
-
289
- instance.targetInstance =
290
- await this.EntityManagerClass.getEntityManagerInstanceFromEntityId(
291
- instance.integration.entities[1],
292
- instance.integration.user
293
- );
294
-
295
- return instance;
296
- }
297
-
298
- // Children must implement
299
- async processCreate() {
300
- throw new Error(
301
- 'processCreate method not implemented in child Manager'
302
- );
303
- }
304
-
305
- async processDelete() {
306
- throw new Error(
307
- 'processDelete method not implemented in child Manager'
308
- );
309
- }
310
-
311
- async processUpdate() {
312
- throw new Error(
313
- 'processUpdate method not implemented in child Manager'
314
- );
315
- }
316
-
317
- async getConfigOptions() {
318
- throw new Error(
319
- 'getConfigOptions method not implemented in child Manager'
320
- );
321
- }
322
-
323
- async getSampleData() {
324
- throw new Error(
325
- 'getSampleData method not implemented in child Manager'
326
- );
327
- }
328
- }
329
-
330
- module.exports = IntegrationManager;
@@ -1,190 +0,0 @@
1
- const Delegate = require('../Delegate');
2
- const Integration = require('@friggframework/models/Integration');
3
- const { get } = require('@friggframework/assertions');
4
-
5
- class Migrator extends Delegate {
6
- constructor(params) {
7
- super(params);
8
- this.integrationMO = new Integration();
9
- this.options = [];
10
- }
11
-
12
- static getInstance() {
13
- const instance = new this();
14
- return instance;
15
- }
16
-
17
- static getName() {
18
- return this.integrationManager.getName();
19
- }
20
-
21
- async migrate(params) {
22
- try {
23
- const fromVersion = get(params, 'fromVersion', null);
24
- const toVersion = get(params, 'toVersion');
25
-
26
- console.log(
27
- 'Migrate called. First validating whether it can be done.'
28
- );
29
- if (
30
- !this.integrationManager.Config.supportedVersions.some(
31
- (version) => version === toVersion
32
- )
33
- ) {
34
- return this.throwException(
35
- `Attempting to migrate to an unsupported version. Current supported versions are ${this.integrationManager.Config.supportedVersions.join(
36
- ', '
37
- )}`,
38
- 'Migration Error'
39
- );
40
- }
41
- const migrationOption = this.options
42
- .map((val) => val.get())
43
- .find(
44
- (option) =>
45
- option.fromVersion === fromVersion &&
46
- option.toVersion === toVersion
47
- );
48
- if (!migrationOption)
49
- return this.throwException(
50
- `No migration option found for version ${fromVersion} to ${toVersion}`,
51
- 'Migration Error'
52
- );
53
- // Run all general functions
54
- for (const generalFunct of migrationOption.generalFunctions) {
55
- console.log('Running general functions first');
56
- const res = await generalFunct();
57
- console.log(res);
58
- }
59
- // Get all integration records based on fromVersion
60
- const filter = {
61
- 'config.type': this.integrationManager.getName(),
62
- };
63
- console.log(
64
- `Retrieved all ${this.integrationManager.getName()} integrations`
65
- );
66
-
67
- const integrations = await this.integrationMO.list(filter);
68
- const filteredIntegrations = integrations.filter((int) => {
69
- const isNotToVersion = int.version !== toVersion;
70
- let isFromVersion = true;
71
- if (fromVersion && fromVersion !== '*') {
72
- isFromVersion = int.version === fromVersion;
73
- }
74
- return isNotToVersion && isFromVersion;
75
- });
76
- const results = {
77
- integrationType: this.integrationManager.getName(),
78
- totalIntegrations: integrations.length,
79
- versionReport: {
80
- startVersions: {},
81
- endVersions: {},
82
- },
83
- statusReport: {
84
- startStatuses: {},
85
- endStatuses: {},
86
- },
87
- toMigrate: filteredIntegrations.length,
88
- migrationResults: {
89
- success: 0,
90
- needsConfig: 0,
91
- error: 0,
92
- },
93
- };
94
-
95
- for (const integration of integrations) {
96
- if (results.versionReport.startVersions[integration.version]) {
97
- results.versionReport.startVersions[
98
- integration.version
99
- ] += 1;
100
- } else {
101
- results.versionReport.startVersions[
102
- integration.version
103
- ] = 1;
104
- }
105
- if (results.statusReport.startStatuses[integration.status]) {
106
- results.statusReport.startStatuses[integration.status] += 1;
107
- } else {
108
- results.statusReport.startStatuses[integration.status] = 1;
109
- }
110
- }
111
-
112
- // Instantiate the integrationManager based on integration ID, run all specific functions for each integration
113
- for (const integration of filteredIntegrations) {
114
- let integrationManagerInstance;
115
- try {
116
- integrationManagerInstance =
117
- await this.integrationManager.getInstanceFromIntegrationId(
118
- {
119
- integrationId: integration.id,
120
- userId: integration.user.id,
121
- }
122
- );
123
- } catch (e) {
124
- console.log(e);
125
- }
126
- // Test Auth
127
- if (integrationManagerInstance) {
128
- await integrationManagerInstance.testAuth();
129
-
130
- // Run functions
131
- if (
132
- integrationManagerInstance.integration.status !==
133
- 'ERROR'
134
- ) {
135
- for (const func of migrationOption.perIntegrationFunctions) {
136
- const res = await func(integrationManagerInstance);
137
- console.log(res);
138
- }
139
- }
140
-
141
- // Validate Config
142
- if (
143
- integrationManagerInstance.integration.status !==
144
- 'ERROR'
145
- ) {
146
- await integrationManagerInstance.validateConfig();
147
- }
148
-
149
- // Add to results tally
150
- const currentStatus =
151
- integrationManagerInstance.integration.status;
152
- if (currentStatus === 'ENABLED') {
153
- integrationManagerInstance.integration.version =
154
- toVersion;
155
- await integrationManagerInstance.integration.save();
156
- results.migrationResults.success += 1;
157
- }
158
- if (currentStatus === 'NEEDS_CONFIG') {
159
- integrationManagerInstance.integration.version =
160
- toVersion;
161
- await integrationManagerInstance.integration.save();
162
- results.migrationResults.needsConfig += 1;
163
- }
164
- if (currentStatus === 'ERROR')
165
- results.migrationResults.error += 1;
166
- }
167
- }
168
-
169
- const freshRetrieve = await this.integrationMO.list(filter);
170
- for (const int of freshRetrieve) {
171
- if (results.versionReport.endVersions[int.version]) {
172
- results.versionReport.endVersions[int.version] += 1;
173
- } else {
174
- results.versionReport.endVersions[int.version] = 1;
175
- }
176
- if (results.statusReport.endStatuses[int.status]) {
177
- results.statusReport.endStatuses[int.status] += 1;
178
- } else {
179
- results.statusReport.endStatuses[int.status] = 1;
180
- }
181
- }
182
-
183
- return results;
184
- } catch (e) {
185
- this.throwException(e.message, 'Migrate Error');
186
- }
187
- }
188
- }
189
-
190
- module.exports = Migrator;
@@ -1,178 +0,0 @@
1
- const Delegate = require('../Delegate');
2
- const Entity = require('@friggframework/models/Entity');
3
- const Credential = require('@friggframework/models/Credential');
4
- const { get } = require('@friggframework/assertions');
5
-
6
- class ModuleManager extends Delegate {
7
- static Entity = Entity;
8
- static Credential = Credential;
9
-
10
- constructor(params) {
11
- super(params);
12
- this.userId = get(params, 'userId');
13
-
14
- this.entityMO = new this.constructor.Entity();
15
- this.credentialMO = new this.constructor.Credential();
16
- }
17
-
18
- static getName() {
19
- throw new Error('Module name is not defined');
20
- }
21
-
22
- static async getInstance(params) {
23
- throw new Error(
24
- 'getInstance is not implemented. It is required for ModuleManager. '
25
- );
26
- }
27
-
28
- static async getEntitiesForUserId(userId) {
29
- const entityMO = new this.Entity();
30
- // Only return non-internal fields. Leverages "select" and "options" to non-excepted fields and a pure object.
31
- const list = await entityMO.list(
32
- { user: userId },
33
- '-dateCreated -dateUpdated -user -credentials -credential -__t -__v',
34
- { lean: true }
35
- );
36
- return list.map((entity) => ({
37
- id: entity._id,
38
- type: this.getName(),
39
- ...entity,
40
- }));
41
- }
42
-
43
- async getEntityId() {
44
- const list = await this.entityMO.list({ user: this.userId });
45
- if (list.length > 1) {
46
- throw new Error(
47
- 'There should not be more than one entity associated with a user for this specific class type'
48
- );
49
- }
50
- if (list.length == 0) {
51
- return null;
52
- }
53
- return list[0].id;
54
- }
55
-
56
- async validateAuthorizationRequirements() {
57
- const requirements = await this.getAuthorizationRequirements();
58
-
59
- if (
60
- (requirements.type === 'oauth1' ||
61
- requirements.type === 'oauth2') &&
62
- !requirements.url
63
- ) {
64
- return false;
65
- }
66
-
67
- return true;
68
- }
69
-
70
- async getAuthorizationRequirements(params) {
71
- // this function must return a dictionary with the following format
72
- // node only url key is required. Data would be used for Base Authentication
73
- // let returnData = {
74
- // url: "callback url for the data or teh redirect url for login",
75
- // type: one of the types defined in modules/Constants.js
76
- // data: ["required", "fields", "we", "may", "need"]
77
- // }
78
- throw new Error(
79
- 'Authorization requirements method getAuthorizationRequirements() is not defined in the class'
80
- );
81
- }
82
-
83
- async testAuth(params) {
84
- // this function must invoke a method on the API using authentication
85
- // if it fails, an exception should be thrown
86
- throw new Error(
87
- 'Authentication test method testAuth() is not defined in the class'
88
- );
89
- }
90
-
91
- async processAuthorizationCallback(params) {
92
- // this function takes in a dictionary of callback information along with
93
- // a unique user id to associate with the entity in the form of
94
- // {
95
- // userId: "some id",
96
- // data: {}
97
- // }
98
-
99
- throw new Error(
100
- 'Authorization requirements method processAuthorizationCallback() is not defined in the class'
101
- );
102
- }
103
-
104
- //----------------------------------------------------------------------------------------------------
105
- // optional
106
-
107
- async getEntityOptions() {
108
- // May not be needed if the callback already creates the entity, such as in situations
109
- // like HubSpot where the account is determined in the authorization flow.
110
- // This should only be used in situations such as FreshBooks where the user needs to make
111
- // an account decision on the front end.
112
- throw new Error(
113
- 'Entity requirement method getEntityOptions() is not defined in the class'
114
- );
115
- }
116
-
117
- async findOrCreateEntity(params) {
118
- // May not be needed if the callback already creates the entity, such as in situations
119
- // like HubSpot where the account is determined in the authorization flow.
120
- // This should only be used in situations such as FreshBooks where the user needs to make
121
- // an account decision on the front end.
122
- throw new Error(
123
- 'Entity requirement method findOrCreateEntity() is not defined in the class'
124
- );
125
- }
126
-
127
- async getAllSyncObjects(SyncClass) {
128
- // takes in a Sync class and will return all objects associated with the SyncClass in an array
129
- // in the form of
130
- // [
131
- // {...object1},{...object2}...
132
- // ]
133
-
134
- throw new Error(
135
- 'The method "getAllSyncObjects()" is not defined in the class'
136
- );
137
- }
138
-
139
- async batchCreateSyncObjects(syncObjects, syncManager) {
140
- // takes in an array of Sync objects that has two pieces of data that
141
- // are important to the updating module:
142
- // 1. obj.data -> The data mapped to the obj.keys data
143
- // 2. obj.syncId -> the id of the newly created sync object in our database. You will need to update
144
- // the sync object in the database with the your id associated with this data. You
145
- // can do this by calling the SyncManager function updateSyncObject.
146
- // [
147
- // syncObject1,syncObject2, ...
148
- // ]
149
-
150
- throw new Error(
151
- 'The method "batchUpdateSyncObjects()" is not defined in the class'
152
- );
153
- }
154
-
155
- async batchUpdateSyncObjects(syncObjects, syncManager) {
156
- // takes in an array of Sync objects that has two pieces of data that
157
- // are important to the updating module:
158
- // 1. obj.data -> The data mapped to the obj.keys data
159
- // 2. obj.moduleObjectIds[this.constructor.getName()] -> Indexed from the point of view of the module manager
160
- // it will return a json object holding all of the keys
161
- // required update this datapoint. an example would be:
162
- // {companyId:12, email:"test@test.com"}
163
- // [
164
- // syncObject1,syncObject2, ...
165
- // ]
166
-
167
- throw new Error(
168
- 'The method "batchUpdateSyncObjects()" is not defined in the class'
169
- );
170
- }
171
-
172
- async markCredentialsInvalid() {
173
- this.credential.auth_is_valid = false;
174
- return await this.credential.save();
175
- }
176
- }
177
-
178
- module.exports = ModuleManager;