-
Notifications
You must be signed in to change notification settings - Fork 0
Review for YourCodeReview (ru) #1
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: master
Are you sure you want to change the base?
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,169 @@ | ||
| /** | ||
| * MFF HTTP-JSON-RPC CLI-client for administrative operation | ||
| */ | ||
|
|
||
| var http = require('http') | ||
|
|
||
| var JSONRPCClient = function(port, host, path = null) { | ||
| this.port = port; | ||
| this.host = host; | ||
| this.path = path; | ||
|
|
||
| this.call = function(method, params, callback) { | ||
| var requestJSON = JSON.stringify({ | ||
| 'jsonrpc': '2.0', | ||
| 'id': (new Date().getTime()), | ||
| 'method': method, | ||
| 'params': params, | ||
| 'cl': 'mffcli' | ||
| }); | ||
| var headers = { | ||
| 'host': host, | ||
| 'Content-Length': requestJSON.length, | ||
| 'Content-Type': 'application/json', | ||
| 'Accept': 'application/json' | ||
| }; | ||
|
|
||
| if (this.path === null) { | ||
| this.path = '/'; | ||
| } | ||
|
|
||
| var options = { | ||
| host: host, | ||
| port: port, | ||
| path: this.path, | ||
| headers: headers, | ||
| method: 'POST' | ||
| } | ||
|
|
||
| var buffer = ''; | ||
|
|
||
| var req = http.request(options, function(res) { | ||
| res.on('data', function(chunk) { | ||
| buffer = buffer + chunk; | ||
| }); | ||
|
|
||
| res.on('end', function() { | ||
| var decoded = {} | ||
| try { | ||
| decoded = JSON.parse(buffer); | ||
| } catch (error) { | ||
| callback(error, null); | ||
| return | ||
| } | ||
|
|
||
| if (decoded.hasOwnProperty('result')) { | ||
| callback(null, decoded.result); | ||
| } else { | ||
| callback(decoded.error, null); | ||
| } | ||
| }); | ||
|
|
||
| res.on('error', function(err) { | ||
| callback(err, null); | ||
| }); | ||
| }); | ||
|
|
||
| req.on('error', function(err) { | ||
| console.error('ClientError:', err.code); | ||
| }); | ||
|
|
||
| req.write(requestJSON); | ||
| req.end(); | ||
| }; | ||
| } | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Код, связанный с отправкой и обработкой запроса можно несколько сократить при использовании сторонней библиотеки axios или https://www.npmjs.com/package/node-fetch .
Owner
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Стараюсь не использовать внешние библиотеки или включать их технические решения в свой код There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Можно узнать, почему?
Owner
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Есть несколько моментов:
|
||
|
|
||
| const ARGUMENT_SEPARATION_REGEX = /([^=\s]+)=?\s*(.*)/; | ||
|
|
||
| function Parse(argv) { | ||
| // Removing node/bin and called script name | ||
| argv = argv.slice(2); | ||
|
|
||
| const parsedArgs = {}; | ||
| let argName, argValue; | ||
|
|
||
| argv.forEach(function(arg) { | ||
| // Separate argument for a key/value return | ||
| arg = arg.match(ARGUMENT_SEPARATION_REGEX); | ||
| arg.splice(0, 1); | ||
|
|
||
| // Retrieve the argument name | ||
| argName = arg[0]; | ||
|
|
||
| // Remove "--" or "-" | ||
| if (argName.indexOf('-') === 0) { | ||
| argName = argName.slice(argName.slice(0, 2).lastIndexOf('-') + 1); | ||
| } | ||
|
|
||
| // Parse argument value or set it to `true` if empty | ||
| argValue = | ||
| arg[1] !== '' ? | ||
| parseFloat(arg[1]).toString() === arg[1] ? | ||
| +arg[1] : | ||
| arg[1] : | ||
| true; | ||
|
|
||
| parsedArgs[argName] = argValue; | ||
| }); | ||
|
|
||
| return parsedArgs; | ||
| } | ||
|
|
||
| /** Read args from cmd */ | ||
| var args = Parse(process.argv); | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Возможно, для парсинга аргументов имеет смысл воспользоваться готовыми библиотеками, на подобие minimist
Owner
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Стараюсь не использовать внешние библиотеки или включать их технические решения в свой код. |
||
| /** Set from args or use defs */ | ||
| var host = args.host || '127.0.0.1' | ||
| var port = args.port || 20799 | ||
| var path = args.path || '/' | ||
| var method = args.method || 'ping' | ||
| var params = {} | ||
|
|
||
| for (const key in args) { | ||
| if (Object.hasOwnProperty.call(args, key)) { | ||
| const value = args[key]; | ||
| switch (key) { | ||
| case 'host': | ||
| case 'port': | ||
| case 'path': | ||
| case 'method': | ||
| break; | ||
|
|
||
| default: | ||
| if (value === true) { | ||
| method = key | ||
| } else if (key.match(/^p\.(.*)$/)) { | ||
| params[key.replace(/^p\./, '')] = value | ||
| } | ||
| break; | ||
| } | ||
| } | ||
| } | ||
|
|
||
| if (Object.keys(args).length == 0) { | ||
| console.log('') | ||
| console.log(' MFF HTTP-JSON-RPC CLI-client') | ||
| console.log('') | ||
| console.log('use: node cli.js method [args,...]') | ||
| console.log(' node cli.js ping --port=20799') | ||
| console.log(' node cli.js ping --p.alpha=5 --p.beta=7 => params: {"alpha":5,"beta":7}') | ||
| console.log('') | ||
| console.log('\targ\t\treq\tdescription \tdefault') | ||
| console.log('') | ||
| console.log('\t--host\t\t\tserver host \t"127.0.0.1"') | ||
| console.log('\t--port\t\t\tserver port \t20799 (back-RPC)') | ||
| console.log('\t--path\t\t\tserver path \t"/"') | ||
| console.log('\t--p.[key]\t\tset params key \t"{}"') | ||
| console.log('\t--method\t*\texecuted method') | ||
| console.log('') | ||
| return | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
Owner
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Спасибо, буду внимательнее |
||
| } | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Библиотека commander.js предоставляет удобный интерфейс для вывода подобного рода сообщений (да и предоставляет больше возможностей для работы с командной строкой, чем упоминаемый ранее minimist )
Owner
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Стараюсь не использовать внешние библиотеки или включать их технические решения в свой код. |
||
|
|
||
| /** Run client */ | ||
| var client = new JSONRPCClient(port, host, path) | ||
| client.call(method, params, function(error, result) { | ||
| if (error) { | ||
| console.error('ServerError:', error); | ||
| } | ||
| console.log('ServerResult:', result); | ||
| }); | ||
| /** End of CLI */ | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,17 +1,59 @@ | ||
| { | ||
| "server": { | ||
| "port": 20744, | ||
| "logs": false | ||
| "rpc": { | ||
| "front": { | ||
| "active": true, | ||
| "driver": "json", | ||
| "dsn": { | ||
| "type": "front", | ||
| "host": "127.0.0.1", | ||
| "port": 20744, | ||
| "path": "/" | ||
| } | ||
| }, | ||
| "back": { | ||
| "active": true, | ||
| "driver": "json", | ||
| "dsn": { | ||
| "type": "back", | ||
| "host": "127.0.0.1", | ||
| "port": 20799, | ||
| "path": "/" | ||
| } | ||
| } | ||
| }, | ||
| "metric": { | ||
| "check": { | ||
| "interval": 15, | ||
| "run": "/usr/bin/sh /home/user/check.sh", | ||
| "notice": 20, | ||
| "warning": 35, | ||
| "error": 45, | ||
| "history": 10, | ||
| "call": "/usr/bin/sh /home/user/send.sh --metric=$1 --level=$2 --time=$3" | ||
| "test": { | ||
| "active": true, | ||
| "metric": { | ||
| "interval": 1000, | ||
| "driver": "dns", | ||
| "path": { | ||
| "rec": "google.com", | ||
| "type": "A", | ||
| "dns": "8.8.8.8" | ||
| } | ||
| }, | ||
| "call": { | ||
| "caller": "shell", | ||
| "path": "echo $1 $2 $3 >> call.log" | ||
| }, | ||
| "log": { | ||
| "logger": "local" | ||
| } | ||
| } | ||
| }, | ||
| "caller": { | ||
| "shell": { | ||
| "active": true, | ||
| "driver": "shell", | ||
| "path": "echo $1 $2 $3 >> $1.call.log" | ||
| } | ||
| }, | ||
| "logger": { | ||
| "local": { | ||
| "active": true, | ||
| "driver": "file", | ||
| "path": "./logs/$1.log" | ||
| } | ||
| } | ||
| } |
This file was deleted.
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,15 @@ | ||
| /** | ||
| * Metric From Future | ||
| * Metric Server for calculation timing of script execution time | ||
| * | ||
| * @author AlexMcArrow <alex.mcarrow@gmail.com> | ||
| * @version 0.3.0 | ||
| * @package metricfromfuture | ||
| */ | ||
|
|
||
| const server = require('./src/server') | ||
|
|
||
| var MFF = new server() | ||
| MFF.start(process.env.PATH_CONFIG || './config.json') | ||
|
|
||
| /** End of index */ |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Стоит переходить на современные стандарты и использовать
let/constThere was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Хорошее замечание, спасибо