aurelia / http-client

A simple, restful, message-based wrapper around XMLHttpRequest.
MIT License
62 stars 59 forks source link

JSON.stringify replacer #105

Closed tareqimbasher closed 9 years ago

tareqimbasher commented 9 years ago

Hello everyone, I am configuring the HttpClient with a replacer to JSON.stringify like this:

let replacer = new JsonStringifyReplacer();   // this is my replace i have built
this.http = this.http.configure(x => {
      x.withBaseUrl(CONSTS.ApiUrlBase);
      x.withHeader('Accept', 'application/json;charset=UTF-8');
      x.withReplacer((key, value) => replacer.stringify(key, value));   // here i am using my replacer
});

JsonStringifyReplacer :

export class JsonStringifyReplacer {
    private cache = [];

    stringify(key, value) {
        if (typeof value === 'object' && value !== null) {
            if (this.cache.indexOf(value) !== -1) {
                // Circular reference found, discard key
                return;
            }
            // Store value in our collection
            this.cache.push(value);
        }
        return value;
    }
}

My problem: This works once, but the cache array is never emptied for the next time the replacer needs to be used.

I also cannot do this:

 x.withReplacer((key, value) => new new JsonStringifyReplacer().stringify(key, value));

because then the cache will be reinitialized for every member the JSON.stringify method is trying to stringify, which defeats the purpose, since the cache is always new. Any ideas on how to solve this?I thought up some elaborate solutions in my head, but I think I may be over complicating things.

bryanrsmith commented 9 years ago

I think right now you'd need to pass your replacer at request creation time instead of at configuration time so it's not shared by all requests. It'd probably be better if the withReplacer helper took a function that returned a replacer, so we could create a new one for each request. Care to open a PR? :-)

EisenbergEffect commented 9 years ago

Closing for now. The reviver/replacer can be passed per request instead of as part of the global config.