Last active
March 17, 2017 09:30
-
-
Save yellowred/9dc4299b50f2707770495e981fbb66ec to your computer and use it in GitHub Desktop.
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
/** | |
* @author Oleg Kubrakov yellowred.github.com | |
* @since 2017 | |
**/ | |
const Promise = require('Bluebird') | |
const jwt = require('jsonwebtoken'); | |
let generateOneTimeToken = (value) => { | |
// we use promise to stub a request to MongoDB | |
let token = jwt.sign({ value }, 'privkey'); | |
return Promise.resolve({value, token}); | |
} | |
let data = [ | |
{ | |
name: "Michelle Rung", | |
contacts: [ | |
{ phone: "7281681726" }, | |
{ emailAddress: "michelle@gmail.com" }, | |
{ emailAddress: "michelle@gmail.com" }, | |
{ emailAddress: "" } | |
] | |
}, | |
{ | |
name: "Johann Sigh", | |
contacts: [ | |
{ phone: "7812787-2667" }, | |
{ emailAddress: "johann@gmail.com" }, | |
{ emailAddress: "johann-md@gmail.com" } | |
] | |
} | |
] | |
let generateResponse = (data) => { | |
return Promise.coroutine(function* () { | |
let emails = data | |
.map(getEmailsFromIndividual) | |
.reduce(flatten) | |
.filter(value => value != undefined && value != "") | |
.filter(distinct) | |
return yield Promise.map( | |
emails, | |
emailAddress => valueAndToken(emailAddress) | |
) | |
})() | |
} | |
let getEmailsFromIndividual = (individual) => { | |
if (!Array.isArray(individual.contacts)) return [] | |
return individual | |
.contacts | |
.map(value => value['emailAddress']) | |
} | |
let flatten = (flatArray, arrayElement) => { | |
return flatArray.concat(arrayElement) | |
} | |
let distinct = (val, index, contacts) => { | |
return contacts.indexOf(val) === index | |
} | |
let valueAndToken = (emailAddress) => { | |
return generateOneTimeToken(emailAddress) | |
.then(tokenObject => { | |
return { | |
electronicAddress: emailAddress, | |
token: tokenObject.token | |
} | |
}) | |
} | |
generateResponse(data).then(console.log) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment