crowdstart.js
Version:
Ecommerce SDK for JavaScript and client for Crowdstart.
84 lines (60 loc) • 1.87 kB
text/coffeescript
Xhr = require 'xhr-promise-es6'
Xhr.Promise = require 'broken'
cookie = require 'js-cookie'
{isFunction, newError, updateQuery} = require '../utils'
module.exports = class XhrClient
sessionName: 'crwdst'
constructor: (opts = {}) ->
return new XhrClient opts unless @ instanceof XhrClient
= 'https://api.crowdstart.com'
{ , } = opts
if opts.endpoint
opts.endpoint
()
setEndpoint: (endpoint) ->
= endpoint.replace /\/$/, ''
setStore: (id) ->
= id
setKey: (key) ->
= key
getKey: ->
or or .KEY
getUserKey: ->
if (session = cookie.getJSON )?
= session.userKey if session.userKey?
setUserKey: (key) ->
cookie.set , {userKey: key}, expires: 7 * 24 * 3600 * 1000
= key
deleteUserKey: ->
cookie.set , {userKey: null}, expires: 7 * 24 * 3600 * 1000
getUrl: (url, data, key) ->
if isFunction url
url = url.call @, data
updateQuery ( + url), 'token', key
request: (blueprint, data, key = ()) ->
opts =
url: blueprint.url, data, key
method: blueprint.method
data: JSON.stringify data
if
console.log '--REQUEST--'
console.log opts
(new Xhr).send opts
.then (res) ->
if
console.log '--RESPONSE--'
console.log res
res.data = res.responseText
res
.catch (res) ->
try
res.data = res.responseText ? (JSON.parse res.xhr.responseText)
catch err
err = newError data, res
if
console.log '--RESPONSE--'
console.log res
console.log 'ERROR:', err
throw err