Notes
Notes - notes.io |
const express = require('express');
const request = require('request');
const multer = require('multer');
const objectAssign = require('object-assign');
import { graphqlExpress, graphiqlExpress } from 'apollo-server-express';
import cors from 'cors';
import mockSchema from './mock-schema';
const applicationConfig = require('./config');
const app = express();
let cookieVal;
if (!applicationConfig.isLiveAPI) {
app.use(require('body-parser').text());
}
app.locals.paymentsConfig = applicationConfig.paymentsConfig;
const dynamicEndPoints = require('glob').sync('./endpoints/**/*.js');
let dynamicEndPointMapping = {};
dynamicEndPoints.map((dEP) => {
dynamicEndPointMapping = objectAssign(dynamicEndPointMapping, require(dEP));
});
const dynamicEndPointUrls = Object.keys(dynamicEndPointMapping);
var cookieReference = '';
app.post('/s2b/bulkImport/upload', multer().single('upl'), function (req, res) {
if (req.file) {
res.json({ err: false, files: req.file });
}
});
/* service router which will handle URL's after the base url */
const service = express.Router();
service.use(function (req, res, next) {
next();
});
/* upload and storage are for mock file upload services */
const storage = multer.diskStorage({
destination: function (req, file, callback) {
callback(null, 'uploads/');
},
filename: function (req, file, callback) {
callback(null, file.fieldname + '-' + Date.now());
}
});
const upload = multer({ storage }).single('file');
/* OPTIONS requests for CORS handled here */
service.options('/*', function (req, res) {
console.log(req.get('Origin'));
res.header('Access-Control-Allow-Origin', req.get('Origin'));
res.header('Access-Control-Allow-Credentials', 'true');
res.header(
'Access-Control-Allow-Headers',
'Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With, correlationid, product, categoryid, entityid, filesize, doccode, entitytype, filedesc, filename, nounce, contentType, userid, encryptFlag, servicecontext'
);
res.header('Access-Control-Expose-Headers', 'correlationId, nounce');
res.sendStatus(200);
});
/* GET requests handler */
service.get('/*', function (req, res) {
console.log(req.get('Origin'));
/* CORS request support handled here for the post requests */
res.header('Access-Control-Allow-Origin', req.get('Origin'));
res.header('Access-Control-Allow-Credentials', 'true');
res.header(
'Access-Control-Allow-Headers',
'Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With, correlationid, product, categoryid, entityid, filesize, doccode, entitytype, filedesc, filename, nounce, contentType, encryptFlag'
);
res.header('Access-Control-Expose-Headers', 'correlationId, nounce');
console.log('Service: ' + req.url);
var splitURL = req.url.split('?');
var url = splitURL[0];
var serviceDetails =
applicationConfig.serviceConfig[url.replace(//v1.0/g, '')];
var isLiveAPIMode = applicationConfig.isLiveAPI;
if (serviceDetails) {
var isMockEnabled = serviceDetails.isMockEnabled;
var newUrl;
var port;
if (applicationConfig.mode === 'API') {
port = serviceDetails.port || '8080';
newUrl =
applicationConfig.APIBaseServerIP +
':' +
port +
'/s2b/global/corporate/api' +
req.url;
} else {
port = serviceDetails.port || '8182';
newUrl =
applicationConfig.CSLBaseServerIP +
':' +
port +
'/s2b/global/corporate/api' +
req.url;
}
console.log('New URL: ' + newUrl);
if (!isMockEnabled || isLiveAPIMode) {
console.log('in live mode');
if (req.headers['cookie']) {
var cookie = req.headers['cookie'] + '; ' + 'Path=/; secure; httponly;';
req.headers['cookie'] = cookie;
cookieReference = cookie;
}
if (isLiveAPIMode) {
req.headers['cookie'] = cookieReference;
}
req
.pipe(
request({
url: newUrl,
rejectUnauthorized: false,
headers: req.headers
})
)
.on('response', function (response) {
console.log(response.headers['set-cookie']);
if (response.headers['set-cookie']) {
var cookie = response.headers['set-cookie'][0].replace(
'secure; ',
''
);
response.headers['set-cookie'] = cookie;
console.log('inside cookie');
}
console.log('outside cookie');
res.writeHead(200, response.headers);
})
.on('error', function (err) {
if (err.errno == 'ETIMEDOUT') {
console.log('Error : Request timed out');
} else {
console.log('Error : ' + err);
}
res.sendStatus(500);
})
.pipe(res);
} else {
console.log('in mock mode');
var isFileUpload = serviceDetails.isFileUpload;
if (isFileUpload) {
console.log('File upload service');
upload(req, res, function (err) {
if (err) {
console.log(err);
return res.end('Error uploading file.');
}
res.end('File is uploaded');
console.log('File is uploaded');
});
} else {
var mockResponse = require('./mock/' + serviceDetails.mockDataSource);
if (mockResponse) {
res.send(mockResponse);
} else {
// Error logging for mock data fail should be handled here
console.log('Unable to fetch mock response data for ' + req.url);
res.sendStatus(500);
}
}
}
} else {
// Error logging for mock data fail should be handled here
console.log('Unable to find the response for ' + req.url);
res.sendStatus(500);
}
});
/* POST requests are handled here */
service.post('/*', function (req, res) {
console.log(req.get('Origin'));
/* CORS request support handled here for the post requests */
res.header('Access-Control-Allow-Origin', req.get('Origin'));
res.header('Access-Control-Allow-Credentials', 'true');
res.header(
'Access-Control-Allow-Headers',
'Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With, correlationid, product, categoryid, entityid, filesize, doccode, entitytype, filedesc, filename, nounce, contentType'
);
res.header('Access-Control-Expose-Headers', 'correlationId, nounce');
console.log('Service: ' + req.url);
var urlPath = req.url.replace(//v1.0/g, '');
var serviceDetails = applicationConfig.serviceConfig[urlPath] || {};
var containsDynamic =
req.url.includes('/search/favourites/delete') ||
req.url.includes('/search/favourites/add');
console.log(containsDynamic);
var isLiveAPIMode = applicationConfig.isLiveAPI;
if (serviceDetails || containsDynamic) {
var isMockEnabled =
applicationConfig.enableMockForAll || serviceDetails.isMockEnabled;
var newUrl;
if (applicationConfig.mode === 'API') {
let port = '8080';
newUrl =
applicationConfig.APIBaseServerIP +
':' +
port +
'/s2b/global/corporate/api' +
req.url;
} else {
let port = serviceDetails.port || '8182';
newUrl =
applicationConfig.CSLBaseServerIP +
':' +
port +
'/s2b/global/corporate/api' +
req.url;
}
console.log(newUrl);
if (!isMockEnabled || isLiveAPIMode) {
console.log('in live mode');
req.headers['cookie'] = cookieVal;
if (req.headers['cookie']) {
var cookie = req.headers['cookie'] + '; ' + 'Path=/; secure; httponly;';
req.headers['cookie'] = cookie;
cookieReference = cookie;
}
if (isLiveAPIMode) {
req.headers['cookie'] = cookieReference;
}
req
.pipe(
request({
url: newUrl,
rejectUnauthorized: false
})
)
.on('response', function (response) {
console.log(response.headers['set-cookie']);
if (response.headers['set-cookie']) {
let cookie = '';
response.headers['set-cookie'].forEach((value) => {
cookie += value.substr(0, value.indexOf(';') + 1);
});
cookieVal = cookie;
console.log('inside cookie');
}
console.log('outside cookie');
res.writeHead(200, response.headers);
})
.on('error', function (err) {
if (err.errno == 'ETIMEDOUT') {
console.log('Error : Request timed out');
} else {
console.log('Error : ' + err);
}
res.sendStatus(500);
})
.pipe(res);
} else {
console.log('in mock mode');
var isFileUpload = serviceDetails.isFileUpload;
if (isFileUpload) {
console.log('File upload service');
upload(req, res, function (err) {
if (err) {
console.log(err);
return res.end('Error uploading file.');
}
res.end('File is uploaded');
console.log('File is uploaded');
});
} else {
if (dynamicEndPointUrls.includes(urlPath)) {
return dynamicEndPointMapping[urlPath](req, res);
}
var mockResponse = require('./mock/' + serviceDetails.mockDataSource);
if (mockResponse) {
res.send(mockResponse);
} else {
// Error logging for mock data fail should be handled here
console.log('Unable to fetch mock response data for ' + req.url);
res.sendStatus(500);
}
}
}
} else {
// Error logging for mock data fail should be handled here
console.log('Unable to find the response for ' + req.url);
res.sendStatus(500);
}
});
/* Base url of the server after which it is routed to the service router */
app.use('/s2b/global/corporate/api', service);
app.use(cors());
if (process.env.RUN_SERVER_IN_MOCK_MODE) {
app.use(
'/s2b/global/corporate/graphql',
require('body-parser').json(),
graphqlExpress({ schema: mockSchema })
);
app.use(
'/s2b/global/corporate/graphiql',
graphiqlExpress({ endpointURL: '/s2b/global/corporate/graphql' })
);
}
/* else {
app.all('/s2b/global/corporate/graphql', (req, res) => {
res.send('Back end graphQL is still being implemented.');
});
app.all('/s2b/global/corporate/graphiql', (req, res) => {
res.send('Back end graphQL is still being implemented.');
});
}*/
app.listen(4201, function () {
console.log('server started on port 4201');
});
|
Notes.io is a web-based application for taking notes. You can take your notes and share with others people. If you like taking long notes, notes.io is designed for you. To date, over 8,000,000,000 notes created and continuing...
With notes.io;
- * You can take a note from anywhere and any device with internet connection.
- * You can share the notes in social platforms (YouTube, Facebook, Twitter, instagram etc.).
- * You can quickly share your contents without website, blog and e-mail.
- * You don't need to create any Account to share a note. As you wish you can use quick, easy and best shortened notes with sms, websites, e-mail, or messaging services (WhatsApp, iMessage, Telegram, Signal).
- * Notes.io has fabulous infrastructure design for a short link and allows you to share the note as an easy and understandable link.
Fast: Notes.io is built for speed and performance. You can take a notes quickly and browse your archive.
Easy: Notes.io doesn’t require installation. Just write and share note!
Short: Notes.io’s url just 8 character. You’ll get shorten link of your note when you want to share. (Ex: notes.io/q )
Free: Notes.io works for 12 years and has been free since the day it was started.
You immediately create your first note and start sharing with the ones you wish. If you want to contact us, you can use the following communication channels;
Email: [email protected]
Twitter: http://twitter.com/notesio
Instagram: http://instagram.com/notes.io
Facebook: http://facebook.com/notesio
Regards;
Notes.io Team