|
1 | | -import { isJSONObject } from '../helpers/json' |
| 1 | +import { camelizeKeys, isJSONObject } from '../helpers/json' |
2 | 2 | import { unmarshalArrayOfObject, unmarshalDate } from '../helpers/marshalling' |
3 | 3 | import { fromByteArray } from '../vendor/base64' |
4 | 4 | import type { |
@@ -207,3 +207,61 @@ export const marshalTimeSeries = ( |
207 | 207 | export const marshalDecimal = (obj: Decimal): { value: string } => ({ |
208 | 208 | value: obj.toString(), |
209 | 209 | }) |
| 210 | + |
| 211 | +/** |
| 212 | + * Unmarshals record to convert iso dates from string to Dates. |
| 213 | + * |
| 214 | + * @param obj - The input |
| 215 | + * @param keys - The keys requiring a conversion |
| 216 | + * @returns The updated input |
| 217 | + * |
| 218 | + * @internal |
| 219 | + */ |
| 220 | +export const unmarshalDates = <T>(obj: unknown, keys: string[]): T => { |
| 221 | + if (Array.isArray(obj)) { |
| 222 | + return obj.map(v => unmarshalDates(v, keys)) as unknown as T |
| 223 | + } |
| 224 | + |
| 225 | + if (obj && typeof obj === 'object') { |
| 226 | + return Object.entries(obj).reduce( |
| 227 | + (acc, [key, value]) => ({ |
| 228 | + ...acc, |
| 229 | + [key]: |
| 230 | + typeof value === 'string' && keys.includes(key) |
| 231 | + ? new Date(value) |
| 232 | + : unmarshalDates(value, keys), |
| 233 | + }), |
| 234 | + {}, |
| 235 | + ) as T |
| 236 | + } |
| 237 | + |
| 238 | + return obj as T |
| 239 | +} |
| 240 | + |
| 241 | +/** |
| 242 | + * Unmarshals input to a record with camilized keys and instanciated Date. |
| 243 | + * |
| 244 | + * @param obj - The input |
| 245 | + * @param ignoreKeys - The keys which should be not be transformed |
| 246 | + * @param dateKeys - The keys which should be transformed to Date |
| 247 | + * @returns The record |
| 248 | + * |
| 249 | + * @throws TypeError |
| 250 | + * Thrown if the input isn't {@link JSONObject}. |
| 251 | + * |
| 252 | + * @internal |
| 253 | + */ |
| 254 | +export const unmarshalAnyRes = <T>( |
| 255 | + obj: unknown, |
| 256 | + ignoreKeys: string[] = [], |
| 257 | + dateKeys?: string[], |
| 258 | +): T => { |
| 259 | + if (!isJSONObject(obj)) { |
| 260 | + throw new TypeError(`Data isn't a dictionary.`) |
| 261 | + } |
| 262 | + |
| 263 | + return camelizeKeys( |
| 264 | + dateKeys && dateKeys.length > 0 ? unmarshalDates(obj, dateKeys) : obj, |
| 265 | + ignoreKeys, |
| 266 | + ) |
| 267 | +} |
0 commit comments