janhommes / o.js

o.js - client side oData lib.
https://janhommes.github.io/o.js/example/
MIT License
241 stars 58 forks source link

cant find correct way to query single object #101

Closed Abenezer closed 4 years ago

Abenezer commented 4 years ago

the old versions have find(1) methods. but on new version even get(resource(x)) will sometimes (i think it caches the prev requests) append $count param which results error

janhommes commented 4 years ago

Can you share the full code as an example? Your way of querying it is correct, the find method was removed in 1.x as it is easy to now use string literals for that:

const id = 1;
await o('http://some.url').get(`user(${id})`).query()

But why the $count is attached I don't know exactly. Maybe there is an issue with your query or maybe with o.js. I could try it if you give me some more code.

Abenezer commented 4 years ago

wow, did not expect that fast response. thanks i may have found the problem, i was using it like this
const oHandler = o('https://localhost:44385/odata/'); console.log('gettingOne',resource) const query = {} const {expand,id} = params if(expand) { query.$expand = expand }

    ` return oHandler
         .get(`${resource}(${id})`)
         .query(query).then(data =>
             {
              //   console.log(data)

                 return {data}

             }
         )`

does using it as handler caches previous query. because it happens when i run another query with $count=true using the same oHandler right before i run the above. if i just use return o('https://localhost:44385/odata/').get(${resource}(${id})) every thing is working as expected. .

janhommes commented 4 years ago

yep, that is correct... the handler chains multiple requests and only cleans them when they are done (see: https://github.com/janhommes/o.js/blob/cba5d7d771383768ca303634ab1aa1b5f866e424/src/OHandler.ts#L76). So if you want to use the handler, you must either await the first request or chain your request:

oHandler.get('$count').get(`${resource}(${id}).query()

but this doesn't work for you, as it will attach the query parameters to both requests. Maybe it is better to initialize the handler with some kind of function.

getHandler() {
  return o('http://yourUrl');
}

and then call getHandler().get(...).

Abenezer commented 4 years ago

perfect, thanks ... don't you think it should be in the docs