@flowerforce/flowerbase 1.0.1-beta.9 → 1.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 (178) hide show
  1. package/CHANGELOG.md +17 -0
  2. package/LICENSE +1 -1
  3. package/README.md +466 -7
  4. package/dist/auth/controller.d.ts.map +1 -1
  5. package/dist/auth/controller.js +11 -1
  6. package/dist/auth/providers/local-userpass/controller.d.ts.map +1 -1
  7. package/dist/auth/providers/local-userpass/controller.js +15 -15
  8. package/dist/auth/utils.d.ts +2 -1
  9. package/dist/auth/utils.d.ts.map +1 -1
  10. package/dist/auth/utils.js +14 -10
  11. package/dist/constants.d.ts.map +1 -1
  12. package/dist/constants.js +3 -3
  13. package/dist/features/endpoints/utils.d.ts +1 -1
  14. package/dist/features/endpoints/utils.d.ts.map +1 -1
  15. package/dist/features/endpoints/utils.js +5 -2
  16. package/dist/features/functions/controller.d.ts.map +1 -1
  17. package/dist/features/functions/controller.js +12 -8
  18. package/dist/features/functions/dtos.d.ts +2 -1
  19. package/dist/features/functions/dtos.d.ts.map +1 -1
  20. package/dist/features/functions/interface.d.ts +2 -1
  21. package/dist/features/functions/interface.d.ts.map +1 -1
  22. package/dist/features/functions/utils.d.ts +1 -1
  23. package/dist/features/functions/utils.d.ts.map +1 -1
  24. package/dist/features/functions/utils.js +4 -4
  25. package/dist/features/triggers/index.d.ts.map +1 -1
  26. package/dist/features/triggers/index.js +9 -3
  27. package/dist/features/triggers/interface.d.ts +4 -4
  28. package/dist/features/triggers/interface.d.ts.map +1 -1
  29. package/dist/features/triggers/utils.d.ts.map +1 -1
  30. package/dist/features/triggers/utils.js +25 -14
  31. package/dist/global.d.ts +9 -0
  32. package/dist/global.d.ts.map +1 -0
  33. package/dist/global.js +2 -0
  34. package/dist/index.d.ts +1 -1
  35. package/dist/index.d.ts.map +1 -1
  36. package/dist/index.js +13 -9
  37. package/dist/model.d.ts +1 -0
  38. package/dist/model.d.ts.map +1 -1
  39. package/dist/model.js +15 -0
  40. package/dist/services/api/index.d.ts.map +1 -1
  41. package/dist/services/api/index.js +6 -1
  42. package/dist/services/aws/index.d.ts.map +1 -1
  43. package/dist/services/aws/index.js +5 -5
  44. package/dist/services/index.d.ts.map +1 -1
  45. package/dist/services/mongodb-atlas/index.d.ts.map +1 -1
  46. package/dist/services/mongodb-atlas/index.js +76 -71
  47. package/dist/services/mongodb-atlas/model.d.ts +3 -3
  48. package/dist/services/mongodb-atlas/model.d.ts.map +1 -1
  49. package/dist/services/mongodb-atlas/utils.d.ts.map +1 -1
  50. package/dist/state.d.ts +2 -2
  51. package/dist/state.d.ts.map +1 -1
  52. package/dist/utils/context/helpers.d.ts +4 -4
  53. package/dist/utils/context/helpers.d.ts.map +1 -1
  54. package/dist/utils/context/helpers.js +1 -1
  55. package/dist/utils/context/index.d.ts.map +1 -1
  56. package/dist/utils/context/index.js +3 -5
  57. package/dist/utils/helpers/someAsync.d.ts.map +1 -1
  58. package/dist/utils/initializer/exposeRoutes.d.ts.map +1 -1
  59. package/dist/utils/initializer/exposeRoutes.js +44 -1
  60. package/dist/utils/initializer/registerPlugins.d.ts.map +1 -1
  61. package/dist/utils/initializer/registerPlugins.js +9 -9
  62. package/dist/utils/roles/helpers.d.ts.map +1 -1
  63. package/dist/utils/roles/helpers.js +9 -7
  64. package/dist/utils/roles/interface.d.ts.map +1 -1
  65. package/dist/utils/roles/machines/commonValidators.d.ts +2 -2
  66. package/dist/utils/roles/machines/commonValidators.d.ts.map +1 -1
  67. package/dist/utils/roles/machines/commonValidators.js +5 -6
  68. package/dist/utils/roles/machines/index.d.ts.map +1 -1
  69. package/dist/utils/roles/machines/interface.d.ts.map +1 -1
  70. package/dist/utils/roles/machines/machine.d.ts +3 -3
  71. package/dist/utils/roles/machines/machine.d.ts.map +1 -1
  72. package/dist/utils/roles/machines/machine.js +12 -4
  73. package/dist/utils/roles/machines/read/A/index.d.ts.map +1 -1
  74. package/dist/utils/roles/machines/read/A/index.js +12 -2
  75. package/dist/utils/roles/machines/read/B/index.d.ts.map +1 -1
  76. package/dist/utils/roles/machines/read/B/index.js +20 -5
  77. package/dist/utils/roles/machines/read/C/index.d.ts.map +1 -1
  78. package/dist/utils/roles/machines/read/C/index.js +20 -5
  79. package/dist/utils/roles/machines/read/D/index.d.ts.map +1 -1
  80. package/dist/utils/roles/machines/read/D/index.js +13 -3
  81. package/dist/utils/roles/machines/read/D/validators.d.ts +1 -1
  82. package/dist/utils/roles/machines/read/D/validators.d.ts.map +1 -1
  83. package/dist/utils/roles/machines/read/D/validators.js +8 -4
  84. package/dist/utils/roles/machines/utils.d.ts +4 -4
  85. package/dist/utils/roles/machines/utils.d.ts.map +1 -1
  86. package/dist/utils/roles/machines/utils.js +5 -1
  87. package/dist/utils/roles/machines/write/A/index.d.ts.map +1 -1
  88. package/dist/utils/roles/machines/write/A/index.js +13 -3
  89. package/dist/utils/roles/machines/write/B/index.d.ts.map +1 -1
  90. package/dist/utils/roles/machines/write/B/index.js +37 -10
  91. package/dist/utils/roles/machines/write/C/index.d.ts.map +1 -1
  92. package/dist/utils/roles/machines/write/C/index.js +13 -3
  93. package/dist/utils/roles/machines/write/C/validators.d.ts +1 -1
  94. package/dist/utils/roles/machines/write/C/validators.d.ts.map +1 -1
  95. package/dist/utils/roles/machines/write/C/validators.js +8 -4
  96. package/dist/utils/rules-matcher/interface.d.ts.map +1 -1
  97. package/dist/utils/rules-matcher/utils.d.ts.map +1 -1
  98. package/dist/utils/rules.d.ts.map +1 -1
  99. package/package.json +9 -2
  100. package/src/auth/controller.ts +12 -1
  101. package/src/auth/providers/local-userpass/controller.ts +47 -39
  102. package/src/auth/providers/local-userpass/dtos.ts +1 -1
  103. package/src/auth/utils.ts +24 -18
  104. package/src/constants.ts +7 -3
  105. package/src/features/endpoints/utils.ts +6 -4
  106. package/src/features/functions/controller.ts +23 -22
  107. package/src/features/functions/dtos.ts +9 -9
  108. package/src/features/functions/interface.ts +2 -1
  109. package/src/features/functions/utils.ts +12 -12
  110. package/src/features/triggers/index.ts +9 -6
  111. package/src/features/triggers/interface.ts +9 -10
  112. package/src/features/triggers/utils.ts +57 -29
  113. package/src/global.ts +9 -0
  114. package/src/index.ts +16 -11
  115. package/src/model.ts +3 -1
  116. package/src/services/api/index.ts +6 -1
  117. package/src/services/aws/index.ts +19 -17
  118. package/src/services/mongodb-atlas/index.ts +204 -163
  119. package/src/services/mongodb-atlas/model.ts +13 -13
  120. package/src/services/mongodb-atlas/utils.ts +6 -4
  121. package/src/state.ts +32 -20
  122. package/src/utils/__tests__/STEP_A_STATES.test.ts +78 -47
  123. package/src/utils/__tests__/STEP_B_STATES.test.ts +168 -105
  124. package/src/utils/__tests__/STEP_C_STATES.test.ts +150 -78
  125. package/src/utils/__tests__/STEP_D_STATES.test.ts +129 -86
  126. package/src/utils/__tests__/checkAdditionalFieldsFn.test.ts +35 -35
  127. package/src/utils/__tests__/checkApplyWhen.test.ts +40 -41
  128. package/src/utils/__tests__/checkFieldsPropertyExists.test.ts +40 -40
  129. package/src/utils/__tests__/checkIsValidFieldNameFn.test.ts +185 -184
  130. package/src/utils/__tests__/comparePassword.test.ts +27 -30
  131. package/src/utils/__tests__/evaluateDocumentsFiltersReadFn.test.ts +55 -47
  132. package/src/utils/__tests__/evaluateDocumentsFiltersWriteFn.test.ts +61 -47
  133. package/src/utils/__tests__/evaluateTopLevelReadFn.test.ts +48 -48
  134. package/src/utils/__tests__/evaluateTopLevelWriteFn.test.ts +56 -56
  135. package/src/utils/__tests__/exposeRoutes.test.ts +46 -44
  136. package/src/utils/__tests__/generateContextData.test.ts +57 -51
  137. package/src/utils/__tests__/getDefaultRule.test.ts +32 -27
  138. package/src/utils/__tests__/getKey.test.ts +10 -10
  139. package/src/utils/__tests__/getKeys.test.ts +10 -9
  140. package/src/utils/__tests__/getWinningRole.test.ts +57 -50
  141. package/src/utils/__tests__/hashPassword.test.ts +24 -25
  142. package/src/utils/__tests__/isEmpty.test.ts +14 -15
  143. package/src/utils/__tests__/logMachineInfo.test.ts +12 -12
  144. package/src/utils/__tests__/operators.test.ts +94 -96
  145. package/src/utils/__tests__/readFileContent.test.ts +28 -28
  146. package/src/utils/__tests__/registerPlugins.test.ts +44 -32
  147. package/src/utils/__tests__/rule.test.ts +47 -49
  148. package/src/utils/__tests__/rulesMatcherInterfaces.test.ts +57 -52
  149. package/src/utils/__tests__/rulesMatcherUtils.test.ts +64 -53
  150. package/src/utils/__tests__/someAsync.test.ts +46 -49
  151. package/src/utils/context/helpers.ts +1 -1
  152. package/src/utils/context/index.ts +7 -10
  153. package/src/utils/crypto/index.ts +2 -2
  154. package/src/utils/helpers/someAsync.ts +11 -11
  155. package/src/utils/initializer/exposeRoutes.ts +56 -2
  156. package/src/utils/initializer/registerPlugins.ts +11 -13
  157. package/src/utils/roles/helpers.ts +22 -15
  158. package/src/utils/roles/interface.ts +2 -3
  159. package/src/utils/roles/machines/commonValidators.ts +23 -14
  160. package/src/utils/roles/machines/index.ts +7 -4
  161. package/src/utils/roles/machines/interface.ts +17 -5
  162. package/src/utils/roles/machines/machine.ts +97 -72
  163. package/src/utils/roles/machines/read/A/index.ts +12 -4
  164. package/src/utils/roles/machines/read/B/index.ts +20 -7
  165. package/src/utils/roles/machines/read/C/index.ts +24 -8
  166. package/src/utils/roles/machines/read/D/index.ts +14 -8
  167. package/src/utils/roles/machines/read/D/validators.ts +21 -13
  168. package/src/utils/roles/machines/read/index.ts +5 -5
  169. package/src/utils/roles/machines/utils.ts +30 -13
  170. package/src/utils/roles/machines/write/A/index.ts +13 -5
  171. package/src/utils/roles/machines/write/B/index.ts +42 -16
  172. package/src/utils/roles/machines/write/C/index.ts +14 -8
  173. package/src/utils/roles/machines/write/C/validators.ts +21 -13
  174. package/src/utils/roles/machines/write/index.ts +4 -4
  175. package/src/utils/rules-matcher/interface.ts +4 -4
  176. package/src/utils/rules-matcher/utils.ts +10 -6
  177. package/src/utils/rules.ts +12 -5
  178. package/src/global.d.ts +0 -0
@@ -64,7 +64,9 @@ export async function authController(app: FastifyInstance) {
64
64
  throw new Error(`User with ID ${req.user.sub} not found`)
65
65
  }
66
66
 
67
- const user = await db!.collection(userCollection).findOne({ [AUTH_CONFIG.user_id_field]: req.user.sub })
67
+ const user = await db!
68
+ .collection(userCollection)
69
+ .findOne({ [AUTH_CONFIG.user_id_field]: req.user.sub })
68
70
 
69
71
  res.status(201)
70
72
  return {
@@ -75,4 +77,13 @@ export async function authController(app: FastifyInstance) {
75
77
  }
76
78
  }
77
79
  )
80
+ /**
81
+ * Endpoint to destroy the existing session.
82
+ */
83
+ app.delete(
84
+ AUTH_ENDPOINTS.SESSION,
85
+ async function () {
86
+ return { status: "ok" }
87
+ }
88
+ )
78
89
  }
@@ -1,8 +1,8 @@
1
- import sendGrid from "@sendgrid/mail"
1
+ import sendGrid from '@sendgrid/mail'
2
2
  import { FastifyInstance } from 'fastify'
3
3
  import { AUTH_CONFIG, DB_NAME } from '../../../constants'
4
- import { StateManager } from "../../../state"
5
- import { GenerateContext } from "../../../utils/context"
4
+ import { StateManager } from '../../../state'
5
+ import { GenerateContext } from '../../../utils/context'
6
6
  import { comparePassword, generateToken, hashPassword } from '../../../utils/crypto'
7
7
  import {
8
8
  AUTH_ENDPOINTS,
@@ -14,7 +14,12 @@ import {
14
14
  REGISTRATION_SCHEMA,
15
15
  RESET_SCHEMA
16
16
  } from '../../utils'
17
- import { ConfirmResetPasswordDto, LoginDto, RegistrationDto, ResetPasswordDto } from './dtos'
17
+ import {
18
+ ConfirmResetPasswordDto,
19
+ LoginDto,
20
+ RegistrationDto,
21
+ ResetPasswordDto
22
+ } from './dtos'
18
23
 
19
24
  /**
20
25
  * Controller for handling local user registration and login.
@@ -99,7 +104,6 @@ export async function localUserPassController(app: FastifyInstance) {
99
104
  schema: LOGIN_SCHEMA
100
105
  },
101
106
  async function (req) {
102
-
103
107
  const storedUser = await db.collection(authCollection!).findOne({
104
108
  email: req.body.username
105
109
  })
@@ -127,12 +131,12 @@ export async function localUserPassController(app: FastifyInstance) {
127
131
  )
128
132
 
129
133
  /**
130
- * Endpoint for reset password.
131
- *
132
- * @route {POST} /reset/call
133
- * @param {ResetPasswordDto} req - The request object with th reset request.
134
- * @returns {Promise<void>}
135
- */
134
+ * Endpoint for reset password.
135
+ *
136
+ * @route {POST} /reset/call
137
+ * @param {ResetPasswordDto} req - The request object with th reset request.
138
+ * @returns {Promise<void>}
139
+ */
136
140
  app.post<ResetPasswordDto>(
137
141
  AUTH_ENDPOINTS.RESET,
138
142
  {
@@ -152,16 +156,17 @@ export async function localUserPassController(app: FastifyInstance) {
152
156
  const token = generateToken()
153
157
  const tokenId = generateToken()
154
158
 
155
- await db?.collection(resetPasswordCollection).updateOne(
156
- { email },
157
- { $set: { token, tokenId, email, createdAt: new Date() } },
158
- { upsert: true }
159
- );
160
-
159
+ await db
160
+ ?.collection(resetPasswordCollection)
161
+ .updateOne(
162
+ { email },
163
+ { $set: { token, tokenId, email, createdAt: new Date() } },
164
+ { upsert: true }
165
+ )
161
166
 
162
167
  if (resetPasswordConfig.runResetFunction && resetPasswordConfig.resetFunctionName) {
163
- const functionsList = StateManager.select("functions")
164
- const services = StateManager.select("services")
168
+ const functionsList = StateManager.select('functions')
169
+ const services = StateManager.select('services')
165
170
  const currentFunction = functionsList[resetPasswordConfig.resetFunctionName]
166
171
  await GenerateContext({
167
172
  args: [{ token, tokenId, email }],
@@ -175,25 +180,28 @@ export async function localUserPassController(app: FastifyInstance) {
175
180
  return
176
181
  }
177
182
 
178
- const { from, subject, mailToken, body } = getMailConfig(resetPasswordConfig, token, tokenId)
183
+ const { from, subject, mailToken, body } = getMailConfig(
184
+ resetPasswordConfig,
185
+ token,
186
+ tokenId
187
+ )
179
188
  sendGrid.setApiKey(mailToken)
180
189
  await sendGrid.send({
181
190
  to: email,
182
191
  from,
183
192
  subject,
184
193
  html: body
185
- });
186
-
194
+ })
187
195
  }
188
196
  )
189
197
 
190
198
  /**
191
- * Endpoint for confirm reset password.
192
- *
193
- * @route {POST} /reset
194
- * @param {ConfirmResetPasswordDto} req - The request object with reset data.
195
- * @returns {Promise<void>}
196
- */
199
+ * Endpoint for confirm reset password.
200
+ *
201
+ * @route {POST} /reset
202
+ * @param {ConfirmResetPasswordDto} req - The request object with reset data.
203
+ * @returns {Promise<void>}
204
+ */
197
205
  app.post<ConfirmResetPasswordDto>(
198
206
  AUTH_ENDPOINTS.CONFIRM_RESET,
199
207
  {
@@ -203,24 +211,24 @@ export async function localUserPassController(app: FastifyInstance) {
203
211
  const { resetPasswordCollection } = AUTH_CONFIG
204
212
  const { token, tokenId, password } = req.body
205
213
 
206
- const resetRequest = await db?.collection(resetPasswordCollection).findOne(
207
- { token, tokenId },
208
- );
214
+ const resetRequest = await db
215
+ ?.collection(resetPasswordCollection)
216
+ .findOne({ token, tokenId })
209
217
 
210
218
  if (!resetRequest) {
211
219
  throw new Error(AUTH_ERRORS.INVALID_RESET_PARAMS)
212
220
  }
213
221
  const hashedPassword = await hashPassword(password)
214
- await db.collection(authCollection!).updateOne({ email: resetRequest.email, }, {
215
- $set: {
216
- password: hashedPassword
222
+ await db.collection(authCollection!).updateOne(
223
+ { email: resetRequest.email },
224
+ {
225
+ $set: {
226
+ password: hashedPassword
227
+ }
217
228
  }
218
- })
219
-
220
- await db?.collection(resetPasswordCollection).deleteOne(
221
- { _id: resetRequest._id },
222
- );
229
+ )
223
230
 
231
+ await db?.collection(resetPasswordCollection).deleteOne({ _id: resetRequest._id })
224
232
  }
225
233
  )
226
234
  }
@@ -37,4 +37,4 @@ export interface ConfirmResetPasswordDto {
37
37
  tokenId: string
38
38
  password: string
39
39
  }
40
- }
40
+ }
package/src/auth/utils.ts CHANGED
@@ -1,4 +1,5 @@
1
1
  import fs from 'fs'
2
+ import path from 'path'
2
3
 
3
4
  export const LOGIN_SCHEMA = {
4
5
  body: {
@@ -22,7 +23,6 @@ export const RESET_SCHEMA = {
22
23
  }
23
24
  }
24
25
 
25
-
26
26
  export const CONFIRM_RESET_SCHEMA = {
27
27
  body: {
28
28
  type: 'object',
@@ -35,7 +35,6 @@ export const CONFIRM_RESET_SCHEMA = {
35
35
  }
36
36
  }
37
37
 
38
-
39
38
  export const REGISTRATION_SCHEMA = {
40
39
  body: {
41
40
  type: 'object',
@@ -53,7 +52,8 @@ export enum AUTH_ENDPOINTS {
53
52
  PROFILE = '/profile',
54
53
  SESSION = '/session',
55
54
  RESET = '/reset/call',
56
- CONFIRM_RESET = "/reset"
55
+ CONFIRM_RESET = "/reset",
56
+ FIRST_USER = '/setup/first-user'
57
57
  }
58
58
 
59
59
  export enum AUTH_ERRORS {
@@ -108,7 +108,8 @@ export const PROVIDER_TYPE = 'local-userpass'
108
108
  * @testable
109
109
  */
110
110
  export const loadAuthConfig = (): AuthConfig => {
111
- return JSON.parse(fs.readFileSync('auth/providers.json', 'utf-8'))
111
+ const authPath = path.join(require.main!.path, 'auth/providers.json')
112
+ return JSON.parse(fs.readFileSync(authPath, 'utf-8'))
112
113
  }
113
114
 
114
115
  /**
@@ -116,24 +117,29 @@ export const loadAuthConfig = (): AuthConfig => {
116
117
  * @testable
117
118
  */
118
119
  export const loadCustomUserData = (): CustomUserDataConfig => {
119
- return JSON.parse(fs.readFileSync('auth/custom_user_data.json', 'utf-8'))
120
+ const userDataPath = path.join(require.main!.path, 'auth/custom_user_data.json')
121
+ return JSON.parse(fs.readFileSync(userDataPath, 'utf-8'))
120
122
  }
121
123
 
122
-
123
-
124
- export const getMailConfig = (resetPasswordConfig: Config, token: string, tokenId: string) => {
124
+ export const getMailConfig = (
125
+ resetPasswordConfig: Config,
126
+ token: string,
127
+ tokenId: string
128
+ ) => {
125
129
  const { mailConfig, resetPasswordUrl } = resetPasswordConfig
126
- const ENV_PREFIX = "ENV"
130
+ const ENV_PREFIX = 'ENV'
127
131
  const { from, subject, mailToken } = mailConfig
128
132
 
129
- const [fromPrefix, fromPath] = from.split(".")
130
- const currentSender = (fromPrefix === ENV_PREFIX ? process.env[fromPath] : from) ?? ""
131
- const [subjectPrefix, subjectPath] = subject.split(".")
132
- const currentSubject = (subjectPrefix === ENV_PREFIX ? process.env[subjectPath] : subject) ?? ""
133
- const [mailTokenPrefix, mailTokenPath] = mailToken.split(".")
134
- const currentMailToken = (mailTokenPrefix === "ENV" ? process.env[mailTokenPath] : mailToken) ?? ""
133
+ const [fromPrefix, fromPath] = from.split('.')
134
+ const currentSender = (fromPrefix === ENV_PREFIX ? process.env[fromPath] : from) ?? ''
135
+ const [subjectPrefix, subjectPath] = subject.split('.')
136
+ const currentSubject =
137
+ (subjectPrefix === ENV_PREFIX ? process.env[subjectPath] : subject) ?? ''
138
+ const [mailTokenPrefix, mailTokenPath] = mailToken.split('.')
139
+ const currentMailToken =
140
+ (mailTokenPrefix === 'ENV' ? process.env[mailTokenPath] : mailToken) ?? ''
135
141
 
136
- const link = `${resetPasswordUrl}/${token}/${tokenId}`;
142
+ const link = `${resetPasswordUrl}/${token}/${tokenId}`
137
143
  const body = `<body style="font-family: Arial, sans-serif; background-color: #f4f4f4; text-align: center; padding: 20px;">
138
144
  <table width="100%" cellspacing="0" cellpadding="0">
139
145
  <tr>
@@ -157,9 +163,9 @@ export const getMailConfig = (resetPasswordConfig: Config, token: string, tokenI
157
163
  </table>
158
164
  </body>`
159
165
  return {
160
- from: currentSender ?? "",
166
+ from: currentSender ?? '',
161
167
  subject: currentSubject,
162
168
  mailToken: currentMailToken,
163
169
  body
164
170
  }
165
- }
171
+ }
package/src/constants.ts CHANGED
@@ -1,13 +1,17 @@
1
1
  import { loadAuthConfig, loadCustomUserData } from './auth/utils'
2
2
 
3
- const { database_name, collection_name = 'users', user_id_field = "id" } = loadCustomUserData()
3
+ const {
4
+ database_name,
5
+ collection_name = 'users',
6
+ user_id_field = 'id'
7
+ } = loadCustomUserData()
4
8
  const { auth_collection = 'auth_users', ...configuration } = loadAuthConfig()
5
9
 
6
10
  export const DEFAULT_CONFIG = {
7
11
  PORT: Number(process.env.PORT) || 3000,
8
12
  MONGODB_URL: process.env.MONGODB_URL || '',
9
13
  JWT_SECRET: process.env.JWT_SECRET || '',
10
- API_VERSION: process.env.API_VERSION || "v2.0",
14
+ API_VERSION: process.env.API_VERSION || 'v2.0',
11
15
  HTTPS_SCHEMA: process.env.HTTPS_SCHEMA || 'https',
12
16
  HOST: process.env.HOST || '0.0.0.0',
13
17
  ENABLE_LOGGER: process.env.ENABLE_LOGGER
@@ -18,7 +22,7 @@ export const DB_NAME = database_name
18
22
  export const AUTH_CONFIG = {
19
23
  authCollection: auth_collection,
20
24
  userCollection: collection_name,
21
- resetPasswordCollection: "reset-password-requests",
25
+ resetPasswordCollection: 'reset-password-requests',
22
26
  resetPasswordConfig: configuration['local-userpass'].config,
23
27
  user_id_field
24
28
  }
@@ -1,4 +1,5 @@
1
1
  import fs from 'fs'
2
+ import path from 'node:path'
2
3
  import { FastifyInstance, FastifyReply, FastifyRequest } from 'fastify'
3
4
 
4
5
  import { services } from '../../services'
@@ -10,10 +11,11 @@ import { Endpoints, GenerateHandlerParams } from './interface'
10
11
  * > Loads the endpoint config json file
11
12
  * @testable
12
13
  */
13
- export const loadEndpoints = async (): Promise<Endpoints> => {
14
- const config: Endpoints<'*'> = JSON.parse(
15
- fs.readFileSync('http_endpoints/config.json', 'utf-8')
16
- )
14
+ export const loadEndpoints = async (rootDir = process.cwd()): Promise<Endpoints> => {
15
+ const endpointsDir = 'http_endpoints'
16
+ const endPointsFile = path.join(rootDir, endpointsDir, 'config.json')
17
+ const config: Endpoints<'*'> = JSON.parse(fs.readFileSync(endPointsFile, 'utf-8'))
18
+
17
19
  return config.map(({ http_method, ...endpoint }) => ({
18
20
  http_method: http_method === '*' ? 'ALL' : http_method,
19
21
  ...endpoint
@@ -1,6 +1,5 @@
1
1
  import { ObjectId } from 'bson'
2
2
 
3
-
4
3
  import { services } from '../../services'
5
4
  import { StateManager } from '../../state'
6
5
  import { GenerateContext } from '../../utils/context'
@@ -29,7 +28,7 @@ export const functionsController: FunctionController = async (
29
28
  if (!serviceFn) {
30
29
  throw new Error(`Service "${req.body.service}" does not exist`)
31
30
  }
32
- const [{ database, collection, query, update, document }] = args
31
+ const [{ database, collection, query, update, document, documents }] = args
33
32
 
34
33
  const currentMethod = serviceFn(app, { rules, user })
35
34
  .db(database)
@@ -39,7 +38,8 @@ export const functionsController: FunctionController = async (
39
38
  currentMethod,
40
39
  query,
41
40
  update,
42
- document
41
+ document,
42
+ documents
43
43
  })
44
44
  return operatorsByType[method as keyof typeof operatorsByType]()
45
45
  }
@@ -54,7 +54,6 @@ export const functionsController: FunctionController = async (
54
54
  throw new Error(`Function "${req.body.name}" is private`)
55
55
  }
56
56
 
57
-
58
57
  const result = await GenerateContext({
59
58
  args: req.body.arguments,
60
59
  app,
@@ -64,39 +63,41 @@ export const functionsController: FunctionController = async (
64
63
  functionsList,
65
64
  services
66
65
  })
67
- res.type("application/json")
66
+ res.type('application/json')
68
67
  return JSON.stringify(result)
69
68
  })
70
69
  app.get<{
71
- Querystring: FunctionCallBase64Dto,
70
+ Querystring: FunctionCallBase64Dto
72
71
  }>('/call', async (req, res) => {
73
72
  const { query, user } = req
74
73
  const { baas_request, stitch_request } = query
75
74
 
76
- const config: Base64Function = JSON.parse(Buffer.from(baas_request || stitch_request || "", "base64").toString("utf8"));
75
+ const config: Base64Function = JSON.parse(
76
+ Buffer.from(baas_request || stitch_request || '', 'base64').toString('utf8')
77
+ )
77
78
  const [{ database, collection }] = config.arguments
78
- const app = StateManager.select("app")
79
- const services = StateManager.select("services")
79
+ const app = StateManager.select('app')
80
+ const services = StateManager.select('services')
80
81
 
81
- const changeStream = await services["mongodb-atlas"](app, {
82
+ const changeStream = await services['mongodb-atlas'](app, {
82
83
  user,
83
84
  rules
84
- }).db(database).collection(collection).watch([], { fullDocument: "whenAvailable" })
85
-
86
- res.header('Content-Type', 'text/event-stream');
87
- res.header('Cache-Control', 'no-cache');
88
- res.header('Connection', 'keep-alive');
89
- res.raw.flushHeaders();
85
+ })
86
+ .db(database)
87
+ .collection(collection)
88
+ .watch([], { fullDocument: 'whenAvailable' })
90
89
 
90
+ res.header('Content-Type', 'text/event-stream')
91
+ res.header('Cache-Control', 'no-cache')
92
+ res.header('Connection', 'keep-alive')
93
+ res.raw.flushHeaders()
91
94
 
92
95
  changeStream.on('change', (change) => {
93
- res.raw.write(`data: ${JSON.stringify(change)}\n\n`);
94
- });
96
+ res.raw.write(`data: ${JSON.stringify(change)}\n\n`)
97
+ })
95
98
 
96
99
  req.raw.on('close', () => {
97
- changeStream.close();
98
- });
100
+ changeStream.close()
101
+ })
99
102
  })
100
-
101
-
102
103
  }
@@ -1,4 +1,4 @@
1
- import { Document } from "mongodb"
1
+ import { Document } from 'mongodb'
2
2
  import { Arguments } from '../../auth/dtos'
3
3
  import { GetOperatorsFunction } from '../../services/mongodb-atlas/model'
4
4
 
@@ -6,14 +6,14 @@ type MethodName = Exclude<keyof ReturnType<GetOperatorsFunction>, 'match'>
6
6
 
7
7
  export type FunctionCallDto =
8
8
  | {
9
- name: MethodName
10
- arguments: ArgumentsData
11
- }
9
+ name: MethodName
10
+ arguments: ArgumentsData
11
+ }
12
12
  | {
13
- arguments: ArgumentsData
14
- name: MethodName
15
- service: 'mongodb-atlas'
16
- }
13
+ arguments: ArgumentsData
14
+ name: MethodName
15
+ service: 'mongodb-atlas'
16
+ }
17
17
 
18
18
  export type FunctionCallBase64Dto = {
19
19
  baas_request?: string
@@ -26,9 +26,9 @@ type ArgumentsData = Arguments<{
26
26
  query: Parameters<GetOperatorsFunction>
27
27
  update: Document
28
28
  document: Document
29
+ documents: Document[]
29
30
  }>
30
31
 
31
-
32
32
  export type Base64Function = {
33
33
  name: string
34
34
  arguments: Argument[]
@@ -1,5 +1,5 @@
1
1
  import { FastifyInstance } from 'fastify'
2
- import { Document } from "mongodb"
2
+ import { Document } from 'mongodb'
3
3
  import { GetOperatorsFunction } from '../../services/mongodb-atlas/model'
4
4
  import { Rules } from '../rules/interface'
5
5
 
@@ -25,6 +25,7 @@ export type ExecuteQueryParams = {
25
25
  query: Parameters<GetOperatorsFunction>
26
26
  update: Document
27
27
  document: Document
28
+ documents: Document[]
28
29
  }
29
30
 
30
31
  type FunctionsControllerOptions = {
@@ -16,16 +16,16 @@ export const loadFunctions = async (rootDir = process.cwd()): Promise<Functions>
16
16
  }[]
17
17
 
18
18
  const functions = config.reduce((acc, { name, ...opts }) => {
19
- const extensions = ['.js', '.ts'];
20
- let code = '';
19
+ const extensions = ['.js', '.ts']
20
+ let code = ''
21
21
  const fnPath = extensions
22
- .map(ext => path.join(rootDir, fnDir, `${name}${ext}`))
23
- .find(fs.existsSync);
22
+ .map((ext) => path.join(rootDir, fnDir, `${name}${ext}`))
23
+ .find(fs.existsSync)
24
24
 
25
25
  if (!fnPath) {
26
- throw new Error(`File ${name}.js or ${name}.ts not found`);
26
+ throw new Error(`File ${name}.js or ${name}.ts not found`)
27
27
  }
28
- code = fs.readFileSync(fnPath, 'utf-8');
28
+ code = fs.readFileSync(fnPath, 'utf-8')
29
29
  acc[name] = { code, ...opts }
30
30
 
31
31
  return acc
@@ -44,7 +44,8 @@ export const executeQuery = async ({
44
44
  currentMethod,
45
45
  query,
46
46
  update,
47
- document
47
+ document,
48
+ documents
48
49
  }: ExecuteQueryParams) => {
49
50
  return {
50
51
  find: async () =>
@@ -70,13 +71,12 @@ export const executeQuery = async ({
70
71
  ),
71
72
  insertMany: () =>
72
73
  (currentMethod as ReturnType<GetOperatorsFunction>['insertMany'])(
73
- EJSON.deserialize(query)
74
+ EJSON.deserialize(documents)
74
75
  ),
75
76
  updateMany: () =>
76
77
  (currentMethod as ReturnType<GetOperatorsFunction>['updateMany'])(
77
- EJSON.deserialize(query), EJSON.deserialize(update)
78
- ),
79
-
80
-
78
+ EJSON.deserialize(query),
79
+ EJSON.deserialize(update)
80
+ )
81
81
  }
82
82
  }
@@ -15,7 +15,7 @@ export const activateTriggers = async ({
15
15
  triggersList,
16
16
  functionsList
17
17
  }: ActivateTriggersParams) => {
18
- console.log("START ACTIVATION TRIGGERS")
18
+ console.log('START ACTIVATION TRIGGERS')
19
19
  try {
20
20
  for await (const trigger of triggersList) {
21
21
  const { content } = trigger
@@ -24,13 +24,16 @@ export const activateTriggers = async ({
24
24
  const functionName: keyof Functions = event_processors.FUNCTION.config.function_name
25
25
  const triggerHandler = functionsList[functionName] as Function
26
26
 
27
- await TRIGGER_HANDLERS[type]({ config, triggerHandler, app: fastify, services, functionsList })
28
-
27
+ await TRIGGER_HANDLERS[type]({
28
+ config,
29
+ triggerHandler,
30
+ app: fastify,
31
+ services,
32
+ functionsList
33
+ })
29
34
  }
30
- console.log("TRIGGERS ACTIVATION COMPLETED")
35
+ console.log('TRIGGERS ACTIVATION COMPLETED')
31
36
  } catch (e) {
32
37
  console.error('Error while activating triggers', (e as Error).message)
33
38
  }
34
39
  }
35
-
36
-
@@ -1,6 +1,6 @@
1
- import { FastifyInstance } from "fastify"
2
- import { Services } from "../../services/interface"
3
- import { Function, Functions } from "../functions/interface"
1
+ import { FastifyInstance } from 'fastify'
2
+ import { Services } from '../../services/interface'
3
+ import { Function, Functions } from '../functions/interface'
4
4
 
5
5
  export interface Trigger {
6
6
  name: string
@@ -31,14 +31,13 @@ type Config = {
31
31
  schedule: string
32
32
  }
33
33
 
34
- export type TriggerType = "SCHEDULED" | "DATABASE" | "AUTHENTICATION"
34
+ export type TriggerType = 'SCHEDULED' | 'DATABASE' | 'AUTHENTICATION'
35
35
  export type Triggers = { fileName: string; content: Trigger }[]
36
36
 
37
-
38
37
  export type HandlerParams = {
39
- config: Config,
40
- triggerHandler: Function,
41
- app: FastifyInstance,
42
- services: Services,
38
+ config: Config
39
+ triggerHandler: Function
40
+ app: FastifyInstance
41
+ services: Services
43
42
  functionsList: Functions
44
- }
43
+ }