-
Notifications
You must be signed in to change notification settings - Fork 1
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
chapter 02: refactoring genericEncoder to use the encoder factory
- Loading branch information
Showing
1 changed file
with
33 additions
and
0 deletions.
There are no files selected for viewing
33 changes: 33 additions & 0 deletions
33
chapter-02-the-open-closed-principle/refactor/genericEncoder.js
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,33 @@ | ||
function genericEncoder(encoderFactory) { | ||
function encodeToFormat(data, format) { | ||
const encoder = encoderFactory.createForFormat(format); | ||
|
||
data = prepareData(data, format); | ||
|
||
return encoder.encode(data); | ||
} | ||
|
||
function prepareData(data, format) { | ||
switch (format) { | ||
case 'json': { | ||
data = this.forceArray(data); | ||
data = this.fixKeys(data); | ||
} | ||
case 'xml': { | ||
data = this.fixAttributes(data); | ||
break; | ||
} | ||
default: { | ||
throw new Error('Format not supported'); | ||
} | ||
} | ||
|
||
return data; | ||
} | ||
|
||
return { | ||
encodeToFormat, | ||
}; | ||
} | ||
|
||
module.exports = genericEncoder; |