javascriptdojodstore

Add query parameters at dstore/Rest request


I have a dstore/Rest instance like this:

const entries = new Rest({ target: '/rest/entries' })

And I need to add a token as query parameter for every PUT/POST request, so url for my PUT/POST request should look like this:

'/rest/entries/100500?token=some_token'

Is there in dstore/Rest any convinient way to do this? Or maybe set header before each request and place token there. Anyway, my problem is to build correct request when I call

entries.add({id: 100500, value: 'someValue'})

Update:

I figured out, that Rest.add accepts two arguments - object and options and managed to add token in headers:

entries.add(entry, {
            headers: {
                Token: token
            }
        })

But I'm still curious about query parameters.


Solution

  • I've managed to find following solution for me:

    lang.extend(Rest, {
        setToken: function(token) {
            this.token = token
    
            aspect.after(this, '_getTarget', function(target) {
                if (this.token) {
                    target += '?token=' + this.token
                    this.token = undefined
                }
                return target
            })
    
    
            aspect.before(this, 'add', function() {
                if (this.token) {
                    this.target += '?token=' + this.token
                    this.token = undefined
                }
            })
    
            return this
        }
    })
    

    And I use it like this:

    entries.setToken(token).add(data)
    

    But I'm not sure that it's a good way to accomplish my task.