Created
September 3, 2017 22:59
-
-
Save 0xpatrickdev/3c4742e9f8adaf151c6354adeeb7d8d6 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
import fetch from 'isomorphic-fetch'; | |
import stripeInit from 'stripe'; | |
import {stripeKey, graphCoolEndpoint} from './constants'; | |
const stripe = stripeInit(stripeKey); | |
const updateGraphCoolCustomer = async (id, stripeId) => { | |
const updateCustomer = JSON.stringify({ | |
query: ` | |
mutation { | |
updateUser( | |
id: "${id}", | |
stripeId: "${stripeId}", | |
) { | |
id | |
stripeId | |
} | |
} | |
` | |
}); | |
try { | |
const response = await fetch(graphCoolEndpoint, { | |
headers: {'content-type': 'application/json'}, | |
method: 'POST', | |
body: updateCustomer, | |
}); | |
return await response.json(); | |
} | |
catch (err) { | |
console.log(`Error updating GraphCool customer: ${JSON.stringify(err)}`); | |
throw err; | |
} | |
}; | |
const createStripeCustomer = async (email, source) => { | |
console.log(`Creating stripe customer for ${email}`); | |
let stripeCustomer; | |
try { | |
stripeCustomer = await stripe.customers.create({email: email, source: source}); | |
console.log(`Successfully created Stripe customer: ${stripeCustomer.id}`); | |
return stripeCustomer; | |
} | |
catch (err) { | |
console.log(`Error creating Stripe customer: ${JSON.stringify(err)}`); | |
throw err; | |
} | |
}; | |
const main = event => { | |
const {cardToken, user} = event.data.CardDetails.node; | |
const { id, email, stripeId } = user; | |
return new Promise(async (resolve, reject) => { | |
try { | |
stripeId && resolve(event) | |
const stripeCustomer = await createStripeCustomer(email, cardToken); | |
const graphCoolCustomer = await updateGraphCoolCustomer(id, stripeCustomer.id); | |
console.log(`Successfully updated GraphCool customer: ${JSON.stringify(graphCoolCustomer)}`); | |
resolve(event); | |
} | |
catch (err) { | |
console.log(err); | |
reject(err); | |
} | |
}); | |
}; | |
module.exports = main; | |
// export these local methods so we can unit test them | |
module.exports.updateGraphCoolCustomer = updateGraphCoolCustomer; | |
module.exports.createStripeCustomer = createStripeCustomer; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment