FRiCKLE / ngx_postgres

upstream module that allows nginx to communicate directly with PostgreSQL database.
http://labs.frickle.com/nginx_ngx_postgres/
BSD 2-Clause "Simplified" License
545 stars 122 forks source link

JSON-RPC support #59

Open ppKrauss opened 6 years ago

ppKrauss commented 6 years ago

There are some JSON-RPC support or a simple way to configure it? If not, it is a suggestion.


Example: supposing rds_json_format=normal and rds_json_root=result, it is near to a JSON-RPC response,

 {"result":[{"id":2,"name":null},{"id":3,"name":"bob"}]}

need only to add jsonrpc and id attributes,

 { "jsonrpc":2.0, "id":123, "result":[{"id":2,"name":null},{"id":3,"name":"bob"}]}

where id is the ID for control the AJAX promises or any other kind of request-ID, and jsonrpc only a standard way to say that the client-server dialog is a JSON-RPC 2.0 (REST-adapted) dialect.

Error response also need some minimal adaptations, and use as primary-error-code the HTTP status codes... It is a convention over configuration proposal.


PS: no "protocol conflict" here, JSON-RPC can be used in a context of REST standards. It is only a standarized way to encapsulate JSON, and can be used also internally as generic SQL command tool.

Exemple of snippet code for internal error handling

/**
 * Add attributes "code" and "message" in a JSONb object, or create a new one.
 */
CREATE or replace FUNCTION lib.resp_error_add(
  p_code float, -- the error code in the form general_httpStatus.detail_internalCode
  p_msg text DEFAULT NULL,  -- the error message
  p_data JSONb DEFAULT NULL   -- optional data for warnings like 200.X
) RETURNS JSONb AS $f$
  SELECT CASE
      WHEN p_data IS NULL OR jsonb_typeof(p_data)='null' THEN x
      ELSE jsonb_build_object('result',p_data) || x
    END
  FROM (SELECT jsonb_build_object('code',p_code, 'message',p_msg)) t(x)
$f$ language SQL IMMUTABLE;

CREATE or replace FUNCTION lib.resp_error_add(
  int, text, JSONb DEFAULT NULL
) RETURNS JSONb AS $wrap$
  SELECT lib.resp_error_add((200.0+$1/1000.0)::float, $2, $3);
$wrap$ language SQL IMMUTABLE;

So, another interesting (optional) adaptation is to get the integer part of a float error code, or check that it is to by-pass as status 200.