Last active
April 26, 2019 17:54
-
-
Save clnmcgrw/6303cd3541bd603eeb4aa2b803fd6b67 to your computer and use it in GitHub Desktop.
Data Migration Technique
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
// prop - destination key | |
// value - source key | |
const entityProps = { | |
name: 'title', | |
body: 'description', | |
day: 'date', | |
room: 'location', | |
}; | |
// transform a destination value | |
// use entire entity to return a transformed value | |
const entityTransforms = { | |
title: entity => entity.title.toLowerCase(), | |
room: entity => ({ name: entity.location.name }), | |
}; | |
// gets a converted entity based on an entityProps object | |
const getConvertedEntity = (sourceEntity, props, ignore = []) => { | |
Object.keys(sourceEntity).reduce((result, key) => { | |
if (sourceEntity[key] && !ignore.includes(key)) { | |
Object.assign(result, { | |
[props[key]] : entityTransforms[key] ? entityTransforms[key](sourceEntity) : sourceEntity[key] | |
}); | |
} | |
return result; | |
}, {}); | |
}; | |
// example usage | |
// pretend sourceClient & destClient are 2 different api clients | |
(async () => { | |
//list of things from an api | |
const apiResponse = await sourceClient.getThings(); | |
//convert each entity in the list | |
const convertedEntities = apiResponse.map(entity => { | |
const newEntity = getConvertedEntity(entity, entityProps); | |
return destClient.createNewThing(newEntity); | |
}); | |
//create via api | |
await Promise.all( | |
apiResponse.map(entity => { | |
const newEntity = getConvertedEntity(entity, entityProps); | |
return destClient.createNewThing(newEntity); | |
}) | |
); | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment