Created
November 10, 2020 23:09
-
-
Save richardcalahan/f10be5c1b872f93ecd76b5d874a14c2f 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 Promise from 'bluebird' | |
import Cookies from 'js-cookie' | |
export const init = () => { | |
return Promise.map(window.vinoshipper.accounts, account => { | |
return $ | |
.get(`https://vinoshipper.com/json-api/v2/wine-list?id=${account.id}`) | |
.then(data => { | |
account.shipsTo = data.shipsTo | |
account.wines = data.wines | |
return account | |
}) | |
}).then(accounts => { | |
window.vinoshipper.accounts = accounts | |
return accounts | |
}) | |
} | |
export const getAccountByState = ( state ) => { | |
return _.find(window.vinoshipper.accounts, a => { | |
return _.chain(a.shipsTo).map(st => st.abbr).includes(state).value() | |
}) | |
} | |
export const getWineFromAccount = ( productIds, account ) => { | |
if ( !account ) return false | |
return _.find(account.wines, w => { | |
return _.includes(productIds, w.id) | |
}) | |
} | |
export const getWines = ( productIds ) => { | |
return _ | |
.chain(window.vinoshipper.accounts) | |
.map(account => account.wines) | |
.flatten() | |
.filter(wine => _.includes(productIds, wine.id)) | |
.value() | |
} | |
export const createCart = () => { | |
$.post('https://vinoshipper.com/json-api/v2/cart').then(resp => { | |
Cookies.set('VSCartId', resp.id, { expires: 10 }) | |
return resp | |
}) | |
} | |
export const getCart = () => { | |
let cartId = Cookies.get('VSCartId') | |
return $.get(`https://vinoshipper.com/json-api/v2/cart/${cartId}`) | |
} | |
export const getOrCreateCart = () => { | |
return getCart().fail(() => createCart()) | |
} | |
export const addWine = ( id, qty=1 ) => { | |
return getOrCreateCart().then(cart => { | |
return $.ajax({ | |
type: 'POST', | |
url: `https://vinoshipper.com/json-api/v2/cart/${cart.id}/item`, | |
data: JSON.stringify({ | |
id: id, | |
qty: qty, | |
quantity: qty | |
}), | |
contentType: 'application/json', | |
dataType: 'json' | |
}) | |
}) | |
} | |
export const updateWine = ( id, qty=1 ) => { | |
return getOrCreateCart().then(cart => { | |
return $.ajax({ | |
type: 'PUT', | |
url: `https://vinoshipper.com/json-api/v2/cart/${cart.id}/item/${id}`, | |
data: JSON.stringify({ | |
id: id, | |
qty: qty, | |
quantity: qty | |
}), | |
contentType: 'application/json', | |
dataType: 'json' | |
}) | |
}) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment