Skip to content

Instantly share code, notes, and snippets.

@oukayuka
Last active April 9, 2019 09:17
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save oukayuka/8d2d3b2093822ff3503a068fe6987bca to your computer and use it in GitHub Desktop.
Save oukayuka/8d2d3b2093822ff3503a068fe6987bca to your computer and use it in GitHub Desktop.
axios のレスポンスからスネークケースのキーをキャメルケースに変換して、日付をDateTimeオブジェクトにする
import { AxiosResponse } from 'axios';
import { camel } from 'change-case';
import { isArray, isObject, isString } from 'lodash';
import { DateTime } from 'luxon';
export const reform = (
obj: object,
keyConverter: (k: string) => string,
): any => {
if (isArray(obj)) {
return obj.map(o => reform(o, keyConverter));
}
const newObj = {};
Object.keys(obj).map(key => {
const value = obj[key];
const newKey = keyConverter(key);
if (isObject(value)) {
newObj[newKey] = reform(value, keyConverter);
} else if (key.match(/_at$/) && isString(value)) {
newObj[newKey] = DateTime.fromISO(value);
} else {
newObj[newKey] = value;
}
});
return newObj;
};
export const reformResponse = (response: AxiosResponse): AxiosResponse => {
const data = reform(response.data, camel);
return { ...response, data };
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment