postgraphile - function to add structured data as field on mutation

424 Views Asked by At

I'd like to do the simplest possible thing to add structured data to a postgraphile mutation.

I have a simple example table:

> \d test1.my_table                                                                                                                                                                      
+----------+--------+
| Column   | Type   |
|----------+--------+
| id       | uuid   |
| the_box  | box    |
+----------+--------+

The box column creates a type of {kind: "SCALAR", name: "String", ofType: null} through postgraphile, which leaves me to parse the result of a query, and marshal the data into a string for a mutation.

query MyQuery {
  myTables {
    nodes { id theBox }
  }
}

yields

{
  "data": {
    "myTables": {
      "nodes": [
        {
          "id": "c79ee287-88ca-4950-a44b-e4ef07d3c3dc",
          "theBox": "(3,4),(1,2)"
        }
      ]
    }
  }
}

A similar thing happens for polygon or bytea types.

In my ideal world, I write a computed column function for the query which returns the box (or polygon, or bytea) as some custom postgres type.

CREATE TYPE box_arg AS (x point, y point);

CREATE OR REPLACE FUNCTION test1.my_table_box_for_query(the_row test1.my_table)  
RETURNS box_arg AS $$  
BEGIN 
   SELECT '(the_row.the_box[0][0], the_row.the_box[1][0])'::point,
          '(the_row.the_box[0][1], the_row.the_box[1][1])'::point;
END; 
$$ LANGUAGE 'plpgsql' STABLE;

(Leaving aside whether i'm picking the right x/y in that query...)

However, I can't seem to figure out the other direction. How do I write a function that is exposed on the mutation created by postgraphile for my_table that will accept structured data (the box_arg type from above, for example), and have the function update the record during the mutation with the values from the function argument? I'd like to have the box_arg type as an input on the mutation. Indeed, you can see here that the box is only available on the input as a string.

Example of theBox parameter as a string

Is this possible with a postgres function? Or is this only possible via a postgraphile plugin?

Thank you so much for any advice/examples!

0

There are 0 best solutions below