Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Changes for integrating [email protected] #1

Open
wants to merge 4 commits into
base: develop
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
136 changes: 62 additions & 74 deletions src/app.js
Original file line number Diff line number Diff line change
@@ -1,74 +1,62 @@
'use strict';
require('module-alias/register');
const express = require('express');
const cors = require('cors');
require('dotenv').config({ path: './.env' });
const path = require('path');
const packageInstaller = require('./utils/packageInstaller');
const executeScripts = require('./scripts');



(async () => {
try {


// First, install necessary packages
await packageInstaller(process.env.REQUIRED_PACKAGES);

// Next, execute fetchRouteConfigs and combineRoutesConfigs
await executeScripts();

const dependencyManager = require('@helpers/dependencyManager')
await dependencyManager()

// After scripts execution, continue with environment data validation
let environmentData = require('./envVariables')();
if (!environmentData.success) {
console.error('Server could not start. Not all environment variables are provided');
process.exit(1);
}

// Initialize the rest of the application (after the scripts are done)
require('./init');

// Create an Express app instance
const app = express();
app.set('trust proxy', parseInt(process.env.RATE_LIMITER_NUMBER_OF_PROXIES));

// Middleware and CORS setup
app.use(cors());

// Set Access-Control-Allow-Origin header
app.use((req, res, next) => {
res.setHeader('Access-Control-Allow-Origin', process.env.ALLOWED_HOST);
next();
});

// Load router packages and initialize the router
const routerPackages = require('@utils/packageLoader').packageLoader();
const validatedPackages = routerPackages; // Bypassing the validator for now
const { initializeRouter } = require('@router');
app.use(initializeRouter(validatedPackages));

// Serve API documentation
app.get(process.env.API_DOC_URL, (req, res) => {
res.sendFile(path.join(__dirname, './api-doc/index.html'));
});

// Start the server
app.listen(process.env.APPLICATION_PORT, (err) => {
if (err) {
onError(err);
}
console.log('Environment: ' + process.env.APPLICATION_ENV);
console.log('Application is running on port: ' + process.env.APPLICATION_PORT);

});

} catch (error) {
// Handle any error from script execution or package installation
console.error('Error in app initialization:', error);
process.exit(1);
}
})();
'use strict'
require('module-alias/register')
const express = require('express')
const cors = require('cors')
require('dotenv').config({ path: './.env' })
const path = require('path')
const packageInstaller = require('./utils/packageInstaller')
const executeScripts = require('./scripts')

;(async () => {
try {
// First, install necessary packages
await packageInstaller(process.env.REQUIRED_PACKAGES)

// Next, execute fetchRouteConfigs and combineRoutesConfigs
await executeScripts()

const dependencyManager = require('@helpers/dependencyManager')
await dependencyManager()

// After scripts execution, continue with environment data validation
let environmentData = require('./envVariables')()
if (!environmentData.success) {
console.error('Server could not start. Not all environment variables are provided')
process.exit(1)
}
// Initialize the rest of the application (after the scripts are done)
require('./init')

// Create an Express app instance
const app = express()
app.set('trust proxy', parseInt(process.env.RATE_LIMITER_NUMBER_OF_PROXIES))

// Middleware and CORS setup
app.use(cors())

// Set Access-Control-Allow-Origin header
app.use((req, res, next) => {
res.setHeader('Access-Control-Allow-Origin', process.env.ALLOWED_HOST)
next()
})
// Load router packages and initialize the router
const routerPackages = require('@utils/packageLoader').packageLoader()
const validatedPackages = routerPackages // Bypassing the validator for now
const { initializeRouter } = require('@router')
app.use(initializeRouter(validatedPackages))
// Serve API documentation
app.get(process.env.API_DOC_URL, (req, res) => {
res.sendFile(path.join(__dirname, './api-doc/index.html'))
})
// Start the server
app.listen(process.env.APPLICATION_PORT, (err) => {
if (err) {
onError(err)
}
})
} catch (error) {
// Handle any error from script execution or package installation
console.error('Error in app initialization:', error)
process.exit(1)
}
})()
7 changes: 1 addition & 6 deletions src/configs/dependencyConfig.json
Original file line number Diff line number Diff line change
@@ -1,9 +1,4 @@
{
"requiredDependencies": [],
"supportedDependencies": [
{
"name": "kafka",
"packageName": "elevate-kafka"
}
]
"supportedDependencies": []
}
2 changes: 1 addition & 1 deletion src/configs/routesConfigs.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,6 @@
const config = require('@configs/.config.json')

exports.routesConfigs = {
services: process.env.REQUIRED_BASE_PACKAGES.split(","),
services: process.env.REQUIRED_BASE_PACKAGES,
routes: config.routes,
}
30 changes: 30 additions & 0 deletions src/configs/routesConfigs/shiksha-user.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
{
"routes": [
{
"sourceRoute": "/interface/v1/account/create",
"type": "POST",
"priority": "MUST_HAVE",
"inSequence": false,
"orchestrated": false,
"targetPackages": [
{
"basePackageName": "user",
"packageName": "shiksha-user"
}
]
},
{
"sourceRoute": "/interface/v1/account/login",
"type": "POST",
"priority": "MUST_HAVE",
"inSequence": false,
"orchestrated": false,
"targetPackages": [
{
"basePackageName": "user",
"packageName": "shiksha-user"
}
]
}
]
}
83 changes: 42 additions & 41 deletions src/generics/request.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
const request = require('request');
const request = require('request')

/**
* Makes a GET request to the specified URL with optional token headers.
Expand All @@ -8,50 +8,51 @@ const request = require('request');
* @returns {Promise<object>} - A promise that resolves to the fetched result object.
*/
var get = function (url, token = '', internal_access_token = '') {
return new Promise((resolve, reject) => {
try {
let headers = {
'content-type': 'application/json',
};
if (internal_access_token) {
headers['internal_access_token'] = internal_access_token;
}
return new Promise((resolve, reject) => {
try {
let headers = {
'content-type': 'application/json',
}
if (internal_access_token) {
headers['internal_access_token'] = internal_access_token
}

if (token) {
headers['x-auth-token'] = token;
}
if (token) {
headers['x-auth-token'] = token
}

const options = {
headers: headers,
};
const options = {
headers: headers,
}

request.get(url, options, (err, response) => {
let result = {
success: true,
};
request.get(url, options, (err, response) => {
console.log('url: ', url)
//console.log('options: ', options)
let result = {
success: true,
}
if (err) {
result.success = false
result.error = err
} else {
let body = response.body
try {
result.data = typeof body === 'string' ? JSON.parse(body) : body // Attempt to parse the JSON string JSON.parse(body);
} catch (jsonError) {
console.log('Error parsing JSON : ', jsonError)
result.success = false
result.error = 'Error parsing JSON'
}
}

if (err) {
result.success = false;
result.error = err;
} else {
let body = response.body;
try {
result.data = typeof body === "string" ? JSON.parse(body) : body ; // Attempt to parse the JSON string JSON.parse(body);
} catch (jsonError) {
console.log('Error parsing JSON : ',jsonError)
result.success = false;
result.error = 'Error parsing JSON';
}
}

return resolve(result);
});
} catch (error) {
return reject(error);
}
});
};
return resolve(result)
})
} catch (error) {
return reject(error)
}
})
}

module.exports = {
get
get,
}
98 changes: 39 additions & 59 deletions src/helpers/dependencyManager.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,68 +3,48 @@
const dependencyConfigs = require('@configs/dependencyConfig.json')
const requiredEnvsJSON = require('../configs/requiredEnvs.json')

const packageLoader = require('@utils/packageLoader');
const packageLoader = require('@utils/packageLoader')

const dependencyManager = () => {
try {
const { supportedDependencies } = dependencyConfigs
const supportedDependencyMap = new Map()

supportedDependencies.map((dependency) => {
const dependencyPackage = require(dependency.packageName)
supportedDependencyMap.set(dependency.name, dependencyPackage)
return dependency.name
})

const packages = packageLoader.packageLoader()

packages.forEach(packageInfo => {

const { packageName } = packageInfo.packageMeta;




const { dependencyManager, requiredEnvs } = require(packageName)

requiredEnvsJSON.requiredEnvs = {
...requiredEnvsJSON.requiredEnvs,
...requiredEnvs,
}

if(packageInfo.requiredDependencies){
let requiredDependencies = packageInfo.requiredDependencies();

if( requiredDependencies.length > 0) {

const injectionPackageMap = new Map()
const unsupportedDependencies = []

requiredDependencies.forEach(dependencyArray => {

if(dependencyArray.dependencies) {
dependencyArray.dependencies.map((dependency) => {

if (!supportedDependencyMap.has(dependency.name)) unsupportedDependencies.push(dependency.name)
else injectionPackageMap.set(dependency.name, supportedDependencyMap.get(dependency.name))
})
}
if (unsupportedDependencies.length > 0)
throw `Package ${packageName} requires unsupported dependencies: [${unsupportedDependencies}]`

const packageEnvironmentVariables = {}
Object.keys(requiredEnvs).map((envVariable) => {
packageEnvironmentVariables[envVariable] = process.env[envVariable]
})

dependencyManager(injectionPackageMap, packageEnvironmentVariables)

});
}
}

});

// const { supportedDependencies } = dependencyConfigs
arati-tekdi marked this conversation as resolved.
Show resolved Hide resolved
// const supportedDependencyMap = new Map()
// supportedDependencies.map((dependency) => {
// const dependencyPackage = require(dependency.packageName)
// supportedDependencyMap.set(dependency.name, dependencyPackage)
// return dependency.name
// })
// const packages = packageLoader.packageLoader()
// packages.forEach(packageInfo => {
// const { packageName } = packageInfo.packageMeta;
// const { dependencyManager, requiredEnvs } = require(packageName)
// requiredEnvsJSON.requiredEnvs = {
// ...requiredEnvsJSON.requiredEnvs,
// ...requiredEnvs,
// }
// if(packageInfo.requiredDependencies){
// let requiredDependencies = packageInfo.requiredDependencies();
// if( requiredDependencies.length > 0) {
// const injectionPackageMap = new Map()
// const unsupportedDependencies = []
// requiredDependencies.forEach(dependencyArray => {
// if(dependencyArray.dependencies) {
// dependencyArray.dependencies.map((dependency) => {
// if (!supportedDependencyMap.has(dependency.name)) unsupportedDependencies.push(dependency.name)
// else injectionPackageMap.set(dependency.name, supportedDependencyMap.get(dependency.name))
// })
// }
// if (unsupportedDependencies.length > 0)
// throw `Package ${packageName} requires unsupported dependencies: [${unsupportedDependencies}]`
// const packageEnvironmentVariables = {}
// Object.keys(requiredEnvs).map((envVariable) => {
// packageEnvironmentVariables[envVariable] = process.env[envVariable]
// })
// dependencyManager(injectionPackageMap, packageEnvironmentVariables)
// });
// }
// }
// });
} catch (error) {
console.log('Dependency Manager Error: ', error)
throw error
Expand Down
Loading