var httpfunc = require('topsin.httpfunc');
var REQ = httpfunc.argv().request;
var RES = httpfunc.argv().response;
var SinEror = require('topsin.error');
var result = new (require('topsin.responsedata'))();
var DB = require('topsin.database');
var DBNAME = REQ.pathCapture('DBNAME');
var Crypto = require('topsin.crypto');
var _ = require('lodash');

try {
  if (REQ.method() != "POST") throw "only support POST method!";

  var body = JSON.parse(REQ.body());
  var func = _.get(body, 'func');
  var paras = _.get(body, 'paras');

  if (!_.isString(func)) throw "func must be a string!";
  if (!_.isArray(paras)) throw "paras must be an array!";

  var r = DB.query(DBNAME, function (q) {
    var r = q[func].apply(q, paras);
    if (q.lastError().isValid()) throw q.lastError().text();
    return r;
  });
  result.setData(r);
  RES.body(result.toJson());
} catch (err) {
  result.setErrText(CONFIG.tr(_.toString(err)));
  RES.body(result.toJson());
}
