Skip to content

Instantly share code, notes, and snippets.

@LuoZijun
Created July 20, 2015 03:18
Show Gist options
  • Save LuoZijun/9a587cb95268ff502626 to your computer and use it in GitHub Desktop.
Save LuoZijun/9a587cb95268ff502626 to your computer and use it in GitHub Desktop.
nodejs.js
#!/usr/bin/env nodejs
// -*- mode: js -*-
/*
NodeJS:
WEB: https://nodejs.org/
Package: https://www.npmjs.com/
*/
'use strict';
// Object
Object.prototype.values = function (dict){
return Object.keys(dict).map( function (k, i){
if ( typeof dict[k] === "object" ) return JSON.stringify(dict[k]);
else return dict[k];
} );
};
// var http = require('http');
var request = require("request");
var rpc_server = require('jsonrpc2');
var server = new rpc_server.Server();
// RPC Client.
var rpc = {};
rpc.call = function ( method, params, opts ){
if ( !opts ) var opts = {};
if ( !opts.callback ) opts.callback = function (){};
if ( !opts.url ) opts.url = "http://115.29.211.139:3000/";
var requestID = 1
var requestJSON = {
"jsonrpc": "2.0",
"id": requestID,
"method": method,
"params": params, // ["select * from ucentermain.common_user_bd where id=875596"]
};
var requestOption = {
"url": opts.url,
"method": "POST",
"headers": [
{"name": "content-type", "value": "application/json"}
],
"json": requestJSON
};
request( requestOption, function (error, response, body){
if ( response.statusCode != 200 || error ) {
// DEBUG
opts.callback(error, null );
} else {
// DEBUG
try{
if ( typeof body == "string" ) body = JSON.parse(body);
if ( !body.error && body.result ) {
// rpc success.
opts.callback(null, body.result );
} else {
// rpc error.
opts.callback( {"message": "unknow error.", "debug": {"error": body.error} }, null );
}
} catch ( e ) {
opts.callback( {"message": "exception." }, null );
}
}
} );
};
// response: error, result
function index (args, opt, response){
response(null, "It Work!\n");
}
function hello (args, opt, response){
response(undefined , "hi ... " );
}
function query(args, opt, response) {
// Query Sql
var rpc_server_url = "http://115.29.211.139:3000/";
var callback = function (error, result){
if (error) {
response(error, null);return;
}
response(null, result );
};
// args: ["select * from ucentermain.common_user_bd where id=875596"]
rpc.call('index', args, {"url": rpc_server_url, "callback": callback });
}
server.expose('index', index);
server.expose('hello', hello);
server.expose('query', query);
server.listen(8000, 'localhost');
// Test
/*
Run server:
$ npm install jsonrpc2
$ npm install request
$ nodejs rpc_in_nodejs.js
Curl RPC Request:
curl -X POST -H "Content-Type: application/json" \
-d '{"jsonrpc": "2.0", "method": "query", "params": ["select * from ucentermain.common_user_bd where id=875596"], "id": 12222}' \
'http://127.0.0.1:8000' -i
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment