SHARE
TWEET

Untitled

a guest May 19th, 2017 48 in 3 days
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. app.post("/api/create", function (req, res) {
  2.     var body = '';
  3.     req.on('data', function (data) {
  4.         body += data;
  5.         // If someone is trying to nuke RAM, nuke the request
  6.         // 1e6 === 1 * Math.pow(10, 6) === 1 * 1000000 ~~~ 1MB
  7.         if (body.length > 1e6) {
  8.             req.connection.destroy();
  9.         }
  10.     });
  11.     req.on('end', function () {
  12.         process_request(body);
  13.     });
  14.    
  15.     function process_request(body) {
  16.         // Continue with parsing json string in body and inserting organisation
  17.         // json string is stored in the body variable
  18.         var org = JSON.parse(body);
  19.         insert_organisation(org, 0);
  20.         res.end('INSERTED');
  21.     }
  22.    
  23.     function insert_organisation(org, parent_id) {
  24.         // normally check if organisation exists
  25.         var sQuery = "INSERT INTO orgs (org_name) VALUES (?) ON DUPLICATE KEY UPDATE org_name = VALUES(org_name), id=LAST_INSERT_ID(id)";
  26.         connection.query(sQuery, [org.org_name], function (error, results, fields) {
  27.             if (error) {
  28.                 console.log(error);
  29.                 return;
  30.             }
  31.             // Insert relation if any
  32.             var new_parent_id = results.insertId;
  33.             if (new_parent_id && parent_id > 0) {
  34.                 var rQuery = "INSERT INTO orgs_relation (org_id, parent_org_id) VALUES (?, ?) ON DUPLICATE KEY UPDATE org_id = VALUES(org_id)";
  35.                 connection.query(rQuery, [new_parent_id, parent_id], function (error, results, fields) {
  36.                     if (error) {
  37.                         console.log(error);
  38.                         return;
  39.                     }
  40.                     console.log(new_parent_id + ' - ' + parent_id + ' relation inserted');
  41.                 });
  42.             }
  43.             if (new_parent_id && org.daughters && org.daughters.length) {
  44.                 for (var i = 0; i < org.daughters.length; i++) {
  45.                     insert_organisation(org.daughters[i], new_parent_id);
  46.                 }
  47.             }
  48.             console.log(org.org_name + ' inserted!');
  49.         });
  50.     }
  51.    
  52. });
RAW Paste Data
Want to get better at JavaScript?
Learn to code JavaScript in 2017
Top