const express = require('express');
const router = express.Router();
const SigNRouter = require('../src/signstore');
const { createClient } = require('../src/data');
const { constants } = require('../src/constants');
/**
* Take the request body and extract the payload as a string, without parsing to JSON.
* First get a substring starting at '"payload"' and ending at the end of the string.
* Next get the index of the first '{', this will be our starting point. Then loop through each character of the substring with a counter
* for the number of '{' that appear in the string. Add 1 to the counter for each '{' and subtract 1 for each '}'.
* When the counter reaches 0, we have found the index of the last '}'.
* Then our result will be a substring of that starting at the starting point and ending at the last '}'.
* @param {string} reqBody string representation of the request body before being parsed
*/
const extractPayload = (reqBody) => {
const payloadStart = reqBody.indexOf('"payload"');
const payloadString = reqBody.substring(payloadStart);
const payloadStartIndex = payloadString.indexOf('{');
let counter = 0;
let payloadEndIndex = 0;
let stringed = false;
for (let i = payloadStartIndex; i < payloadString.length; i++) {
if (payloadString[i] === '\\') {
i++;
continue;
}
if (payloadString[i] === '"') {
stringed = !stringed;
continue;
}
if (payloadString[i] === '{' && !stringed) {
counter++;
}
if (payloadString[i] === '}' && !stringed) {
counter--;
}
if (counter === 0) {
payloadEndIndex = i;
break;
}
}
return payloadString.substring(payloadStartIndex, payloadEndIndex + 1);
}
router.post('/*', async (req, res, next) => {
const dbClient = await createClient(constants.mongo.connectionUri());
console.log('Payload: ', extractPayload(req.body));
console.log(`Processing request on route ${req.path}`, req.body);
const reqRes = await SigNRouter.route(req.path, JSON.parse(req.body), extractPayload(req.body), dbClient);
res.send(reqRes);
});
module.exports = router;