Created
September 30, 2020 14:34
-
-
Save muralikrishnat/16ce59384e8f5d520d561009cb27018a to your computer and use it in GitHub Desktop.
NodeJS API creation
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module.exports = { | |
name: 'basic', | |
'get': function() { | |
}, | |
'post': function({ | |
request, | |
response, | |
sendResponseObj, | |
db, | |
queryParams, | |
payload | |
}) { | |
sendResponseObj({ | |
data: { | |
success: true | |
} | |
}); | |
}, | |
'delete': function() { | |
} | |
}; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const { initServer } = require('./server'); | |
let port = process.env.PORT || 5656, | |
folder = 'build', | |
endpoint = "dev", | |
ssl = true, | |
sslPort = process.env.SSL_PORT || 4443, | |
host = '127.0.0.1'; | |
if (process.argv) { | |
process.argv.forEach((p) => { | |
if (p.indexOf('--port=') >= 0) { | |
port = parseInt(p.split('=')[1]); | |
} | |
}); | |
process.argv.forEach((p) => { | |
if (p.indexOf('--ssl-port=') >= 0) { | |
sslPort = parseInt(p.split('=')[1]); | |
} | |
}); | |
process.argv.forEach((p) => { | |
if (p.indexOf('--folder=') >= 0) { | |
folder = p.split('=')[1]; | |
} | |
}); | |
process.argv.forEach((p) => { | |
if (p.indexOf('--endpoint=') >= 0) { | |
endpoint = p.split('=')[1]; | |
} | |
}); | |
process.argv.forEach((p) => { | |
if (p.indexOf('--host=') >= 0) { | |
host = p.split('=')[1]; | |
} | |
}); | |
process.argv.forEach((p) => { | |
if (p.indexOf('--ssl=') >= 0) { | |
if (p.split('=')[1] && p.split('=')[1] === 'false') { | |
ssl = false; | |
} | |
} | |
}); | |
} | |
const { getDB } = require('./db-utils/index.js'); | |
const configs = require('./configs')(); | |
initServer({ | |
fePort: port, | |
folder, | |
sslPort, | |
db: getDB(configs.DATABASE_CONFIG) | |
}); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var fs = require('fs'); | |
var path = require('path'); | |
var url = require('url'); | |
const querystring = require('querystring'); | |
const formidable = require('formidable'); | |
var jwt = require('jsonwebtoken'); | |
const jwtKey = '1234567890abcdefghijklmnopqrstuvwxyz'; | |
var { sendResponse } = require('./utils/index'); | |
var unrestrictedActions = [ | |
'version', | |
'authenticate', | |
'database', | |
'forgotpassword', | |
'changepassword', | |
'registration' | |
]; | |
const { checkForFunction } = require('./functions/index'); | |
const configs = require('./configs')(); | |
var httpProxy = require('http-proxy'); | |
var proxy = httpProxy.createProxyServer({}); | |
var initServer = function({ | |
fePort = 5656, | |
folder = 'dist', | |
sslPort = 4443, | |
db | |
}) { | |
let requestHandler = async (request, response) => { | |
console.log(`[LOG ${request.method}]: ${request.url}`); | |
let checkAuthentication = true; | |
let allowRequest = true; | |
let queryPath = url.parse(request.url); | |
let queryParams = querystring.parse(queryPath.query); | |
let authorizationMessage = 'Authorization token is required to access this end point'; | |
if (unrestrictedActions.indexOf(queryParams.action) >= 0 || (!queryParams.action)) { | |
checkAuthentication = false; | |
} | |
let loggedUserInfo = null; | |
if (checkAuthentication) { | |
if (request.headers && request.headers.authorization) { | |
let token = request.headers.authorization.replace('Bearer ', ''); | |
try { | |
loggedUserInfo = jwt.verify(token, jwtKey); | |
allowRequest = true; | |
} catch (e) { | |
allowRequest = false; | |
authorizationMessage = 'Authorization token is not valid'; | |
} | |
} else { | |
allowRequest = false; | |
} | |
} | |
if (allowRequest) { | |
let sendResponseObj = (body) => { | |
sendResponse({ | |
request, | |
response, | |
body: JSON.stringify(body) | |
}); | |
} | |
if (request.method === 'OPTIONS') { | |
sendResponse({ | |
request, | |
response | |
}); | |
} else { | |
let foundRoute = false; | |
if (request.url.indexOf('/api') >= 0) { | |
if (checkForFunction({ | |
request, | |
response, | |
sendResponseObj, | |
db, | |
queryParams, | |
user: loggedUserInfo, | |
configs | |
})) { | |
foundRoute = true; | |
} | |
} | |
if (!foundRoute) { | |
if (process.env.NODE_ENV === 'dev' && request.url.indexOf('/upload-files') < 0) { | |
proxy.web(request, response, { target: 'http://localhost:8686' }); | |
} else { | |
let parsedUrl = url.parse(request.url); | |
let fileName = parsedUrl.pathname === '/' ? 'index.html' : parsedUrl.pathname; | |
let folderToServe = request.url.indexOf('/upload-files') < 0 ? folder : 'upload-files'; | |
let filePath = path.join(__dirname, folderToServe, fileName.replace('upload-files', '')); | |
if (fs.existsSync(filePath)) { | |
var stat = fs.statSync(filePath); | |
let contentType = 'application/json'; | |
let fExtension = fileName.substr(fileName.lastIndexOf('.')) | |
switch (fExtension) { | |
case '.html': | |
contentType = 'text/html'; | |
break; | |
case '.icon': | |
contentType = 'image/x-icon'; | |
break; | |
case '.svg': | |
contentType = 'image/svg+xml'; | |
break; | |
case '.css': | |
contentType = 'text/css'; | |
break; | |
case '.js': | |
contentType = 'application/javascript'; | |
break; | |
default: | |
break; | |
} | |
response.writeHead(200, { | |
'Content-Type': contentType, | |
'Content-Length': stat.size | |
}); | |
var readStream = fs.createReadStream(filePath); | |
readStream.pipe(response); | |
} else { | |
let filePath = path.join(__dirname, folder, 'index.html'); | |
if (fs.existsSync(filePath)) { | |
let stat = fs.statSync(filePath); | |
let contentType = 'text/html'; | |
response.writeHead(200, { | |
'Content-Type': contentType, | |
'Content-Length': stat.size | |
}); | |
let readStream = fs.createReadStream(filePath); | |
readStream.pipe(response); | |
} else { | |
response.end(); | |
} | |
} | |
} | |
} | |
} | |
} else { | |
sendResponse({ | |
request, | |
response, | |
body: JSON.stringify({ | |
error: { | |
code: 'NOT_AUTHORIZED', | |
message: authorizationMessage | |
} | |
}) | |
}); | |
} | |
}; | |
require('http').createServer(requestHandler).listen(fePort, () => { | |
console.log(`Server Listening on ${fePort}`); | |
}); | |
// let certOptions = { | |
// key: fs.readFileSync('ssl/server.key'), | |
// cert: fs.readFileSync('ssl/server.crt') | |
// }; | |
// return require('https').createServer(certOptions, requestHandler).listen(sslPort, () => { | |
// console.log('Secure Server Listining on ' + sslPort); | |
// }); | |
} | |
module.exports = { | |
initServer | |
}; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const bcrypt = require('bcrypt'); | |
function getNonObject(objToCheck) { | |
if (typeof objToCheck === 'boolean') { | |
return { | |
'BOOL': objToCheck | |
}; | |
} else if(typeof objToCheck === 'number') { | |
return { | |
'N': objToCheck + '' | |
}; | |
} else { | |
return { | |
'S': objToCheck | |
}; | |
} | |
} | |
function s5() { | |
return Math.floor((1 + Math.random()) * 0x10000) | |
.toString(16) | |
.substring(0); | |
} | |
function subData(data) { | |
let updatedData = {}; | |
if (typeof data === 'object' && data instanceof Array) { | |
let listData = []; | |
data.forEach(item => { | |
let itemObj = {}; | |
if (typeof item === 'object'){ | |
Object.keys(item).forEach(itm => { | |
if (typeof item[itm] === 'string') { | |
itemObj[itm] = { | |
"S": item[itm] | |
}; | |
} else if(typeof item[itm] === 'boolean') { | |
itemObj[itm] = { | |
"BOOL": item[itm] | |
}; | |
} else if(typeof item[itm] === 'number') { | |
itemObj[itm] = { | |
"N": item[itm] + '' | |
}; | |
} else { | |
itemObj[itm] = subData(item[itm]); | |
} | |
}); | |
} else { | |
itemObj = getNonObject(item); | |
} | |
let toSetMap = {}; | |
if (itemObj['S'] || itemObj['L'] || itemObj['BOOL']) { | |
toSetMap = itemObj; | |
} else { | |
toSetMap['M'] = itemObj; | |
} | |
listData.push(toSetMap); | |
}); | |
updatedData['L'] = listData; | |
} else if (typeof data === 'object' && data !== null && data !== undefined) { | |
let objSet = {}; | |
Object.keys(data).forEach(item => { | |
objSet[item] = getNonObject(data[item]); | |
}); | |
updatedData['M'] = objSet; | |
} else { | |
if (data !== null && data !== undefined) { | |
updatedData = getNonObject(data); | |
} | |
} | |
return updatedData; | |
} | |
function subDataParse(data) { | |
if (data['S']) { | |
return data['S']; | |
} | |
if (data['BOOL']) { | |
return data['BOOL']; | |
} | |
if (data['N']) { | |
return data['N']; | |
} | |
if (data['M']) { | |
let mData = {}; | |
Object.keys(data['M']).forEach(item => { | |
mData[item] = subDataParse(data['M'][item]); | |
}); | |
return mData; | |
} | |
return data; | |
} | |
var allowedHeaders = ['Authorization', 'Content-Type', 'x-api-key', 'authtype', 'username', 'name']; | |
module.exports = { | |
encrypt(opts) { | |
return new Promise((res, rej) => { | |
bcrypt.hash(opts.text, 3, function(err, hash) { | |
// console.log('hash', hash); | |
// bcrypt.compare("murali", hash, function(err, result) { | |
// console.log("result", result); | |
// }); | |
res({ | |
hash | |
}); | |
}); | |
}); | |
}, | |
compareHash(opts) { | |
return new Promise((res, rej) => { | |
bcrypt.compare(opts.text, opts.hash, function(err, result) { | |
res({ | |
result | |
}); | |
}); | |
}); | |
}, | |
sendResponse(opts) { | |
let response = opts.response; | |
let request = opts.request; | |
response.setHeader('Access-Control-Allow-Origin', request.headers.origin || '*'); | |
response.setHeader('Access-Control-Allow-Headers', allowedHeaders.join(',')); | |
response.setHeader('Access-Control-Allow-Methods', 'GET,POST,DELETE,PATCH, OPTIONS'); | |
response.setHeader('Access-Control-Allow-Credentials', true); | |
response.writeHead(200, { | |
'Content-Type': opts.contentType || 'application/json' | |
}); | |
if (opts.body || opts.data) { | |
response.end(typeof opts.body === 'string' ? opts.body : JSON.stringify(opts.body)); | |
} else { | |
response.end(); | |
} | |
}, | |
generateDataSchema(data) { | |
let updatedData = {}; | |
Object.keys(data).forEach(item => { | |
if (data[item]) { | |
updatedData[item] = subData(data[item]); | |
} | |
}); | |
return updatedData; | |
}, | |
guid(len) { | |
function s4() { | |
return Math.floor((1 + Math.random()) * 0x10000) | |
.toString(16) | |
.substring(1); | |
} | |
if (len == 8) { | |
return s4() + s4(); | |
} | |
if (len == 4) { | |
return s4(); | |
} | |
return s4() + s4() + s4() + s4() + s4() + s4() + (new Date).getTime().toString(16); | |
}, | |
generateFilterSchema(data) { | |
let updatedData = this.generateDataSchema(data); | |
let objs = Object.keys(data); | |
let exprs = []; | |
let values = {}; | |
let names = {}; | |
let plainValues = {}; | |
for(let i = 0; i < objs.length; i++) { | |
let cardId = s5(); | |
names['#' + cardId] = objs[i]; | |
values[':' + cardId] = updatedData[objs[i]]; | |
plainValues[':' + cardId] = data[objs[i]]; | |
exprs.push(`#${cardId} = :${cardId}`); | |
}; | |
let objToReturn = { | |
"Epressions": exprs, | |
"Expression": exprs.join(', '), | |
"ExpressionAttributeValues": values, | |
"ExpressionAttributeValuesPlain": plainValues, | |
"ExpressionAttributeNames": names | |
}; | |
return objToReturn; | |
}, | |
parseJsonToData(data) { | |
let updatedData = {}; | |
Object.keys(data).forEach(item => { | |
if (data[item]['S']) { | |
updatedData[item] = data[item]['S']; | |
} | |
if (data[item]['BOOL']) { | |
updatedData[item] = data[item]['BOOL']; | |
} | |
if (data[item]['N']) { | |
updatedData[item] = data[item]['N']; | |
} | |
if (data[item]['L']) { | |
let list = []; | |
data[item]['L'].forEach(listItem => { | |
list.push(subDataParse(listItem)); | |
}); | |
updatedData[item] = list; | |
} | |
}); | |
return updatedData; | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment