Last active
April 9, 2019 09:17
-
-
Save oukayuka/8d2d3b2093822ff3503a068fe6987bca to your computer and use it in GitHub Desktop.
axios のレスポンスからスネークケースのキーをキャメルケースに変換して、日付をDateTimeオブジェクトにする
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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