Skip to content

Instantly share code, notes, and snippets.

@tobiasdalhof
Last active May 7, 2018 08:24
Show Gist options
  • Save tobiasdalhof/39e6418b088d2019627c9cb99d950266 to your computer and use it in GitHub Desktop.
Save tobiasdalhof/39e6418b088d2019627c9cb99d950266 to your computer and use it in GitHub Desktop.
import DeliveryMessageHelper from "./Helper";
export default class DeliveryMessageShopify {
static EVENT_DONE () {
return 'DeliveryMessageShopify::DONE'
}
constructor () {
this.shop = Shopify.shop
this.isProductPage = DeliveryMessageShopify.checkProductPage()
this.isCollection = DeliveryMessageShopify.checkCollection()
this.productURL = DeliveryMessageShopify.getProductURL()
this.collectionURL = DeliveryMessageShopify.getCollectionURL()
this.fetchShopifyData()
}
/**
* Fetch product and collection data from current shop.
*/
async fetchShopifyData () {
if (this.isProductPage !== true) {
return
}
try {
const fetches = []
fetches.push(this.fetchProduct())
if (this.isCollection) {
fetches.push(this.fetchCollection())
}
const response = await Promise.all(fetches)
const shopifyData = {}
shopifyData.product = response[0]
if (this.isCollection) {
shopifyData.collection = response[1].collection
}
document.dispatchEvent(
new CustomEvent(DeliveryMessageShopify.EVENT_DONE(), {
detail: shopifyData
})
)
} catch (error) {
console.log(error)
}
}
/**
* Fetch product from current store.
* @returns {Promise}
*/
fetchProduct () {
return fetch(this.productURL, {
credentials: 'same-origin'
}).then(response => response.json())
}
/**
* Fetch collection from current store.
* @returns {Promise}
*/
fetchCollection () {
return fetch(this.collectionURL, {
credentials: 'same-origin'
}).then(response => response.json())
}
/**
* Get myshopify.com URL.
* @returns {String}
*/
static getShop () {
return Shopify.shop
}
/**
* Check if current page is a product page.
* @returns {Boolean}
*/
static checkProductPage () {
return /products/.test(DeliveryMessageHelper.getCurrentURL()) === true
}
/**
* Check if product page contains an collection.
* @returns {Boolean}
*/
static checkCollection () {
return (DeliveryMessageShopify.checkProductPage() === true) &&
(/collections/.test(DeliveryMessageHelper.getCurrentURL()) === true)
}
/**
* Get current product API URL.
* @returns {String}
*/
static getProductURL () {
if (DeliveryMessageShopify.checkProductPage() === true) {
return `${DeliveryMessageHelper.getCurrentURL()}.js`
}
return null
}
/**
* Get collection API URL from current product.
* @returns {String}
*/
static getCollectionURL () {
if (DeliveryMessageShopify.checkCollection() === true) {
const paths = window.location.pathname.split('/')
return `${window.location.origin}/${paths[1]}/${paths[2]}.json`
}
return null
}
}
@tobiasdalhof
Copy link
Author

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