Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add "dictionary" query method #5

Open
gajus opened this issue Aug 9, 2019 · 3 comments
Open

Add "dictionary" query method #5

gajus opened this issue Aug 9, 2019 · 3 comments

Comments

@gajus
Copy link
Owner

gajus commented Aug 9, 2019

I find myself often repeating this pattern:

const dictionary = {};

const cinemaForeignSeatTypes = await connection.any(sql`
  SELECT fuid, id
  FROM cinema_foreign_seat_type
  WHERE cinema_id = ${cinemaId}
`);

for (const cinemaForeignSeatType of cinemaForeignSeatTypes) {
  dictionary[cinemaForeignSeatType.fuid] = cinemaForeignSeatType.id;
}

I think this pattern appears often enough to mandate for a convenience method dictionary, i.e.

const cinemaForeignSeatTypeDictionary = await connection.dictionary(sql`
  SELECT fuid, id
  FROM cinema_foreign_seat_type
  WHERE cinema_id = ${cinemaId}
`);

Object.keys(cinemaForeignSeatTypeDictionary); // `fuid` values
Object.values(cinemaForeignSeatTypeDictionary); // `id` values
@gajus
Copy link
Owner Author

gajus commented Oct 22, 2019

This should also throw an error if keys are duplicate.

@Sharaal
Copy link

Sharaal commented Oct 23, 2019

Maybe it's worth to make it more flexible by adding a formatter which formats the rows before returning them?

e.g.:

const formatter = rows => 
  rows.reduce(
    (obj, value) => {
      obj[value.id] = value
      return obj
    },
    {}
  )

const dictionary = await connection.any(
  sql`
    SELECT fuid, id
    FROM cinema_foreign_seat_type
    WHERE cinema_id = ${cinemaId}
  `,
  formatter
);

And giving a few formatter for few standard use cases like these { id: row } transformation or the more specialised use case if { firstColumn: secondColumn } transformation.

@gajus
Copy link
Owner Author

gajus commented Oct 23, 2019

The reason this has remained an open issue is because it feels like an overly specialised feature, that likely better belongs in an abstraction such as https://github.com/gajus/slonik-utilities

@gajus gajus transferred this issue from gajus/slonik Nov 4, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants