0

I'm trying to find an elegant way to add a parameter on every fetch done by my app.

Is there any configuration that allows me to modify the body appending a new property? I looked at the documentation and aurelia-fetch-client implementation on github but I couldn't find anything about this.

Smaniotto
  • 404
  • 4
  • 16

2 Answers2

1

You're looking for the interceptor. Here are a couple of links to read up on:

http://aurelia.io/hub.html#/doc/api/aurelia/fetch-client/latest/interface/Interceptor

https://gist.github.com/bryanrsmith/14caed2015b9c54e70c3

Basically, you're going to want to modify the request body and you should be able to do that by doing something like this:

httpClient.configure(config => {
    config
        .withBaseUrl('api/')
        .withDefaults({
            credentials: 'same-origin',
            headers: {
                'Accept': 'application/json',
                'X-Requested-With': 'Fetch'
            }
        })
        .withInterceptor({
            request(request) {
                // you're going to want to modify the request body and add the appropriate property. Should be able to do it from here
                return request;
            }
        });
});
Brandon
  • 3,074
  • 3
  • 27
  • 44
  • I tried this approach, but I couldn't find any way to modify the request body. – Smaniotto Oct 08 '16 at 00:19
  • @EduwHS Just tried it myself. I thought you'd be able to. You might have to add it manually for each request depending on what request type your doing. If you're doing GET requests. I think you should be able to just append the key to the end of the url since you can access that property of the request. – Brandon Oct 08 '16 at 00:45
  • Could you share the snippet? When I tried appending a parameter to the URL, the request got canceled (not even fired the request on the network tab in chrome.) – Smaniotto Oct 08 '16 at 18:21
0

For this problem I found another approach.

I created a custom class, on the constructor I add the parameters to send it in the fetch body.

import { transient } from 'aurelia-framework';

@transient()
export class MyCustomBodyRequest {
    private _body?: any = {};

    constructor() {
        this._body.myCustomParameterOnEveryReq = getIt();
    }

    public get body() {
        return this._body;
    }

    public set body(body: any) {
        Object.assign(this._body, body);
    }

}​
Smaniotto
  • 404
  • 4
  • 16