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

How can I query postgres jsonb column with knex adapter? #3425

Open
kvagajack opened this issue Feb 7, 2024 · 1 comment
Open

How can I query postgres jsonb column with knex adapter? #3425

kvagajack opened this issue Feb 7, 2024 · 1 comment

Comments

@kvagajack
Copy link

Steps to reproduce

I have a typebox schema like:

export const itemSchema = Type.Object({
    id: Type.Number(),
    meta_data: Type.Object({
      tie: Type.Optional(Type.String()),
      suit: Type.Optional(Type.String())
    }
})

And I want to query all items that have "meta_data.tie" as "BLUE".

With SQL I would query this like:

Select * from items where meta_data ->>'tie' = 'BLUE';

or

SELECT * FROM items WHERE meta_data @> '{"tie":"BLUE"}';

But I cannot figure out how to build a query in feathers client.
Tried the following:

feathersClient.service('items').find({
    query: {
        meta_data: { tie: "BLUE"}

        "meta_data.tie": "BLUE"
        
        "meta_data ->>'tie'": "BLUE"
    }
})
@kvagajack
Copy link
Author

kvagajack commented Feb 10, 2024

If anybody needs this, here is how you can do it:

// Hook:
export function jsonFilter(context: any) {
    // Extract your custom query parameter
    const { jsonFilter } = context.params.query;

    if (jsonFilter) {
        // QueryBuilder_PostgreSQL:
        const query = context.service.createQuery(context.params)
        jsonFilter.forEach(({column, prop, value}: any) => {
            query.andWhereJsonPath(column, `$.${prop}`, '=', value);
        });
        context.params.knex = query;
    }
}

Add the hook to your db service find method:

before: { find: [ jsonFilter ] }

In UI pass the custom query option:

const jsonFilter = [
    {column: "meta_data", prop: "tie", value: "BLACK"},
    {column: "meta_data", prop: "suit", value: "GREEN"},
];
feathersClient.service("items").find({
    query: {
      $limit: 40,
      jsonFilter
    }
});

Links:

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

1 participant