@friggframework/core 2.0.0--canary.405.1f6792c.0 → 2.0.0--canary.396.6862738.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.
Files changed (59) hide show
  1. package/credential/credential-repository.js +9 -0
  2. package/credential/use-cases/get-credential-for-user.js +21 -0
  3. package/encrypt/encrypt.js +27 -4
  4. package/handlers/app-definition-loader.js +38 -0
  5. package/handlers/app-handler-helpers.js +0 -3
  6. package/handlers/backend-utils.js +29 -34
  7. package/handlers/routers/auth.js +14 -11
  8. package/handlers/routers/integration-defined-routers.js +8 -5
  9. package/handlers/routers/user.js +25 -5
  10. package/handlers/workers/integration-defined-workers.js +6 -3
  11. package/index.js +0 -11
  12. package/integrations/index.js +0 -5
  13. package/integrations/integration-base.js +10 -7
  14. package/integrations/integration-repository.js +44 -0
  15. package/integrations/integration-router.js +230 -132
  16. package/integrations/integration.js +233 -0
  17. package/integrations/options.js +1 -1
  18. package/integrations/use-cases/create-integration.js +58 -0
  19. package/integrations/use-cases/delete-integration-for-user.js +53 -0
  20. package/integrations/use-cases/get-integration-for-user.js +63 -0
  21. package/integrations/use-cases/get-integration-instance.js +73 -0
  22. package/integrations/use-cases/get-integrations-for-user.js +64 -0
  23. package/integrations/use-cases/index.js +11 -0
  24. package/integrations/use-cases/update-integration.js +81 -0
  25. package/integrations/utils/map-integration-dto.js +37 -0
  26. package/module-plugin/index.js +0 -4
  27. package/module-plugin/module-factory.js +13 -32
  28. package/module-plugin/module-repository.js +70 -0
  29. package/module-plugin/module-service.js +50 -0
  30. package/module-plugin/{auther.js → module.js} +109 -173
  31. package/module-plugin/test/mock-api/api.js +8 -3
  32. package/module-plugin/test/mock-api/definition.js +12 -8
  33. package/module-plugin/use-cases/get-entities-for-user.js +32 -0
  34. package/module-plugin/utils/map-module-dto.js +18 -0
  35. package/package.json +5 -5
  36. package/types/integrations/index.d.ts +2 -6
  37. package/types/module-plugin/index.d.ts +4 -21
  38. package/user/tests/doubles/test-user-repository.js +72 -0
  39. package/user/tests/use-cases/create-individual-user.test.js +24 -0
  40. package/user/tests/use-cases/create-organization-user.test.js +28 -0
  41. package/user/tests/use-cases/create-token-for-user-id.test.js +19 -0
  42. package/user/tests/use-cases/get-user-from-bearer-token.test.js +64 -0
  43. package/user/tests/use-cases/login-user.test.js +140 -0
  44. package/user/use-cases/create-individual-user.js +61 -0
  45. package/user/use-cases/create-organization-user.js +47 -0
  46. package/user/use-cases/create-token-for-user-id.js +30 -0
  47. package/user/use-cases/get-user-from-bearer-token.js +77 -0
  48. package/user/use-cases/login-user.js +122 -0
  49. package/user/user-repository.js +62 -0
  50. package/user/user.js +77 -0
  51. package/handlers/routers/HEALTHCHECK.md +0 -240
  52. package/handlers/routers/health.js +0 -459
  53. package/handlers/routers/health.test.js +0 -203
  54. package/handlers/routers/middleware/loadUser.js +0 -15
  55. package/handlers/routers/middleware/requireLoggedInUser.js +0 -12
  56. package/integrations/create-frigg-backend.js +0 -31
  57. package/integrations/integration-factory.js +0 -251
  58. package/integrations/integration-user.js +0 -144
  59. package/module-plugin/entity-manager.js +0 -70
@@ -0,0 +1,9 @@
1
+ const { Credential } = require('../module-plugin');
2
+
3
+ class CredentialRepository {
4
+ async findCredentialById(id) {
5
+ return Credential.findById(id);
6
+ }
7
+ }
8
+
9
+ module.exports = { CredentialRepository };
@@ -0,0 +1,21 @@
1
+ class GetCredentialForUser {
2
+ constructor({ credentialRepository }) {
3
+ this.credentialRepository = credentialRepository;
4
+ }
5
+
6
+ async execute(credentialId, userId) {
7
+ const credential = await this.credentialRepository.findCredentialById(credentialId);
8
+
9
+ if (!credential) {
10
+ throw new Error(`Credential with id ${credentialId} not found`);
11
+ }
12
+
13
+ if (credential.user.toString() !== userId.toString()) {
14
+ throw new Error(`Credential ${credentialId} does not belong to user ${userId}`);
15
+ }
16
+
17
+ return credential;
18
+ }
19
+ }
20
+
21
+ module.exports = { GetCredentialForUser };
@@ -17,6 +17,7 @@ const findOneEvents = [
17
17
  const shouldBypassEncryption = (STAGE) => {
18
18
  const defaultBypassStages = ['dev', 'test', 'local'];
19
19
  const bypassStageEnv = process.env.BYPASS_ENCRYPTION_STAGE;
20
+ // If the env is set to anything or an empty string, use the env. Otherwise, use the default array
20
21
  const useEnv = !String(bypassStageEnv) || !!bypassStageEnv;
21
22
  const bypassStages = useEnv
22
23
  ? bypassStageEnv.split(',').map((stage) => stage.trim())
@@ -24,15 +25,19 @@ const shouldBypassEncryption = (STAGE) => {
24
25
  return bypassStages.includes(STAGE);
25
26
  };
26
27
 
27
- function Encrypt(schema) {
28
+ // The Mongoose plug-in function
29
+ function Encrypt(schema, options) {
28
30
  const { STAGE, KMS_KEY_ARN, AES_KEY_ID } = process.env;
29
31
 
30
32
  if (shouldBypassEncryption(STAGE)) {
31
33
  return;
32
34
  }
33
35
 
34
- const hasAES = AES_KEY_ID && AES_KEY_ID.trim() !== '';
35
- const hasKMS = KMS_KEY_ARN && KMS_KEY_ARN.trim() !== '' && !hasAES;
36
+ if (KMS_KEY_ARN && AES_KEY_ID) {
37
+ throw new Error(
38
+ 'Local and AWS encryption keys are both set in the environment.'
39
+ );
40
+ }
36
41
 
37
42
  const fields = Object.values(schema.paths)
38
43
  .map(({ path, options }) => (options.lhEncrypt === true ? path : ''))
@@ -43,17 +48,25 @@ function Encrypt(schema) {
43
48
  }
44
49
 
45
50
  const cryptor = new Cryptor({
46
- shouldUseAws: hasKMS,
51
+ // Use AWS if the CMK is present
52
+ shouldUseAws: !!KMS_KEY_ARN,
53
+ // Find all the fields in the schema with lhEncrypt === true
47
54
  fields: fields,
48
55
  });
49
56
 
57
+ // ---------------------------------------------
58
+ // ### Encrypt fields before save/update/insert.
59
+ // ---------------------------------------------
60
+
50
61
  schema.pre('save', async function encryptionPreSave() {
62
+ // `this` will be a doc
51
63
  await cryptor.encryptFieldsInDocuments([this]);
52
64
  });
53
65
 
54
66
  schema.pre(
55
67
  'insertMany',
56
68
  async function encryptionPreInsertMany(_, docs, options) {
69
+ // `this` will be the model
57
70
  if (options?.rawResult) {
58
71
  throw new Error(
59
72
  'Raw result not supported for insertMany with Encrypt plugin'
@@ -65,14 +78,17 @@ function Encrypt(schema) {
65
78
  );
66
79
 
67
80
  schema.pre(updateOneEvents, async function encryptionPreUpdateOne() {
81
+ // `this` will be a query
68
82
  await cryptor.encryptFieldsInQuery(this);
69
83
  });
70
84
 
71
85
  schema.pre('updateMany', async function encryptionPreUpdateMany() {
86
+ // `this` will be a query
72
87
  cryptor.expectNotToUpdateManyEncrypted(this.getUpdate());
73
88
  });
74
89
 
75
90
  schema.pre('update', async function encryptionPreUpdate() {
91
+ // `this` will be a query
76
92
  const { multiple } = this.getOptions();
77
93
 
78
94
  if (multiple) {
@@ -83,11 +99,16 @@ function Encrypt(schema) {
83
99
  await cryptor.encryptFieldsInQuery(this);
84
100
  });
85
101
 
102
+ // --------------------------------------------
103
+ // ### Decrypt documents after they are loaded.
104
+ // --------------------------------------------
86
105
  schema.post('save', async function encryptionPreSave() {
106
+ // `this` will be a doc
87
107
  await cryptor.decryptFieldsInDocuments([this]);
88
108
  });
89
109
 
90
110
  schema.post(findOneEvents, async function encryptionPostFindOne(doc) {
111
+ // `this` will be a query
91
112
  const { rawResult } = this.getOptions();
92
113
 
93
114
  if (rawResult) {
@@ -98,10 +119,12 @@ function Encrypt(schema) {
98
119
  });
99
120
 
100
121
  schema.post('find', async function encryptionPostFind(docs) {
122
+ // `this` will be a query
101
123
  await cryptor.decryptFieldsInDocuments(docs);
102
124
  });
103
125
 
104
126
  schema.post('insertMany', async function encryptionPostInsertMany(docs) {
127
+ // `this` will be the model
105
128
  await cryptor.decryptFieldsInDocuments(docs);
106
129
  });
107
130
  }
@@ -0,0 +1,38 @@
1
+ const { findNearestBackendPackageJson } = require('@friggframework/core/utils');
2
+ const path = require('node:path');
3
+ const fs = require('fs-extra');
4
+
5
+ /**
6
+ * Loads the App definition from the nearest backend package
7
+ * @function loadAppDefinition
8
+ * @description Searches for the nearest backend package.json, loads the corresponding index.js file,
9
+ * and extracts the application definition containing integrations and user configuration.
10
+ * @returns {{integrations: Array<object>, userConfig: object | null}} An object containing the application definition.
11
+ * @throws {Error} Throws error if backend package.json cannot be found.
12
+ * @throws {Error} Throws error if index.js file cannot be found in the backend directory.
13
+ * @example
14
+ * const { integrations, userConfig } = loadAppDefinition();
15
+ * console.log(`Found ${integrations.length} integrations`);
16
+ */
17
+ function loadAppDefinition() {
18
+ const backendPath = findNearestBackendPackageJson();
19
+ if (!backendPath) {
20
+ throw new Error('Could not find backend package.json');
21
+ }
22
+
23
+ const backendDir = path.dirname(backendPath);
24
+ const backendFilePath = path.join(backendDir, 'index.js');
25
+ if (!fs.existsSync(backendFilePath)) {
26
+ throw new Error('Could not find index.js');
27
+ }
28
+
29
+ const backendJsFile = require(backendFilePath);
30
+ const appDefinition = backendJsFile.Definition;
31
+
32
+ const { integrations = [], user: userConfig = null } = appDefinition;
33
+ return { integrations, userConfig };
34
+ }
35
+
36
+ module.exports = {
37
+ loadAppDefinition,
38
+ };
@@ -3,7 +3,6 @@ const express = require('express');
3
3
  const bodyParser = require('body-parser');
4
4
  const cors = require('cors');
5
5
  const Boom = require('@hapi/boom');
6
- const loadUserManager = require('./routers/middleware/loadUser');
7
6
  const serverlessHttp = require('serverless-http');
8
7
 
9
8
  const createApp = (applyMiddleware) => {
@@ -20,8 +19,6 @@ const createApp = (applyMiddleware) => {
20
19
  })
21
20
  );
22
21
 
23
- app.use(loadUserManager);
24
-
25
22
  if (applyMiddleware) applyMiddleware(app);
26
23
 
27
24
  // Handle sending error response and logging server errors to console
@@ -1,24 +1,10 @@
1
- const { createFriggBackend, Worker } = require('@friggframework/core');
2
- const { findNearestBackendPackageJson } = require('@friggframework/core/utils');
3
- const path = require('node:path');
4
- const fs = require('fs-extra');
5
-
6
- const backendPath = findNearestBackendPackageJson();
7
- if (!backendPath) {
8
- throw new Error('Could not find backend package.json');
9
- }
10
-
11
- const backendDir = path.dirname(backendPath);
12
- const backendFilePath = path.join(backendDir, 'index.js');
13
- if (!fs.existsSync(backendFilePath)) {
14
- throw new Error('Could not find index.js');
15
- }
16
-
17
- const backendJsFile = require(backendFilePath);
18
1
  const { Router } = require('express');
19
- const appDefinition = backendJsFile.Definition;
2
+ const { Worker } = require('@friggframework/core');
3
+ const { loadAppDefinition } = require('./app-definition-loader');
4
+ const { IntegrationRepository } = require('../integrations/integration-repository');
5
+ const { ModuleService } = require('../module-plugin/module-service');
6
+ const { GetIntegrationInstance } = require('../integrations/use-cases/get-integration-instance');
20
7
 
21
- const backend = createFriggBackend(appDefinition);
22
8
  const loadRouterFromObject = (IntegrationClass, routerObject) => {
23
9
  const router = Router();
24
10
  const { path, method, event } = routerObject;
@@ -27,10 +13,10 @@ const loadRouterFromObject = (IntegrationClass, routerObject) => {
27
13
  );
28
14
  router[method.toLowerCase()](path, async (req, res, next) => {
29
15
  try {
30
- const integration = new IntegrationClass({});
16
+ const integration = new IntegrationClass();
31
17
  await integration.loadModules();
32
18
  await integration.registerEventHandlers();
33
- const result = await integration.send(event, {req, res, next});
19
+ const result = await integration.send(event, { req, res, next });
34
20
  res.json(result);
35
21
  } catch (error) {
36
22
  next(error);
@@ -39,29 +25,39 @@ const loadRouterFromObject = (IntegrationClass, routerObject) => {
39
25
 
40
26
  return router;
41
27
  };
42
- const createQueueWorker = (integrationClass, integrationFactory) => {
28
+
29
+ //todo: this should be in a use case class
30
+ const createQueueWorker = (integrationClass) => {
43
31
  class QueueWorker extends Worker {
44
32
  async _run(params, context) {
45
33
  try {
46
- let instance;
34
+ let integrationInstance;
47
35
  if (!params.integrationId) {
48
- instance = new integrationClass({});
49
- await instance.loadModules();
50
- // await instance.loadUserActions();
51
- await instance.registerEventHandlers();
36
+ integrationInstance = new integrationClass();
37
+ await integrationInstance.loadModules();
38
+ await integrationInstance.registerEventHandlers();
52
39
  console.log(
53
40
  `${params.event} for ${integrationClass.Definition.name} integration with no integrationId`
54
41
  );
55
42
  } else {
56
- instance =
57
- await integrationFactory.getInstanceFromIntegrationId({
58
- integrationId: params.integrationId,
59
- });
43
+ const { integrations: integrationClasses } = loadAppDefinition();
44
+ const integrationRepository = new IntegrationRepository();
45
+ const moduleService = new ModuleService();
46
+
47
+ const getIntegrationInstance = new GetIntegrationInstance({
48
+ integrationRepository,
49
+ integrationClasses,
50
+ moduleService,
51
+ });
52
+
53
+ // todo: are we going to have the userId available here?
54
+ integrationInstance = await getIntegrationInstance.execute(params.integrationId, params.userId);
60
55
  console.log(
61
- `${params.event} for ${instance.record.config.type} of integrationId: ${params.integrationId}`
56
+ `${params.event} for ${integrationInstance.record.config.type} of integrationId: ${params.integrationId}`
62
57
  );
63
58
  }
64
- const res = await instance.send(params.event, {
59
+
60
+ const res = await integrationInstance.send(params.event, {
65
61
  data: params.data,
66
62
  context,
67
63
  });
@@ -79,7 +75,6 @@ const createQueueWorker = (integrationClass, integrationFactory) => {
79
75
  };
80
76
 
81
77
  module.exports = {
82
- ...backend,
83
78
  loadRouterFromObject,
84
79
  createQueueWorker,
85
80
  };
@@ -1,26 +1,29 @@
1
1
  const { createIntegrationRouter } = require('@friggframework/core');
2
2
  const { createAppHandler } = require('./../app-handler-helpers');
3
- const { requireLoggedInUser } = require('./middleware/requireLoggedInUser');
4
3
  const {
5
- moduleFactory,
6
- integrationFactory,
7
- IntegrationHelper,
8
- } = require('./../backend-utils');
4
+ loadAppDefinition,
5
+ } = require('../app-definition-loader');
6
+ const { UserRepository } = require('../../user/user-repository');
7
+ const { GetUserFromBearerToken } = require('../../user/use-cases/get-user-from-bearer-token');
8
+
9
+ const { userConfig } = loadAppDefinition();
10
+ const userRepository = new UserRepository({ userConfig });
11
+ const getUserFromBearerToken = new GetUserFromBearerToken({
12
+ userRepository,
13
+ userConfig,
14
+ });
9
15
 
10
16
  const router = createIntegrationRouter({
11
- factory: { moduleFactory, integrationFactory, IntegrationHelper },
12
- requireLoggedInUser,
13
- getUserId: (req) => req.user.getUserId(),
17
+ getUserFromBearerToken,
14
18
  });
15
19
 
16
20
  router.route('/redirect/:appId').get((req, res) => {
17
21
  res.redirect(
18
- `${process.env.FRONTEND_URI}/redirect/${
19
- req.params.appId
22
+ `${process.env.FRONTEND_URI}/redirect/${req.params.appId
20
23
  }?${new URLSearchParams(req.query)}`
21
24
  );
22
25
  });
23
26
 
24
27
  const handler = createAppHandler('HTTP Event: Auth', router);
25
28
 
26
- module.exports = { handler, router };
29
+ module.exports = { handler };
@@ -1,15 +1,18 @@
1
1
  const { createAppHandler } = require('./../app-handler-helpers');
2
2
  const {
3
- integrationFactory,
4
- loadRouterFromObject,
5
- } = require('./../backend-utils');
3
+ loadAppDefinition,
4
+ } = require('../app-definition-loader');
6
5
  const { Router } = require('express');
6
+ const { loadRouterFromObject } = require('../backend-utils');
7
7
 
8
8
  const handlers = {};
9
- for (const IntegrationClass of integrationFactory.integrationClasses) {
9
+ const { integrations: integrationClasses } = loadAppDefinition();
10
+
11
+ //todo: this should be in a use case class
12
+ for (const IntegrationClass of integrationClasses) {
10
13
  const router = Router();
11
14
  const basePath = `/api/${IntegrationClass.Definition.name}-integration`;
12
-
15
+
13
16
  console.log(`\n│ Configuring routes for ${IntegrationClass.Definition.name} Integration:`);
14
17
 
15
18
  for (const routeDef of IntegrationClass.Definition.routes) {
@@ -1,10 +1,29 @@
1
1
  const express = require('express');
2
2
  const { createAppHandler } = require('../app-handler-helpers');
3
3
  const { checkRequiredParams } = require('@friggframework/core');
4
- const { User } = require('../backend-utils');
4
+ const { UserRepository } = require('../../user/user-repository');
5
+ const {
6
+ CreateIndividualUser,
7
+ } = require('../../user/use-cases/create-individual-user');
8
+ const { LoginUser } = require('../../user/use-cases/login-user');
9
+ const {
10
+ CreateTokenForUserId,
11
+ } = require('../../user/use-cases/create-token-for-user-id');
5
12
  const catchAsyncError = require('express-async-handler');
13
+ const { loadAppDefinition } = require('../app-definition-loader');
6
14
 
7
15
  const router = express();
16
+ const { userConfig } = loadAppDefinition();
17
+ const userRepository = new UserRepository({ userConfig });
18
+ const createIndividualUser = new CreateIndividualUser({
19
+ userRepository,
20
+ userConfig,
21
+ });
22
+ const loginUser = new LoginUser({
23
+ userRepository,
24
+ userConfig,
25
+ });
26
+ const createTokenForUserId = new CreateTokenForUserId({ userRepository });
8
27
 
9
28
  // define the login endpoint
10
29
  router.route('/user/login').post(
@@ -13,8 +32,8 @@ router.route('/user/login').post(
13
32
  'username',
14
33
  'password',
15
34
  ]);
16
- const user = await User.loginUser({ username, password });
17
- const token = await user.createUserToken(120);
35
+ const user = await loginUser.execute({ username, password });
36
+ const token = await createTokenForUserId.execute(user.getId(), 120);
18
37
  res.status(201);
19
38
  res.json({ token });
20
39
  })
@@ -26,11 +45,12 @@ router.route('/user/create').post(
26
45
  'username',
27
46
  'password',
28
47
  ]);
29
- const user = await User.createIndividualUser({
48
+
49
+ const user = await createIndividualUser.execute({
30
50
  username,
31
51
  password,
32
52
  });
33
- const token = await user.createUserToken(120);
53
+ const token = await createTokenForUserId.execute(user.getId(), 120);
34
54
  res.status(201);
35
55
  res.json({ token });
36
56
  })
@@ -1,9 +1,12 @@
1
1
  const { createHandler } = require('@friggframework/core');
2
- const { integrationFactory, createQueueWorker } = require('../backend-utils');
2
+ const { loadAppDefinition } = require('../app-definition-loader');
3
+ const { createQueueWorker } = require('../backend-utils');
3
4
 
4
5
  const handlers = {};
5
- integrationFactory.integrationClasses.forEach((IntegrationClass) => {
6
- const defaultQueueWorker = createQueueWorker(IntegrationClass, integrationFactory);
6
+ const { integrations: integrationClasses } = loadAppDefinition();
7
+
8
+ integrationClasses.forEach((IntegrationClass) => {
9
+ const defaultQueueWorker = createQueueWorker(IntegrationClass);
7
10
 
8
11
  handlers[`${IntegrationClass.Definition.name}`] = {
9
12
  queueWorker: createHandler({
package/index.js CHANGED
@@ -38,17 +38,13 @@ const {
38
38
  IntegrationModel,
39
39
  Options,
40
40
  IntegrationMapping,
41
- IntegrationFactory,
42
- IntegrationHelper,
43
41
  createIntegrationRouter,
44
42
  checkRequiredParams,
45
- createFriggBackend,
46
43
  } = require('./integrations/index');
47
44
  const { TimeoutCatcher } = require('./lambda/index');
48
45
  const { debug, initDebugLog, flushDebugLog } = require('./logs/index');
49
46
  const {
50
47
  Credential,
51
- EntityManager,
52
48
  Entity,
53
49
  ModuleManager,
54
50
  ApiKeyRequester,
@@ -57,7 +53,6 @@ const {
57
53
  Requester,
58
54
  ModuleConstants,
59
55
  ModuleFactory,
60
- Auther,
61
56
  } = require('./module-plugin/index');
62
57
  const utils = require('./utils');
63
58
 
@@ -109,11 +104,8 @@ module.exports = {
109
104
  IntegrationModel,
110
105
  Options,
111
106
  IntegrationMapping,
112
- IntegrationFactory,
113
- IntegrationHelper,
114
107
  checkRequiredParams,
115
108
  createIntegrationRouter,
116
- createFriggBackend,
117
109
 
118
110
  // lambda
119
111
  TimeoutCatcher,
@@ -125,7 +117,6 @@ module.exports = {
125
117
 
126
118
  // module plugin
127
119
  Credential,
128
- EntityManager,
129
120
  Entity,
130
121
  ModuleManager,
131
122
  ApiKeyRequester,
@@ -134,8 +125,6 @@ module.exports = {
134
125
  Requester,
135
126
  ModuleConstants,
136
127
  ModuleFactory,
137
- Auther,
138
-
139
128
  // queues
140
129
  QueuerUtil,
141
130
 
@@ -2,18 +2,13 @@ const { IntegrationBase } = require('./integration-base');
2
2
  const { IntegrationModel } = require('./integration-model');
3
3
  const { Options } = require('./options');
4
4
  const { IntegrationMapping } = require('./integration-mapping');
5
- const { IntegrationFactory, IntegrationHelper } = require('./integration-factory');
6
5
  const { createIntegrationRouter, checkRequiredParams } = require('./integration-router');
7
- const { createFriggBackend } = require('./create-frigg-backend');
8
6
 
9
7
  module.exports = {
10
8
  IntegrationBase,
11
9
  IntegrationModel,
12
10
  Options,
13
11
  IntegrationMapping,
14
- IntegrationFactory,
15
- IntegrationHelper,
16
12
  createIntegrationRouter,
17
13
  checkRequiredParams,
18
- createFriggBackend
19
14
  };
@@ -1,5 +1,6 @@
1
1
  const { IntegrationMapping } = require('./integration-mapping');
2
2
  const { Options } = require('./options');
3
+
3
4
  const constantsToBeMigrated = {
4
5
  defaultEvents: {
5
6
  ON_CREATE: 'ON_CREATE',
@@ -19,6 +20,7 @@ const constantsToBeMigrated = {
19
20
  };
20
21
 
21
22
  class IntegrationBase {
23
+
22
24
  static getOptionDetails() {
23
25
  const options = new Options({
24
26
  module: Object.values(this.Definition.modules)[0], // This is a placeholder until we revamp the frontend
@@ -26,6 +28,7 @@ class IntegrationBase {
26
28
  });
27
29
  return options.get();
28
30
  }
31
+
29
32
  /**
30
33
  * CHILDREN SHOULD SPECIFY A DEFINITION FOR THE INTEGRATION
31
34
  */
@@ -57,7 +60,7 @@ class IntegrationBase {
57
60
  const { definition } =
58
61
  this.constructor.Definition.modules[moduleName];
59
62
  if (typeof definition.API === 'function') {
60
- this[moduleName] = { api: new definition.API() };
63
+ this[moduleName] = { api: new definition.API({}) };
61
64
  } else {
62
65
  throw new Error(
63
66
  `Module ${moduleName} must be a function that extends IntegrationModule`
@@ -197,9 +200,9 @@ class IntegrationBase {
197
200
  return this.record;
198
201
  }
199
202
 
200
- async onUpdate(params) {}
203
+ async onUpdate(params) { }
201
204
 
202
- async onDelete(params) {}
205
+ async onDelete(params) { }
203
206
 
204
207
  async getConfigOptions() {
205
208
  const options = {
@@ -236,10 +239,10 @@ class IntegrationBase {
236
239
  const dynamicUserActions = await this.loadDynamicUserActions();
237
240
  const filteredDynamicActions = actionType
238
241
  ? Object.fromEntries(
239
- Object.entries(dynamicUserActions).filter(
240
- ([_, event]) => event.userActionType === actionType
241
- )
242
- )
242
+ Object.entries(dynamicUserActions).filter(
243
+ ([_, event]) => event.userActionType === actionType
244
+ )
245
+ )
243
246
  : dynamicUserActions;
244
247
  return { ...userActions, ...filteredDynamicActions };
245
248
  }
@@ -0,0 +1,44 @@
1
+ const { IntegrationModel } = require('./integration-model');
2
+
3
+ class IntegrationRepository {
4
+ async findIntegrationsByUserId(userId) {
5
+ const integrationRecords = await IntegrationModel.find({ user: userId }, '', { lean: true }).populate('entities');
6
+ return integrationRecords.map(integrationRecord => ({
7
+ id: integrationRecord._id,
8
+ entitiesIds: integrationRecord.entities.map(e => e._id),
9
+ userId: integrationRecord.user.toString(),
10
+ config: integrationRecord.config,
11
+ version: integrationRecord.version,
12
+ status: integrationRecord.status,
13
+ messages: integrationRecord.messages,
14
+ }));
15
+ }
16
+
17
+ async deleteIntegrationById(integrationId) {
18
+ return IntegrationModel.deleteOne({ _id: integrationId });
19
+ }
20
+
21
+ async findIntegrationById(id) {
22
+ const integrationRecord = await IntegrationModel.findById(id, '', { lean: true }).populate('entities');
23
+ return {
24
+ id: integrationRecord._id,
25
+ entitiesIds: integrationRecord.entities.map(e => e._id),
26
+ userId: integrationRecord.user.toString(),
27
+ config: integrationRecord.config,
28
+ version: integrationRecord.version,
29
+ status: integrationRecord.status,
30
+ messages: integrationRecord.messages,
31
+ }
32
+ }
33
+
34
+ async createIntegration(entities, userId, config) {
35
+ return IntegrationModel.create({
36
+ entities: entities,
37
+ user: userId,
38
+ config,
39
+ version: '0.0.0',
40
+ });
41
+ }
42
+ }
43
+
44
+ module.exports = { IntegrationRepository };