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

Samiksha apis #136

Open
wants to merge 15 commits into
base: unnati
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
702 changes: 702 additions & 0 deletions elevate-survey/constants/routes.js

Large diffs are not rendered by default.

13 changes: 13 additions & 0 deletions elevate-survey/controllers/orchestrationController.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
const routesConfig = require('../constants/routes')
const samikshaController = require('./project')
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 samikshaController[selectedRouteConfig.targetRoute.functionName](req, res, responses)
}

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

// const createUser = async (req, res, responses) => {
// const selectedConfig = routeConfigs.routes.find((obj) => obj.sourceRoute === req.sourceRoute)
// return await requesters.post(req.baseUrl, selectedConfig.targetRoute.path, req.body)
// }
// const updateUser = async (req, res, responses) => {
// const selectedConfig = routeConfigs.routes.find((obj) => obj.sourceRoute === req.sourceRoute)

// //const filteredRequestBody = requestParser.transformUpdateUserBody(req.body)
// return await requesters.patch(req.baseUrl, selectedConfig.targetRoute.path, req.body, req.headers)
// }

// const entityTypeRead = async (req, res, responses) => {
// const selectedConfig = routeConfigs.routes.find((obj) => obj.sourceRoute === req.sourceRoute)
// return await requesters.post(req.baseUrl, selectedConfig.targetRoute.path, req.body, {
// 'X-auth-token': req.headers['x-auth-token'],
// })
// }

const userController = {
// createUser,
// updateUser,
// entityTypeRead,
}

module.exports = userController
37 changes: 37 additions & 0 deletions elevate-survey/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']
}

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

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

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

module.exports = {
dependencies: getDependencies(),
routes,
createPackage,
packageMeta: getPackageMeta(),
packageRouter,
}
18 changes: 18 additions & 0 deletions elevate-survey/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
{
"name": "elevate-survey",
"version": "1.0.7",
"description": "Npm package for Elevate-survey service integration with Interface service",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "PraveenDass",
"license": "ISC",
"dependencies": {
"axios": "^1.4.0",
"express": "^4.18.2",
"lodash": "^4.17.21",
"node-fetch": "^2.7.0",
"path-to-regexp": "^6.2.1"
}
}
10 changes: 10 additions & 0 deletions elevate-survey/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-survey/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-survey/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
}
6 changes: 6 additions & 0 deletions elevate-survey/utils/requestParser.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
const _ = require('lodash')

// exports.transformUpdateUserBody = (requestBody) => {
// const allowedKeys = ['name', 'email', 'image', 'location', 'about', 'preferred_language']
// return _.pick(requestBody, allowedKeys)
// }
121 changes: 121 additions & 0 deletions elevate-survey/utils/requester.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,121 @@
const http = require('http')
const https = require('https')
const { matchPathsAndExtractParams } = require('./patternMatcher')
const routesConfig = require('../constants/routes')
const { pathParamSetter } = require('./pathParamSetter')
const axios = require('axios')
const fetch = require('node-fetch')

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)
console.log(params,'params')
const targetRoute = pathParamSetter(route.targetRoute.path, params)
console.log(route.targetRoute.path, params,'route.targetRoute.path, params')
console.log(targetRoute,'targetRoute')
console.log(req.baseUrl,'req.baseUrl')
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 = (baseUrl, route, requestBody, headers) => {
const url = baseUrl + route
return axios
.post(url, requestBody, { headers })
.then((response) => response.data)
.catch((error) => {
if (error.response) {
return error.response
}
return error
})
}
const patch = async (baseUrl, route, requestBody, headers) => {
try {
const url = baseUrl + route

const options = {
method: 'PATCH',
headers: headers,
body: JSON.stringify(requestBody),
}

const response = await fetch(url, options)

const data = await response.json()
return data
} catch (error) {
console.error(error)
throw error
}
}
const axiosPatch = async (baseUrl, route, requestBody, headers) => {
try {
const url = baseUrl + route
console.log(url, requestBody)
const config = {
headers: headers,
}
axios
.patch(url, requestBody, config)
.then((response) => {
// Handle the successful response here
console.log('PATCH request successful:', response.data)
return response.data
})
.catch((error) => {
// Handle any errors that occurred during the PATCH request
console.error('Error making PATCH request:', error)
if (error.response) {
return error.response
}
return error
})
} catch (error) {
console.error('Error making PATCH request:', error)
}
}

const requesters = {
passThroughRequester,
post,
patch,
axiosPatch,
}

module.exports = requesters