ava / use-http

🐶 React hook for making isomorphic http requests
https://use-http.com
MIT License
2.32k stars 114 forks source link

Suggestion: Custom json transformation for automatic conversion #315

Open SrMouraSilva opened 3 years ago

SrMouraSilva commented 3 years ago

Hello, I can't found any way to convert automatically some data types when I access the json respose. I would an automatic conversion from string dates to Dates object.

As instance, Axios has the transformResponse configuration to automatic conversion:

  // `transformResponse` allows changes to the response data to be made before
  // it is passed to then/catch
  transformResponse: [function (data) {
    // Do whatever you want to transform the data

    return data;
  }],

Then, I can use it like this:

transformResponse: [(data) => JSON.parse(data, dateParser)]
...
function dateParser(key: any, value: any) {
    const dataSimples = /^(\d{4})-(\d{2})-(\d{2})$/;
    const reISO = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}(?:\.\d*)?)(?:Z|(\+|-)([\d|:]*))?$/;

    if (typeof value === 'string') {
        if (reISO.exec(value)) {
            return new Date(value);
        }
        if (dataSimples.exec(value)) {
            return new Date(value);
        }
    }

    return value;
}

It's possible to add in your awesome project a custom configuration like this?

alex-cory commented 3 years ago

Submit a PR