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

updated routes #10

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all 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
20 changes: 14 additions & 6 deletions elevate-notification/constants/routes.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,14 @@
module.exports = [
{ route: '/v1/get-user-photo', config: [{ type: 'GET' }] },
{ route: '/v1/get-user-profile', config: [{ type: 'POST' }] },
{ route: '/v1/get-sharelink', config: [{ type: 'PUT' }, { type: 'PATCH' }] },
{ route: '/v1/get-user-details', config: [{ type: 'DELETE' }] },
];
module.exports = {
routes: [
{
sourceRoute: '/notification/v1/email/send',
type: 'POST',
inSequence: false,
orchestrated: false,
targetRoute: {
path: '/notification/v1/email/send',
type: 'POST',
},
},
],
}
7 changes: 7 additions & 0 deletions elevate-notification/controllers/notification.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
const routeConfigs = require('../constants/routes')
const requesters = require('../utils/requester')

const notificationController = {
}

module.exports = notificationController
13 changes: 13 additions & 0 deletions elevate-notification/controllers/orchestrationController.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
const routesConfig = require('../constants/routes')
const notificationController = require('../controllers/notification')
const orchestrationHandler = async (req, res, responses) => {
console.log(req.targetPackages, req.inSequence, req.orchestrated, req.sourceRoute, responses)
console.log(req.body)
const selectedRouteConfig = routesConfig.routes.find((obj) => obj.sourceRoute === req.sourceRoute)
return await notificationController[selectedRouteConfig.targetRoute.functionName](req, res, responses)
}

const orchestrationController = {
orchestrationHandler,
}
module.exports = orchestrationController
38 changes: 37 additions & 1 deletion elevate-notification/index.js
Original file line number Diff line number Diff line change
@@ -1 +1,37 @@
const routes = require('./constants/routes');
const express = require('express')
const router = express.Router()
const routes = require('./constants/routes')
const packageRouter = require('./router')

const getDependencies = () => {
return ['kafka', 'kafka-connect', 'redis']
}

const getPackageMeta = () => {
return {
basePackageName: 'notification',
packageName: 'elevate-notification',
}
}

const createPackage = (options) => {
return {
router: () => {
console.log('router')
},
endpoints: [],
dependencies: [],
}
}

router.get('/', (req, res) => {
res.send('Hello, world! From notification package')
})

module.exports = {
dependencies: getDependencies(),
routes,
createPackage,
packageMeta: getPackageMeta(),
packageRouter,
}
10 changes: 10 additions & 0 deletions elevate-notification/router/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
const { passThroughRequester } = require('../utils/requester')
const { orchestrationHandler } = require('../controllers/orchestrationController')
const packageRouter = async (req, res, responses) => {
const response = req.orchestrated
? await orchestrationHandler(req, res, responses)
: await passThroughRequester(req, res)
return response
}

module.exports = packageRouter
6 changes: 6 additions & 0 deletions elevate-notification/utils/pathParamSetter.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
exports.pathParamSetter = (targetPath, params) => {
return targetPath.replace(/:\w+/g, (match) => {
const fieldName = match.substring(1)
return params[fieldName] || match
})
}
16 changes: 16 additions & 0 deletions elevate-notification/utils/patternMatcher.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
exports.matchPathsAndExtractParams = (pattern, url) => {
const paramNames = []
const regexPattern = new RegExp(
pattern.replace(/:(\w+)/g, (_, paramName) => {
paramNames.push(paramName)
return '([a-zA-Z0-9]+)'
})
)
const matchResult = url.match(regexPattern)
if (!matchResult) return false
const params = {}
for (let i = 0; i < paramNames.length; i++) {
params[paramNames[i]] = matchResult[i + 1]
}
return params
}
62 changes: 62 additions & 0 deletions elevate-notification/utils/requester.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
const http = require('http')
const https = require('https')
const { matchPathsAndExtractParams } = require('../utils/patternMatcher')
const routesConfig = require('../constants/routes')
const { pathParamSetter } = require('../utils/pathParamSetter')
const axios = require('axios')

const handleInterfaceError = (res, err) => {
console.log('Error: ', err)
res.writeHead(500, { 'Content-Type': 'text/plain' })
res.end('Interface Server Error')
}

const passThroughRequester = async (req, res) => {
try {
const sourceBaseUrl = req.protocol + '://' + req.headers.host + '/'
const sourceUrl = new URL(req.originalUrl, sourceBaseUrl)
const route = routesConfig.routes.find((route) => route.sourceRoute === req.sourceRoute)
const params = matchPathsAndExtractParams(route.sourceRoute, req.originalUrl)
const targetRoute = pathParamSetter(route.targetRoute.path, params)
const parsedUrl = new URL(targetRoute, req.baseUrl)
const options = {
method: req.method,
headers: req.headers,
hostname: parsedUrl.hostname,
port: parsedUrl.port,
path: parsedUrl.pathname + sourceUrl.search,
}
console.log({
sourceBaseUrl,
sourceUrl,
route,
params,
targetRoute,
parsedUrl,
options,
})
const proxyReq = (parsedUrl.protocol === 'https:' ? https : http).request(options, (proxyRes) => {
res.writeHead(proxyRes.statusCode, proxyRes.headers)
proxyRes.pipe(res, { end: true })
})
proxyReq.on('error', (err) => {
handleInterfaceError(res, err)
})
req.pipe(proxyReq, { end: true })
} catch (err) {
handleInterfaceError(res, err)
}
}

const post = async (baseUrl, route, requestBody, headers) => {
const url = baseUrl + route
const response = await axios.post(url, requestBody, { headers })
return response.data
}

const requesters = {
passThroughRequester,
post,
}

module.exports = requesters
50 changes: 44 additions & 6 deletions elevate-scheduler/constants/routes.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,44 @@
module.exports = [
{ route: '/v1/get-user-photo', config: [{ type: 'GET' }] },
{ route: '/v1/get-user-profile', config: [{ type: 'POST' }] },
{ route: '/v1/get-sharelink', config: [{ type: 'PUT' }, { type: 'PATCH' }] },
{ route: '/v1/get-user-details', config: [{ type: 'DELETE' }] },
];
module.exports = {
routes: [
{
sourceRoute: '/scheduler/jobs/list',
type: 'GET',
inSequence: false,
orchestrated: false,
targetRoute: {
path: '/scheduler/jobs/list',
type: 'POST',
},
},
{
sourceRoute: '/scheduler/jobs/create',
type: 'POST',
inSequence: false,
orchestrated: false,
targetRoute: {
path: '/scheduler/jobs/create',
type: 'POST',
},
},
{
sourceRoute: '/scheduler/jobs/remove',
type: 'POST',
inSequence: false,
orchestrated: false,
targetRoute: {
path: '/scheduler/jobs/remove',
type: 'POST',
},
},
{
sourceRoute: '/scheduler/jobs/purge',
type: 'POST',
inSequence: false,
orchestrated: false,
targetRoute: {
path: '/scheduler/jobs/purge',
type: 'POST',
},
},
],
}
13 changes: 13 additions & 0 deletions elevate-scheduler/controllers/orchestrationController.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
const routesConfig = require('../constants/routes')
const schedulerController = require('../controllers/user')
const orchestrationHandler = async (req, res, responses) => {
console.log(req.targetPackages, req.inSequence, req.orchestrated, req.sourceRoute, responses)
console.log(req.body)
const selectedRouteConfig = routesConfig.routes.find((obj) => obj.sourceRoute === req.sourceRoute)
return await schedulerController[selectedRouteConfig.targetRoute.functionName](req, res, responses)
}

const orchestrationController = {
orchestrationHandler,
}
module.exports = orchestrationController
7 changes: 7 additions & 0 deletions elevate-scheduler/controllers/scheduler.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
const routeConfigs = require('../constants/routes')
const requesters = require('../utils/requester')

const schedulerController = {
}

module.exports = schedulerController
37 changes: 37 additions & 0 deletions elevate-scheduler/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
const express = require('express')
const router = express.Router()
const routes = require('./constants/routes')
const packageRouter = require('./router')

const getDependencies = () => {
return ['kafka', 'kafka-connect', 'redis']
}

const getPackageMeta = () => {
return {
basePackageName: 'scheduler',
packageName: 'elevate-scheduler',
}
}

const createPackage = (options) => {
return {
router: () => {
console.log('router')
},
endpoints: [],
dependencies: [],
}
}

router.get('/', (req, res) => {
res.send('Hello, world! From scheduler package')
})

module.exports = {
dependencies: getDependencies(),
routes,
createPackage,
packageMeta: getPackageMeta(),
packageRouter,
}
10 changes: 10 additions & 0 deletions elevate-scheduler/router/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
const { passThroughRequester } = require('../utils/requester')
const { orchestrationHandler } = require('../controllers/orchestrationController')
const packageRouter = async (req, res, responses) => {
const response = req.orchestrated
? await orchestrationHandler(req, res, responses)
: await passThroughRequester(req, res)
return response
}

module.exports = packageRouter
6 changes: 6 additions & 0 deletions elevate-scheduler/utils/pathParamSetter.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
exports.pathParamSetter = (targetPath, params) => {
return targetPath.replace(/:\w+/g, (match) => {
const fieldName = match.substring(1)
return params[fieldName] || match
})
}
16 changes: 16 additions & 0 deletions elevate-scheduler/utils/patternMatcher.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
exports.matchPathsAndExtractParams = (pattern, url) => {
const paramNames = []
const regexPattern = new RegExp(
pattern.replace(/:(\w+)/g, (_, paramName) => {
paramNames.push(paramName)
return '([a-zA-Z0-9]+)'
})
)
const matchResult = url.match(regexPattern)
if (!matchResult) return false
const params = {}
for (let i = 0; i < paramNames.length; i++) {
params[paramNames[i]] = matchResult[i + 1]
}
return params
}
62 changes: 62 additions & 0 deletions elevate-scheduler/utils/requester.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
const http = require('http')
const https = require('https')
const { matchPathsAndExtractParams } = require('../utils/patternMatcher')
const routesConfig = require('../constants/routes')
const { pathParamSetter } = require('../utils/pathParamSetter')
const axios = require('axios')

const handleInterfaceError = (res, err) => {
console.log('Error: ', err)
res.writeHead(500, { 'Content-Type': 'text/plain' })
res.end('Interface Server Error')
}

const passThroughRequester = async (req, res) => {
try {
const sourceBaseUrl = req.protocol + '://' + req.headers.host + '/'
const sourceUrl = new URL(req.originalUrl, sourceBaseUrl)
const route = routesConfig.routes.find((route) => route.sourceRoute === req.sourceRoute)
const params = matchPathsAndExtractParams(route.sourceRoute, req.originalUrl)
const targetRoute = pathParamSetter(route.targetRoute.path, params)
const parsedUrl = new URL(targetRoute, req.baseUrl)
const options = {
method: req.method,
headers: req.headers,
hostname: parsedUrl.hostname,
port: parsedUrl.port,
path: parsedUrl.pathname + sourceUrl.search,
}
console.log({
sourceBaseUrl,
sourceUrl,
route,
params,
targetRoute,
parsedUrl,
options,
})
const proxyReq = (parsedUrl.protocol === 'https:' ? https : http).request(options, (proxyRes) => {
res.writeHead(proxyRes.statusCode, proxyRes.headers)
proxyRes.pipe(res, { end: true })
})
proxyReq.on('error', (err) => {
handleInterfaceError(res, err)
})
req.pipe(proxyReq, { end: true })
} catch (err) {
handleInterfaceError(res, err)
}
}

const post = async (baseUrl, route, requestBody, headers) => {
const url = baseUrl + route
const response = await axios.post(url, requestBody, { headers })
return response.data
}

const requesters = {
passThroughRequester,
post,
}

module.exports = requesters