Some progresss

How the heck did we ever program before google?

Beats me.

I now have a servlet which will permit you to call stored procedures in a postgres database, passing in and getting back JSON. Simple? Well, yes. But the code underneath has to convert things between JSON strings, arrays, record sets and back again.

The goal is that the inner stored procedures should not have to talk JSON at all. There’s a layer to unpack and repack that does that.

For instance: a thing1 has many thing2s. I want to pass back an array of thing1s to the caller. So theres code to build a JSON object from a set of columns from thing2: row_to_json, to convert a result set into an array: array, to convert that array into a single json object: array_to_json, and finally to stuff that into a json object built from the columns of thing1: row_to_json.

Of course, this function is passed an array of thing1 ids, which are integers that come in as a json array. So:

  _result := thing1_array(
      select a.value::text::int 
      from json_array_elements(request_json) a

Ten years ago, the only way to get this done would be to take a few days to thoroughly read the docs. Now, it’s google and trial-and-error.

What else? A consistent framework for passing messages back to the caller, allowing the functions deep down in the call hierarchy to whinge to the user helpfully, and rolling back by throwing exceptions around. The return json *always* is one json object, with a key named ‘ok’ and one named ‘messages’ – other keys as needed depending on the operation.

Oh – I should be returning a meaningful http response code. 404 for “that record id is rubbish”, 409 when we can’t do an update as a result of complicated business rules.

Fun times. Yeah, I know there’s 9000 frameworks that do all this. I have expressed my opinion of frameworks before. My ‘framework’ is 148 lines that go like this:

  public class XxxJson extends HttpServlet {
    protected void service(…) {
      … stuff goes here
      PrintWriter out = new PrintWriter(response.getOutputStream());

Old-school. ‘Cause I’m old.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: