Custom SQL function (json_agg & json_build_object)

Hello there.

I'm new to Drizzle and I love it 😍.

I have successfully made a jsonAgg helper.

function jsonAgg<T extends PgTable<TableConfig>>(table: T) {
  return sql<InferModel<T>[]>`json_agg(${table})`;
}


Now I have trouble to make a jsonAggBuildObject 😅 that should produce something like this:

sql`json_agg(json_build_object('key1', ${table.col1}, 'key2', ${table.col2}, ...))`


I try something but it end with an error error: could not determine data type of parameter $1

function jsonAggBuildObject<T extends Record<string, AnyColumn>>(shape: T) {
  const shapeString = Object.entries(shape)
    .map(([key, value]) => {
      return `'${key}', ${value}`;
    })
    .join(",");

  return sql<
    InferColumnsDataTypes<T>[]
  >`json_agg(json_build_object(${shapeString}))`;
}


Any idea ?
Was this page helpful?