Search code examples
reactjstypescriptdatastoreaws-amplify

How can I create a dynamic query in Amplify Datastore


How do i create a dynamic query in amplify react application

Expected Query:

const posts = await DataStore.query(Post, c => c.or(
  c => c.rating("gt", 4).status("eq", PostStatus.PUBLISHED)
));

'rating' and 'status' may change depends on user. Please help me to create a dynamic datastore query.


Solution

  • let just say you have an object which defines what user can use what filter queries. Here I assumed user can be of two types typeA and typeB.

    const queryTable = {
        typeA: ['status', 'rating'],
        typeB: ['active', 'status']
    }
    
    const posts = await DataStore.query(Post, c => c.or(
        c => {
            const operator = "eq" || "gt";
            const value = 4 || "published";
            queryTable[user.type].forEach(func, => {
                c.[func](operator, value)
            })
            return c
        }
    ));
    

    You have to figure out a way how you can pass operator and value.