Skip to content

Commit

Permalink
refactor: enrich types from server config api (#200)
Browse files Browse the repository at this point in the history
  • Loading branch information
dhhyi committed May 18, 2020
1 parent 41df972 commit e3ffc18
Show file tree
Hide file tree
Showing 3 changed files with 28 additions and 5 deletions.
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
export interface ServerConfigDataEntry {
id: string;
elements?: ServerConfigDataEntry[];
[key: string]: string | boolean | string[] | ServerConfigDataEntry[];
[key: string]: string | boolean | number | string[] | ServerConfigDataEntry[];
}

export interface ServerConfigData {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,8 @@ describe('Server Config Mapper', () => {
id: 'services',
elements: [
{ id: 'captcha', siteKey: 'ASDF' },
{ id: 'gtm', token: 'QWERTY', monitor: true },
{ id: 'deeper', elements: [{ id: 'hidden', foo: 'bar' }] },
{ id: 'gtm', token: 'QWERTY', monitor: 'true' },
{ id: 'deeper', elements: [{ id: 'hidden', foo: 'bar', num: 123, alt: '123' }] },
],
},
],
Expand All @@ -41,7 +41,9 @@ describe('Server Config Mapper', () => {
},
"deeper": Object {
"hidden": Object {
"alt": 123,
"foo": "bar",
"num": 123,
},
},
"gtm": Object {
Expand Down
25 changes: 23 additions & 2 deletions src/app/core/models/server-config/server-config.mapper.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,15 +4,36 @@ import { ServerConfigData, ServerConfigDataEntry } from './server-config.interfa
import { ServerConfig } from './server-config.model';

export class ServerConfigMapper {
private static transformType(val) {
if (typeof val === 'string') {
if (!isNaN(+val)) {
return +val;
} else if (val === 'true') {
return true;
} else if (val === 'false') {
return false;
}
}
return val;
}
private static transformTypes(obj) {
return Object.entries(obj)
.map(v => v)
.reduce((acc, val) => ({ ...acc, [val[0]]: ServerConfigMapper.transformType(val[1]) }), {});
}

private static mapEntries(entries: ServerConfigDataEntry[]) {
return entries.reduce(
(acc, entry) => ({
...acc,
[entry.id]: Array.isArray(entry.elements)
? // do recursion if elements array is set
ServerConfigMapper.mapEntries(entry.elements)
: // filter out unnecessary 'id' attribute
omit(entry, 'id'),
: // transform string types to better values
ServerConfigMapper.transformTypes(
// filter out unnecessary 'id' attribute
omit(entry, 'id')
),
}),
{}
);
Expand Down

0 comments on commit e3ffc18

Please sign in to comment.