93 lines
2.6 KiB
JavaScript
93 lines
2.6 KiB
JavaScript
|
'use strict';
|
||
|
|
||
|
// modules
|
||
|
const express = require('express');
|
||
|
const http = require('http');
|
||
|
const https = require('https');
|
||
|
const parse = require('node-html-parser').parse;
|
||
|
|
||
|
// HTTP status codes by name
|
||
|
const codes = require('./http-codes');
|
||
|
|
||
|
const routerHandling = require('../middleware/router-handling');
|
||
|
|
||
|
/**
|
||
|
* getHtml: REST get request returning HTML page response
|
||
|
* @param {object} options: http options object
|
||
|
* @param {function} onResult: callback to pass the results JSON object(s) back
|
||
|
*/
|
||
|
const getHtml = (options, onResult) => {
|
||
|
let port = (options.port === 443) ? https : http;
|
||
|
let req = port.request(options, (res) => {
|
||
|
let output = '';
|
||
|
res.setEncoding('utf8');
|
||
|
|
||
|
res.on('data', (chunk) => {
|
||
|
output += chunk;
|
||
|
});
|
||
|
|
||
|
res.on('end', () => {
|
||
|
if (res.statusCode === 301) { // follow redirect
|
||
|
const location = res.headers.location;
|
||
|
const baseUrl = ((options.port === 443) ? 'https' : 'http') + '://' + options.host;
|
||
|
options.path = location.replace(baseUrl, '');
|
||
|
getHtml(options, (status, redirectData) => {
|
||
|
onResult(status, redirectData);
|
||
|
});
|
||
|
} else {
|
||
|
onResult(res.statusCode, output);
|
||
|
}
|
||
|
});
|
||
|
|
||
|
res.on('error', (err) => {
|
||
|
onResult(500, err);
|
||
|
});
|
||
|
});
|
||
|
req.end();
|
||
|
};
|
||
|
|
||
|
const defaulUserReqOptions = {
|
||
|
host: 'opt4.net',
|
||
|
port: 443,
|
||
|
path: '/dashboard/index.php?user/',
|
||
|
method: 'GET',
|
||
|
};
|
||
|
|
||
|
const slotting = new express.Router();
|
||
|
|
||
|
// routes **********************
|
||
|
slotting.route('/user/:id')
|
||
|
.get((req, res, next) => {
|
||
|
const userId = req.params.id;
|
||
|
const options = Object.assign({}, defaulUserReqOptions);
|
||
|
options.path = options.path.concat(userId);
|
||
|
|
||
|
getHtml(options, (status, targetRes) => {
|
||
|
if (status !== codes.success) {
|
||
|
const err = new Error('Can not resolve user from remote service');
|
||
|
err.status = codes.notfound;
|
||
|
return next(err);
|
||
|
}
|
||
|
|
||
|
const root = parse(targetRes);
|
||
|
const userNameEl = root.querySelector('.contentTitle');
|
||
|
let user = {
|
||
|
name: userNameEl.childNodes[0].rawText.trim(),
|
||
|
};
|
||
|
|
||
|
res.locals.items = user;
|
||
|
res.locals.processed = true;
|
||
|
return next();
|
||
|
});
|
||
|
})
|
||
|
|
||
|
.all(
|
||
|
routerHandling.httpMethodNotAllowed
|
||
|
);
|
||
|
|
||
|
// this middleware function can be used, if you like or remove it
|
||
|
// it looks for object(s) in res.locals.items and if they exist, they are send to the client as json
|
||
|
slotting.use(routerHandling.emptyResponse);
|
||
|
|
||
|
module.exports = slotting;
|