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

A better way to handle .first() #3

Closed
icopp opened this issue Jul 21, 2021 · 4 comments · Fixed by #4
Closed

A better way to handle .first() #3

icopp opened this issue Jul 21, 2021 · 4 comments · Fixed by #4

Comments

@icopp
Copy link

icopp commented Jul 21, 2021

Currently it looks like when .first() is used on a Knex query, the full array response is still returned to it, so you have to change your response based on whether you know .first() is being used or not.

The simplest fix for the end user here would probably be to use the first item of the passed in array for .first() (or undefined if there is none).

@felixmosh
Copy link
Owner

felixmosh commented Jul 22, 2021

Can you elaborate it? Example will help 🙏🏼

You can register an handler for the specific query which .first constructs (it adds limit 1 at the end) and return the object you want to get.

tracker.on.select('select * from users where `id`=? limit 1').response({ name: 'foo' });
// ---------------------------------------------------^

@max-mathieu
Copy link

Well first, thanks for this lib @felixmosh !

Having faced the same case as @icopp , I think the issue here is that knex returns a different kind of response.

Indeed knex('users').where({id : 1}).limit(1) returns an array of length = 1, whereas knex('users').where({id : 1}).first() directly returns the first row (essentially, you have to write const [ user ] = knex('users').where({id : 1}).limit(1) but can write const user = knex('users').where({id : 1}).first();`)

With the example above, I believe select * from users where ... limit 1 would match both, but break for 50% of them (breaks the first() one if your response is an array, breaks the limit(1) if the response is an object, so I'd agree it'd be great for this lib to understand that first is special. Maybe .response should always take an array?

@felixmosh
Copy link
Owner

felixmosh commented Aug 16, 2021

Thank you for the feedback

I don't think that this lib should make manipulations on user given data, but if 2 people are requesting such a feature I'll consider it ;)

@felixmosh
Copy link
Owner

Added in v1.5.0.

Thank you for the feedback 🙏🏼

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

Successfully merging a pull request may close this issue.

3 participants