/
processHeaderFormatters.ts
38 lines (31 loc) · 1.35 KB
/
processHeaderFormatters.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
import type { IFormatter } from '@interfaces/IFormatter';
import type { IHeaderField } from '@interfaces/IHeaderField';
import { applyFormatters } from '@tools/applyFormatters';
import { encodes } from '@tools/encode';
import fastSafeStringify from 'fast-safe-stringify';
export function processHeaderFormatters<T extends Record<string, any>>(
thisFrame: T,
field: IHeaderField,
formatters: IFormatter[],
) {
const { key: thisFrameAccessKey, option } = field;
const value: any = thisFrame[thisFrameAccessKey];
const processed = formatters
.map<Record<string, any>>((formatter) => {
const resultAccessKey = option.replaceAt ?? thisFrameAccessKey;
// stage 01. apply formatter
const formatted: string | string[] = applyFormatters(value, formatter);
// stage 02. array processing
if (Array.isArray(formatted)) {
// comma seperated string or json serialization
const commaApplied = (option.comma ?? false) === true ? formatted.join(',') : fastSafeStringify(formatted);
const encoded = encodes(option.encode, commaApplied);
return { [resultAccessKey]: encoded };
}
// stage 03. general action
const encoded = encodes(option.encode, formatted);
return { [resultAccessKey]: encoded };
})
.reduce((merged, formatted) => ({ ...merged, ...formatted }), {});
return processed;
}