diff --git a/nodejs.setup b/nodejs.setup deleted file mode 100755 index a82a5b3..0000000 --- a/nodejs.setup +++ /dev/null @@ -1,2 +0,0 @@ -#!/bin/bash -sudo apt install nodejs diff --git a/srv.setup b/srv.setup new file mode 100755 index 0000000..c900e34 --- /dev/null +++ b/srv.setup @@ -0,0 +1,4 @@ +#!/bin/bash +apt install nodejs +mkdir -p /var/log/consult +chgrp www-data /var/log/consult diff --git a/srv/srv.consult.js b/srv/srv.consult.js new file mode 100644 index 0000000..ea2d03a --- /dev/null +++ b/srv/srv.consult.js @@ -0,0 +1,89 @@ +let fs = require("fs"); +let http = require("http"); + +//let DST_DIR = "/var/log"; +let DST_DIR = "/tmp"; +let TEMPLATE_FILE_NAME = "%DIR%/consult_%UUID%"; +let URL_CONSULT = "/api/consult"; + +let srv = http.createServer((req, res) => { + // POST + if (req.method == "POST") { + var dat = ""; + req.on("data", (chunk) => { + dat += chunk; + }); + req.on("end", () => { + // /api/consult + if (isConsultationRequestValid(req, dat)) { + saveUserContacts(dat); + returnSuccess(res); + } else { + returnError(res); + } + }); + } else { + returnError(res); + } +}); + +function isConsultationRequestValid(req, dat) { + var json = {}; + try { + json = JSON.parse(dat); + } catch (e) { + //console.log("ERR isCRV error:", e); + } + + if ( + req.url == URL_CONSULT && + req.method == "POST" && + "name" in json && + "phone" in json + ) { + return true; + } + + return false; +} + +function returnError(res) { + res.writeHead(404, { "Content-Type": "text/html" }); + res.end(` +404 Not Found + +

404 Not Found

+
nginx/1.24.0 (Ubuntu)
+ +`); +} + +function returnSuccess(res) { + res.writeHead(200, { "Content-Type": "application/json;charset=UTF-8" }); + let dat = { code: 4 }; + res.end(JSON.stringify(dat)); +} + +function saveUserContacts(dat) { + let fileName = TEMPLATE_FILE_NAME + .replaceAll("%DIR%", DST_DIR) + .replaceAll("%UUID%", uuidString()); + fs.writeFile(fileName, dat, (err) => { + console.log("ИГР saveUC fileN/err:", fileName, err); + }); +} + +// https://stackoverflow.com/a/2117523 +function uuidString() { + return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace( + /[xy]/g, + function(c) + { + var r = Math.random() * 16 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8); + return v.toString(16); + } + ); +} + +// Launch. +srv.listen(8001); diff --git a/srv/test b/srv/test new file mode 100755 index 0000000..50f9a3c --- /dev/null +++ b/srv/test @@ -0,0 +1,3 @@ +#!/bin/bash +curl -X POST -d '.' http://localhost:8001/api/consult +curl -X POST -d '{"name":"test-name","phone":"+79001002030"}' http://localhost:8001/api/consult