Skip to content

Instantly share code, notes, and snippets.

@wordyallen
Last active February 28, 2017 13:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wordyallen/5182d1b92f422c2c66c1d9b5805fdf0a to your computer and use it in GitHub Desktop.
Save wordyallen/5182d1b92f422c2c66c1d9b5805fdf0a to your computer and use it in GitHub Desktop.
const saveCard = ( {body:{source, amount}, user:{email, _id}}, res ) =>
getBundle(amount) ?
customers.create({email, source, metadata: {_id:_id.toString()}})
.then(writeCustomerId )
.then(createCharge(amount,_id))
.then(grantCredits)
.then(payload=>res.json(payload) )
.catch(e=> res.status(400).send(e))
: res.status(400).send('Product not found')
const bundles = [
{category: 'Beginner', price: 1000, credits:10},
{category: 'Reasonable', price: 2000, credits:20},
{category: 'Beginner', price: 4000, credits:100},
]
const getBundle = amt => bundles.find( ({price}) => price === +amt )
const writeCustomerId = ({id, metadata:{_id}}) =>
User.findOneAndUpdate({_id}, {customer:id}, {upsert:1, safe: 1, new: 1})
const createCharge = (amount,_id) => ({customer}) =>
charges.create({amount, customer, currency:'usd', metadata:{_id:_id.toString()}})
const grantCredits = charge => User.findOneAndUpdate(
{_id: charge.metadata._id},
{credits: getBundle(charge.amount).credits},
{upsert:1, safe: 1,new:1})
.then(mergePayloads(charge))
const mergePayloads = charge => model => Object.assign( charge, model.toObject())
@wordyallen
Copy link
Author

wordyallen commented Feb 28, 2017

  1. check product
  2. create customer
  3. write customer id in the local db
  4. create charge
  5. grant credits to user
  6. merge stripe and db payload

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment