Last active
March 21, 2019 17:18
-
-
Save abnersajr/4ece0650b3b91ff5226fcaf2ab4542f3 to your computer and use it in GitHub Desktop.
Mapper the good way
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
// Your API Response or another data source | |
const API_RESPONSE = { | |
userName: "Talysson", | |
userLastName: "Cassiano", | |
birth: "01/04/1992", | |
evaluation: { | |
average: 4.5, | |
total: 20, | |
} | |
} | |
const apiResponseMapper => data => { | |
const { | |
userName, | |
userLastName | |
birth, | |
evaluation | |
} = data | |
return { | |
name: userName, | |
lastName: userLastName, | |
fullName: `${userName} ${userLastName}`, | |
birthDate: new Date(birth), | |
userRating: evaluation.average, | |
ratingsTotal: evaluation.total | |
} | |
} | |
const userDataMapper = ({ data, origin }) => { | |
const mappers = { | |
API: apiResponseMapper | |
} | |
return mappers[origin] ? mappers[origin](data) : data | |
} | |
// Good way to write components and tests, having same names in both components for the same data | |
const UserProfile = ({ fullName, birthDate, userRating }) => {...} | |
describe('UserProfile', () => { | |
it('renders with correct props', () => { | |
const MOCK_USER = userDataMapper({ data: API_RESPONSE, origin: 'API' }) | |
... | |
}) | |
}) | |
const UserRating = ({ fullName, userRating, ratingsTotal }) => {... } | |
describe('UserRating', () => { | |
it('renders with correct props', () => { | |
const MOCK_USER = userDataMapper({ data: API_RESPONSE, origin: 'API' }) | |
... | |
}) | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment