Search code examples
pg-promise

pg-promise ColumnSet with nested object prop?


What is the proper syntax for a object child as a column prop?

const cs = new pgp.helpers.ColumnSet([
  {
    name: 'uid',
    prop: 'id'
  }, {
    name: 'created_at'
    prop: 'member.created_at // <-- error
  }
])

Cant seem to get this to work.


Solution

  • While the regular pg-promise query formatting (using Named Parameters) supports nested properties, specifically helpers do not, due to certain templates-related complexity.

    However, it is not necessary, because ColumnSet syntax for columns is very flexible (see type Column), and supports dynamic property resolution.

    Simply update the column to use init, to get the value dynamically:

    {
        name: 'created_at',
        init: c => c.source.member.created_at
    }
    

    For the field, we go to the source object, as per documentation, and take what we need.

    Alternative syntax:

    {
        name: 'created_at',
        init(c) {
            // with this syntax, this = c.source
    
            return this.member.created_at;
        }
    }