Skip to content

Commit f5b07d0

Browse files
committed
feat: API initialization accepts an array to handle multi step initialization of third party APIS
1 parent 64ac007 commit f5b07d0

File tree

1 file changed

+40
-12
lines changed

1 file changed

+40
-12
lines changed

src/server.js

+40-12
Original file line numberDiff line numberDiff line change
@@ -193,22 +193,50 @@ class CoCreateLazyLoader {
193193
throw new Error(`Missing ${name} key in organization apis object`);
194194

195195
// ToDo: if data.endpoint service not required as endpoint will be used
196-
let instance = require(config.path);
196+
let instance;
197197

198-
if (config.initialize) {
199-
const initialize = config.initialize.split('.');
200-
201-
// Traverse the nested structure to reach the correct constructor
202-
for (let i = 0; i < initialize.length; i++) {
203-
if (instance[initialize[i]]) {
204-
instance = instance[initialize[i]];
205-
} else {
206-
throw new Error(`Service path ${config.initialize} is incorrect at ${initialize[i]}`);
207-
}
198+
// Try using require() first, for CommonJS modules
199+
try {
200+
instance = require(config.path); // Attempt to require the module
201+
} catch (err) {
202+
if (err.code === 'ERR_REQUIRE_ESM') {
203+
// If it's an ESM module, fallback to dynamic import()
204+
instance = await import(config.path);
205+
} else {
206+
throw err; // Re-throw other errors
208207
}
209208
}
210209

211-
instance = new instance(key);
210+
if (config.initialize) {
211+
if (Array.isArray(config.initialize)) {
212+
const initializations = []
213+
for (let i = 0; i < config.initialize.length; i++) {
214+
const initialize = config.initialize[i].split('.');
215+
initializations.push(instance)
216+
// Traverse the nested structure to reach the correct constructor
217+
for (let j = 0; j < initialize.length; j++) {
218+
if (initializations[i][initialize[j]]) {
219+
initializations[i] = initializations[i][initialize[j]];
220+
} else {
221+
throw new Error(`Service path ${config.initialize[i]} is incorrect at ${initialize[j]}`);
222+
}
223+
}
224+
}
225+
instance = new initializations[1](new initializations[0](key));
226+
} else {
227+
const initialize = config.initialize.split('.');
228+
// Traverse the nested structure to reach the correct constructor
229+
for (let i = 0; i < initialize.length; i++) {
230+
if (instance[initialize[i]]) {
231+
instance = instance[initialize[i]];
232+
} else {
233+
throw new Error(`Service path ${config.initialize} is incorrect at ${initialize[i]}`);
234+
}
235+
}
236+
}
237+
instance = new instance(key);
238+
} else
239+
instance = new instance(key);
212240

213241
let params = [], mainParam = false
214242
for (let i = 0; true; i++) {

0 commit comments

Comments
 (0)