npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

shopify-cart

v1.1.3

Published

Shopify AJAX cart API wrapper.

Downloads

14

Readme

Cart

A wrapper for the Shopify AJAX cart API.

Getting started

Using Shopify Slate V1 or other ES6 project that supports imports

import Cart from 'shopify-cart';
window.cart = new Cart({ configuration })

Configuration

cart

Example
  window.cart = new Cart({ cart: window.cartJSON })

Type | Description | Default ---------|----------------------------|------------- Object | A JSON object of the cart. | null

If a cart object is no provided one will be created using an ajax request. Therefore by using this option we can improve performance by reducing the number of requests. The best way to create this cart object on page load is with liquid.

selectors

Example
window.cart = new Cart({
  selectors: {
    decreaseQuantity: '[data-minus-one]',
    increaseQuantity: '[data-plus-one]',
    addItem: '[data-add-to-cart]',
    quickAdd: '[data-quick-add]',
    quickAddQuantity: '[data-quick-add-qty]',
    quickAddProperties: '[data-quick-add-properties]',
    removeItem: '[data-remove-item]'
  }
})
[data-minus-one]
<button data-minus-one="2">
  Minus one by line index
</button>
[data-plus-one]
<button data-plus-one="2">
  Add one by line index
</button>
[data-remove-item]
<button data-remove-item="1">
  Remove by line
</button>
[data-add-to-cart]
<form>
  <input name="id" value="{{ variant.id }}" />
  <input name="quantity" value="1" /> <!-- optional, defaults to 1 -->
  <input name="properties[gift_wrap]" value="true" />
  <button data-add-to-cart="{{ variant.id }}">Add products with line item properties</button>
</form>
[data-quick-add]
<button data-quick-add="{{ variant.id }}" data-quick-add-properties='{ "gift_wrap": true }'>
  Add product
</button>

Type | Description | Default ---------|----------------------------|------------- Object | An object of css selectors. | null

If no selectors are provided the above example selectors will be used as the defaults.

options

Example
window.cart = new Cart({
  options: {
    getUrl: '/cart?view=json',
    timeout: 1000
  }
})

Type | Description | Default ---------|----------------------------|------------- Object | An object of options | null

getUrl

Type | Description | Default ---------|---------------------------------------------------------|------------- String | A url where the cart JSON should be requested from | /cart.json

The default cart response lacks information such as variant inventory or variant options. This limitation can be overcome by creating a custom cart endpoint and requesting the json from there. In this way you can customise the structure of the data too.

timeout

Type | Description | Default ----------|---------------------------------------------------------|------------- Integer | Debounce some requests by a certain amount. | 1000

The updateItemByLine method debounces requests by 1 second default. This is because these requests can be queued and sent in one request rather than making multiple requests. This is especially useful default behaviour if the site includes plus and minus quantity buttons.

Events API

There are a series of events that you can listen for from the cart.

error

Fires any time a request was unsuccessful for any reason.

document.addEventListener('cart:error', (event) => {
  console.error(event.detail.response)
})

cart:sending

Fires before a request is sent, can be useful for updating or disabling buttons before a response comes back. The response object will return the type of request that is about the be sent and the data that will be sent.

document.addEventListener('cart:sending', (event) => {
  const { response } = event.detail
})

cart:itemAdded

Fire after an item has been added to the cart. This will return the line item that was just added.

document.addEventListener('cart:itemAdded', (event) => {
  const { response } = event.detail
  console.log(response.lineItem)
})

cart:updated

Fires after the cart object has been updated. Returns the new cart object.

document.addEventListener('cart:updated', (event) => {
  const { response } = event.detail
  console.log(response.cart)
})

Methods

NOTICE: Callbacks

All methods have the option of providing custom success and error callbacks which can be useful for a host of custom behaviours. By default most will fire an event as listed above in the Events API section. By adding a custom success or error you will overwrite these events.

getCart({config})

Example
  window.cart.getCart({
    success: (cart) => {
      console.log(cart)
    },
    error: (err) => {
      console.error(err)
    }
  })
success

Default success gets a new cart object and fires a 'cart:updated' event.

addItem({item}, {config})

Example
window.cart.addItem(
  {
    id: 3284983453455,
    quantity: 1,
    properties: {
      propertyName: 'propertyValue'
    }
  },
  {
    success: (item) => {
      console.log(item)
    },
    error: (err) => {
      console.error(err)
    }
  }
)
success

Default success fires a 'cart:itemAdded' event.

removeItemById(id, {config})

Example
window.cart.addItem(3284983453455,
  {
    success: (item) => {
      console.log(item)
    },
    error: (err) => {
      console.error(err)
    }
  }
)
success

Default success gets a new cart object and fires a 'cart:updated' event.

removeItemByLine(line, {config})

line: is a the 1 indexed location of the item that you wish to remove. If you wish to remove the first item in the cart pass 1.

Example
window.cart.removeItemByLine(1,
  {
    success: (item) => {
      console.log(item)
    },
    error: (err) => {
      console.error(err)
    }
  }
)
success

Default success gets a new cart object and fires a 'cart:updated' event.

updateItemById(id, quantity, {config})

id: Id of the variant you wish to modify. quantity: The new desired quantity.

Example
window.cart.updateItemById(12345234243, 4,
  {
    success: (item) => {
      console.log(item)
    },
    error: (err) => {
      console.error(err)
    }
  }
)
success

Default success gets a new cart object and fires a 'cart:updated' event.

updateItemByLine(line, quantity, {config})

line: 1 indexed line of the variant you wish to modify. quantity: The new quantity.

Example
window.cart.updateItemByLine(1, 4,
  {
    success: (item) => {
      console.log(item)
    },
    error: (err) => {
      console.error(err)
    }
  }
)
success

Default success gets a new cart object and fires a 'cart:updated' event.

setAttributes({config})

config.attributes: Object of the attributes that you wish to modify.

Example
window.cart.setAttributes({
  attributes: {
    pickup_store_id: location.location.store_id,
    pickup_store_name: location.name
  },
  success: (item) => {
    console.log(item)
  },
  error: (err) => {
    console.error(err)
  }
})
success

Default success gets a new cart object and fires a 'cart:updated' event.

changeItemByLine(line, quantity, {config})

line: 1 indexed line of the variant you wish to modify. quantity: The new quantity.

Example
window.cart.changeItemByLine(1, 4,
  {
    properties: {
      propertyName: 'propertyValue'
    }
    beforeSend: (requestType, requestData) => {
      console.log(requestData)
    },
    success: (item) => {
      console.log(item)
    },
    error: (err) => {
      console.error(err)
    }
  }
)
success

Default success gets a new cart object and fires a 'cart:updated' event.

getShippingRates({config})

Example
window.cart.getShippingRates({
  data: 'shipping_address[zip]=3141&shipping_address[country]=Australia&shipping_address[province]=Victoria',
  success: (item) => {
    console.log(item)
  },
  error: (err) => {
    console.error(err)
  }
})

More examples

Example custom cart object with getUrl

templates/cart.json.liquid
{%- layout none -%}
{%- include 'cart-json' -%}

snippets/cart-json.liquid

{
  "token": "{{ cart.token }}",
  "note": "{{ cart.note }}",
  "attributes": {{ cart.attributes | json }},
  "original_total_price": {{ cart.original_total_price }},
  "total_price": {{ cart.total_price }},
  "total_discount": {{ cart.total_discount }},
  "total_weight": {{ cart.total_weight }},
  "item_count": {{ cart.item_count }},
  "items": [
    {%- for item in cart.items -%}
      {%- assign selected_size = item.variant.options[1]  -%}
      {%- assign selected_colour = item.variant.options[0]  -%}
      {%- capture variants -%}
        [
          {% if item.product.variants.size > 1 %}
            {%- assign first = true -%}
            {%- for variant in item.product.variants -%}
              {%- if variant.options[0] == selected_colour -%}
                {%- unless first -%},{%- endunless -%}{
                  {% assign first = false %}
                  "id": {{ variant.id }},
                  "title": {{ variant.title | json }},
                  "available": {{ variant.available }},
                  "selected": {% if variant.options[1] == selected_size %}true{% else %}false{% endif %},
                  "size": {{ variant.options[01] | json }}
                }
              {%- endif -%}
            {%- endfor -%}
          {% else %}
            {%- for variant in item.product.variants -%}
              {
                "id": {{ variant.id }},
                "title": {{ variant.title | json }},
                "available": {{ variant.available }},
                "selected": {% if variant.options[1] == selected_size %}true{% else %}false{% endif %},
                "size": {{ variant.options[1] | json }}
              }{%- unless forloop.last -%},{%- endunless -%}
            {%- endfor -%}
          {% endif %}
        ]
      {%- endcapture -%}
      {
        "id": {{ item.id }},
        "properties": { {%- for property in item.properties -%}
          "{{ property | first }}": "{{ property | last }}"{% unless forloop.last %},{% endunless -%}
        {%- endfor -%} },
        "quantity": {{ item.quantity }},
        "variant_id": {{ item.variant_id }},
        "key": "{{ item.key }}",
        "title": "{{ item.title }}",
        "price": {{ item.price }},
        "tags": {{ item.product.tags | json }},
        "original_price": {{ item.original_price }},
        "compare_at_price": {% if item.variant.compare_at_price %}{{ item.variant.compare_at_price }}{% else %}null{% endif %},
        "compare_at_line_price": {% if item.variant.compare_at_price %}{{ item.variant.compare_at_price | times: item.quantity }}{% else %}null{% endif %},
        "discounted_price": {{ item.discounted_price }},
        "line_price": {{ item.line_price }},
        "original_line_price": {{ item.original_line_price }},
        "total_discount": {{ item.total_discount }},
        "discounts": {{ item.discounts | json }},
        "sku": "{{ item.sku }}",
        "grams": {{ item.grams }},
        "vendor": "{{ item.vendor }}",
        "taxable": {{ item.taxable }},
        "product_id": {{ item.product_id }},
        "gift_card": {{ item.gift_card }},
        "url": "{{ item.url }}",
        "image": "{% if item.image == blank %}{{ settings.no_image | img_url: '500x' }}{% else %}{{ item.image | img_url: '500x' }}{% endif %}",
        "handle": "{{ item.product.handle }}",
        "requires_shipping": {{ item.requires_shipping }},
        "product_type": "{{ item.product.type }}",
        "product_title": "{{ item.product.title }}",
        "product_description": {{ item.product.description | json }},
        "variant_title": "{{ item.variant.title }}",
        "variant_options": {{ item.variant.options | json }},
        "options_with_values": {{ item.product.options_with_values | json }},
        "options": {{ item.product.options | json }},
        "inventory_quantity": {{ item.variant.inventory_quantity }},
        "inventory_policy": {{ item.variant.inventory_policy | json }},
        "selected_colour": {% if selected_colour %}"{{ selected_colour }}"{% else %}null{% endif %},
        "variants": {{ variants }}
      }{%- unless forloop.last -%},{%- endunless -%}
    {%- endfor -%}
  ]
}

License

The code is available under an ISC License.