Skip to content

Parsing arrays of custom types #94

@L-Leite

Description

@L-Leite

Hello, thank you for your work developing this library.

I have a project where I fetch a column that stores an array of custom types.
The table structure looks like this:

CREATE TYPE inventoryItem AS
(
  item_id integer,
  ammount integer
);

CREATE TABLE public.inventories
(
  owner_id integer PRIMARY KEY,
  items inventoryItem[] DEFAULT
  ARRAY[
    /* characters */
    (1005, 1), (1006, 1), (1007, 1) /* etc...*/
   ]::inventoryitem[]
);

And I pass these options to postgres:

import postgres from 'postgres'

export class InventoryItem {
    public item_id: number
    public ammount: number
}

const INVENTORY_ITEM_OID = 12345 /* this is generated by a script */

export type DB_POSTGRES_CUSTOM_TYPES = {
    inventoryItem: InventoryItem
}
export const DB_POSTGRES_CONFIG: postgres.Options<DB_POSTGRES_CUSTOM_TYPES> = {
   /* other options... */
    types: {
        inventoryItem: {
            to: INVENTORY_ITEM_OID,
            from: [INVENTORY_ITEM_OID],
            parse: (str: string): InventoryItem => {
                str = str.substr(1, str.length - 2)
                const parts = str.split(',')

                const id = Number(parts[0])
                const ammount = Number(parts[1])

                return new InventoryItem(id, ammount)
            },
            serialize: (item: InventoryItem): number[] => {
                return [item.item_id, item.ammount]
            }
        }
    }
}

export const sql = postgres(DB_POSTGRES_CONFIG)

And I query the data like this:

export class Inventory {
    public static async getById(userId: number): Promise<Inventory> {
        const resRows = await sql<
            Inventory
        >`SELECT * FROM inventories WHERE owner_id = ${userId};`

        if (resRows.count === 0) {
            return null
        } else if (resRows.count === 1) {
            return resRows[0]
        } else {
            throw new Error('getById: got more than one row for an inventory')
        }
    }
}

The issue is that the parse function is never called. I looked into the library's code and I found if I changed line 245 of index.js from where a.typcategory = 'A' and b.typcategory != 'C' to where a.typcategory = 'A' that the parse function gets called.

Is there a way of parsing the custom type array without modifying the library?
I am using version 2.0.0-beta.0 of postgres

Thank you for your time

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementNew feature or request

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions