Skip to content

Instantly share code, notes, and snippets.

@abovedave
Created February 28, 2020 20:23
Show Gist options
  • Save abovedave/623aa740b0e33377275dc55e2ac65c85 to your computer and use it in GitHub Desktop.
Save abovedave/623aa740b0e33377275dc55e2ac65c85 to your computer and use it in GitHub Desktop.
const config = require(__dirname + '/../../../stripe.json')
const stripe = require('stripe')(config.secret)
const apiCongig = require('@dadi/api').Config
const Model = require('@dadi/api').Model
module.exports = (obj, type, data) => {
let customer = {}
switch(type) {
case 'beforeCreate':
customer = {
email: obj.email,
shipping: {
name: obj.name || null,
address: {
line1: obj.shippingLine1 || null,
line2: obj.shippingLine2 || null,
city: obj.shippingCity || null,
country: obj.shippingCountry || null,
postal_code: obj.shippingPostalCode || null
}
}
}
// If passed with a stripe token
if (obj.stripe) {
customer.source = obj.stripe
}
return stripe.customers.create(customer)
.then(response => {
obj.stripe = response.id
obj.joinedAt = response.created * 1000
return obj
})
.catch(err => {
throw err
})
break
case 'beforeUpdate':
customer = {
email: obj.email || data.updatedDocs[0].email,
shipping: {
name: obj.name || data.updatedDocs[0].name,
address: {
line1: obj.shippingLine1 || data.updatedDocs[0].shippingLine1,
line2: obj.shippingLine2 || data.updatedDocs[0].shippingLine2,
city: obj.shippingCity || data.updatedDocs[0].city,
country: obj.shippingCountry || data.updatedDocs[0].country,
postal_code: obj.shippingPostalCode || data.updatedDocs[0].postal_code
}
}
}
return stripe
.customers
.update(data.updatedDocs[0].stripe, customer)
.then(() => {
return obj
})
break
case 'beforeDelete':
return stripe.customers.del(data.deletedDocs[0].stripe, () => {
return obj
})
break
default:
return obj
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment