Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 | 1x 1x 10x 1x 18x 6x 1x 24x 48x 48x 24x 1x 11x 11x 11x 11x 1x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 3x 3x 5x 5x 5x 5x 5x 11x 9x 24x 6x 20x 20x 20x 20x 9x 3x 3x 3x 3x 3x 3x 3x 1x 1x 6x 6x 6x 6x 6x 6x 5x 5x 5x 10x 10x 5x 5x 5x 5x 8x 3x 8x 3x 5x 4x 4x 4x 4x 4x 4x 4x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 177x 177x 175x 175x 175x 175x 27x 27x 27x 27x 27x 27x 27x 3x 3x 3x 7x 1x 1x 2x 2x 2x 3x 2x 1x 2x 1x 9x 9x 9x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 4x 12x 8x 8x 8x 8x 28x 28x 28x 28x 28x 8x 4x 8x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 2x 2x 2x 2x 2x 2x 26x 26x 26x 2x 2x 2x 2x 2x 2x 2x 2x | /** @module merlins */
import {ScrapingConnector} from './scraping-connector'
const ROOT_CATEGORY = 'root'
/**
* Takes commerce-integrations Integer type and returns the URL
* representation used to view a product details page on the website.
*
* @param {module:types.Integer} id
* @returns {String}
* @private
*/
const getProductUrl = (id) => {
return `/${id}.html`
}
// This regex is used to get a product's ID from its "Wishlist" or "Compare"
// button. It's stored in a string in a data attribute of the button.
const PRODUCT_REGEXP = new RegExp(/product":"([0-9]*)","/)
/**
* Takes a Magento product attribute value object and parses out a
* commerce-integrations VariationPropertyValue type
*
* @param {Object} data
* @returns {module:types.VariationPropertyValue}
* @private
*/
const parseVariationPropertyValue = ({label, id}) => ({
name: label,
value: id
})
/**
* Takes a Magento product variation attribute object and parses out a
* commerce-integrations VariationProperty type
*
* @param {Object} data
* @returns {module:types.VariationProperty}
* @private
*/
const parseVariationProperty = ({code, label, options = []}) => ({
id: code,
label,
values: options.map(parseVariationPropertyValue)
})
/**
* Takes a Magento product object and parses out an
* commerce-integrations Variation type
*
* @param {Object} data
* @returns {module:types.Variation}
* @private
*/
const parseVariation = (id, value, config) => {
const convertedValues = Object.keys(value).reduce((acc, curr) => {
acc[config.attributes[curr].code] = value[curr]
return acc
}, {})
return {
id,
price: parseFloat(config.optionPrices[id].basePrice.amount),
orderable: true, // Magento doesn't show out of stock variations... I think...
values: convertedValues
}
}
/**
* Takes a takes a Magento image object and returns a set of commerce-integrations
* Image type.
*
* @param {Object} data
* @returns {Array.<module:types.Image>}
* @private
*/
const parseImageSet = ({caption, full, thumb}) => {
const sets = []
// Parse `full` image
sets.push({
images: [{title: caption, src: full, alt: caption}],
variationProperties: [],
sizeType: 'full'
})
// Parse `thumb` image
sets.push({
images: [{title: caption, src: thumb, alt: caption}],
variationProperties: [],
sizeType: 'thumb'
})
return sets
}
/**
* Takes a document object and parses out a commerce-integrations Product type
*
* @param {Object} htmlDoc a {@link https://developer.mozilla.org/en-US/docs/Web/API/Document|Document} object
* @returns {Promise<module:types.Product>}
* @private
*/
const parseProduct = (htmlDoc, id) => {
const name = htmlDoc.querySelector('.page-title').textContent
const description = htmlDoc.querySelector('.product.description').textContent
const categoryEl = htmlDoc.querySelector('.breadcrumbs .item:nth-last-child(2) a')
const priceEl = htmlDoc.querySelector('meta[property="product:price:amount"]')
const skuEl = htmlDoc.querySelector('.sku .value')
// Parse the categoryId
let categoryId
Eif (categoryEl) {
const categoryIdMatch = categoryEl.pathname.match(/\/([^.]+)\.html/)
categoryId = categoryIdMatch && categoryIdMatch[1]
}
// Parse the currency, price, prices, upc
let price
let upc
Eif (priceEl) { price = parseFloat(priceEl.getAttribute('content')) }
Eif (skuEl) { upc = skuEl.textContent }
// We'll get alot of the product information from an inline script which contains
// product details in the form of JSON.
let productConfig
const productScriptEls = htmlDoc.querySelectorAll('.product-add-form script')
if (productScriptEls && productScriptEls.length > 1) { // NOTE: If there are variations there will be more than 1 script
const productScriptJSON = JSON.parse(productScriptEls[0].textContent)
productConfig = productScriptJSON['#product_addtocart_form'].configurable.spConfig
}
let galleryConfig
const galleryScriptEl = htmlDoc.querySelector('.product.media script')
Eif (galleryScriptEl) {
const galleryScriptJSON = JSON.parse(galleryScriptEl.textContent)
galleryConfig = galleryScriptJSON['[data-gallery-role=gallery-placeholder]']['mage/gallery/gallery'].data
}
return {
id,
name,
imageSets: galleryConfig &&
galleryConfig.reduce((acc, curr) => ([...acc, ...parseImageSet(curr)]), []),
description,
categoryId, // NOTE: Without the category in the path, it won't show up in the bread crumbs.
brand: `Merlin's Potions`,
minimumOrderQuantity: 1,
stepQuantity: 1,
upc,
unit: 'ea',
price,
prices: productConfig &&
Object.keys(productConfig.prices).reduce((acc, curr) => ({...acc, ...{[curr]: productConfig.prices[curr].amount}}), {}),
variations: productConfig &&
Object.keys(productConfig.index).map((key) => parseVariation(key, productConfig.index[key], productConfig)),
variationProperties: productConfig &&
Object.keys(productConfig.attributes).map((attributeId) => parseVariationProperty(productConfig.attributes[attributeId])),
variationValues: productConfig && productConfig.defaultValues
}
}
/**
* A connector for www.merlinspotions.com, using screen-scraping.
*
* @implements {module:interfaces.CommerceConnector}
*/
export class MerlinsConnector extends ScrapingConnector {
constructor({window, basePath, dondeGeoBasePath, dondeApiBasePath, cookieDomainRewrites}) {
super({window, cookieDomainRewrites})
this.basePath = basePath
this.dondeGeoBasePath = dondeGeoBasePath
this.dondeApiBasePath = dondeApiBasePath
}
/**
* @private
*/
loginUrl() {
return `${this.basePath}/customer/account/login/`
}
/**
* @inheritDoc
*/
login(username, password) {
return this.agent.get(this.loginUrl())
.then((res) => this.buildDocument(res))
.then((doc) => doc.querySelector('#login-form input[name="form_key"]').value)
.then((formKey) => ({
form_key: formKey,
'login[username]': username,
'login[password]': password,
persistent_remember_me: 'on',
send: '',
}))
.then((data) => (
this.agent.post(`${this.basePath}/customer/account/loginPost/`)
.type('form')
.send(data)
)
)
.then((res) => this.buildDocument(res))
.then(() => this.getCustomer('me'))
}
/**
* @inheritDoc
*/
logout() {
return this.agent.post(`${this.basePath}/customer/account/logout/`)
.then(() => undefined)
}
/**
* @inheritDoc
*/
getCustomer(id) {
Iif (id !== 'me') {
return Promise.reject(new Error('This backend only supports getting the current customer ' +
'(pass "me" as the ID)'))
}
const ensureLoggedIn = (res) => {
const loggedOut = res.redirects.indexOf(this.loginUrl()) >= 0
return loggedOut ? Promise.reject(new Error('logged out')) : Promise.resolve(res)
}
return this.agent.get(`${this.basePath}/customer/account/edit/`)
.then((res) => ensureLoggedIn(res))
.then((res) => this.buildDocument(res))
.then((doc) => {
const form = doc.getElementById('form-validate')
return {
id: 'me',
firstName: form.querySelector('input[name="firstname"]').value,
lastName: form.querySelector('input[name="lastname"]').value,
email: form.querySelector('input[name="email"]').value,
}
})
}
/**
* @inheritDoc
*/
refreshSession() {
// This is for interface compatibility - it's not necessary
// on a screen-scraping connector, generally.
return this.getCustomer('me')
}
/**
* Given a configuration in the form of a plain object, this method returns
* a new MerlinsConnector instance.
*
* @param {Object} config
*
* @returns {module:types.MerlinsConnector} The new MerlinsConnector instance.
*/
static fromConfig(config) {
return new this.prototype.constructor(config)
}
/**
* @inheritDoc
*/
getProduct(id) {
const url = `${this.basePath}${getProductUrl(id)}`
return this.agent.get(url)
.then((res) => this.buildDocument(res))
.then((htmlDoc) => {
Iif (htmlDoc.title === '404 Not Found') {
throw new Error('Product Not Found')
}
return htmlDoc
})
.then((htmlDoc) => this.parseProduct(htmlDoc, id))
}
/**
* @inheritDoc
*/
getProducts(ids = []) {
const getProductPromises = ids.map((id) => this.getProduct(id).catch(() => null))
return Promise.all(getProductPromises)
.then((products) => {
const validProducts = products.filter((product) => !!product)
return {
count: validProducts.length,
data: validProducts,
total: validProducts.length
}
})
}
/**
* Takes a OCAPI Product object and parses it into a commerce-integrations Product type.
* @param {Object} data a OCAPI {@link https://documentation.demandware.com/DOC1/topic/com.demandware.dochelp/OCAPI/18.3/shop/Documents/Product.html|Product} document
*
* @returns {Promise<module:types.Store>}
*/
parseProduct(data, id) {
return parseProduct(data, id)
}
/**
* @inheritDoc
*/
searchProducts(productSearchRequest) {
const url = `${this.basePath}${this.getSearchUrl(productSearchRequest)}`
Eif (!productSearchRequest.count || [5, 10, 15].includes(productSearchRequest.count)) {
console.warn(`The Merlins backend only supports 'count' values of 5, 10, 15. Defaulting to 5.`)
productSearchRequest.count = 5
}
return this.agent.get(url)
.then((res) => this.buildDocument(res))
.then((htmlDoc) => this.parseSearchProducts(htmlDoc, productSearchRequest))
}
parseGetStore(htmlDoc) {
// Parse the page into the models unique parts and assign them to the result.
const mainContent = htmlDoc.getElementById('maincontent')
const name = mainContent.querySelector('.location-title').textContent
const addressLine1 = mainContent.querySelector('[itemprop="streetAddress"]').textContent.trim()
const city = mainContent.querySelector('[itemprop="addressLocality"]').textContent
const country = mainContent.querySelector('.location-crumb.first-crumb').textContent
const phone = mainContent.querySelector('[itemprop="telephone"]').textContent.replace(new RegExp('[(]|[)]|[.]|[ ]|[-]|[#]|[x]', 'g'), '')
const postalCode = mainContent.querySelector('[itemprop="postalCode"]').textContent
const hoursContent = this.window.document.createElement('div')
hoursContent.innerHTML = mainContent.querySelector('#hoursBlock').textContent
const hours = {}
const hoursNodeList = hoursContent.querySelectorAll('.fh-item')
hoursNodeList.forEach((hour) => {
const content = hour.querySelector('[itemprop="name"]')
if (content) {
const day = content.textContent.slice(0, -1)
const openingTime = hour.querySelector('[itemprop="opens"]').textContent
const closingTime = hour.querySelector('[itemprop="closes"]').textContent
hours[day] = {
openingTime,
closingTime
}
}
})
return {
addressLine1,
city,
country,
name,
phone: phone ? phone : undefined,
postalCode: postalCode ? postalCode : undefined,
hours: hours ? hours : undefined
}
}
/**
* @inheritDoc
*/
getStore(id) {
const storesBasePath = this.basePath.replace('www', 'locations')
const url = `${storesBasePath}/${id}.html?utm_source=storelocator`
return this.agent.get(url)
.then((res) => this.buildDocument(res))
.then((htmlDoc) => this.parseGetStore(htmlDoc))
.then((data) => ({...data, id}))
}
/**
* @inheritDoc
*/
getCategory(id) {
// Always request the basePath for getting all categories
return this.agent.get(this.basePath)
.then((res) => this.buildDocument(res))
.then((htmlDoc) => {
let category
if (id === ROOT_CATEGORY) {
const categoryEls = [...htmlDoc.querySelectorAll('.navigation a')].map((el) => el.parentElement)
const categories = categoryEls.map(this.parseCategory)
category = {
id: ROOT_CATEGORY,
categories
}
} else {
const categoryAnchorEl = htmlDoc.querySelector(`.navigation a[href*="${id}"]`)
Iif (!categoryAnchorEl) {
throw new Error('Category Not Found')
}
category = this.parseCategory(categoryAnchorEl.parentElement)
}
return category
})
}
/**
* @inheritDoc
*/
getCategories(ids = []) {
const getCategoryPromises = ids.map((id) => this.getCategory(id).catch(() => null))
return Promise.all(getCategoryPromises)
.then((categories) => {
const validCategories = categories.filter((category) => !!category)
return {
count: validCategories.length,
data: validCategories,
total: validCategories.length
}
})
}
/**
* Takes a html element that represents a category and parses it into a commerce-integrations
* Category type.
*
* @param {Object} htmlDoc a {@link https://developer.mozilla.org/en-US/docs/Web/API/Element|Element} object
*
* @returns {Promise<module:types.Category>}
*/
parseCategory(categoryEl) {
const anchorEl = categoryEl.querySelector('a')
const idMatch = anchorEl.pathname.match(/[^\\](\w+).html$/)
return {
id: idMatch && idMatch[1],
name: anchorEl.innerText
}
}
/**
* Takes commerce-integrations ProductSearchRequest type and returns the URL
* representation used to query the website.
*
* @param {module:types.ProductSearchRequest} productSearchRequest
*
* @returns {String}
*/
getSearchUrl({
count,
sort,
start,
total,
query,
filters = {},
}) {
const params = []
const pathname = query ?
'/catalogsearch/result/' :
`/${filters.categoryId}.html`
if (count) { params.push(`product_list_limit=${count}`) }
Iif (total) { params.push(`product_list_total=${total}`) }
if (sort) { params.push(`product_list_order=${sort}`) }
Iif (start) { params.push(`p=${Math.ceil(total / start)}`) }
Iif (query) { params.push(`q=${query}`) }
// Compose the filters part of the url
Object.keys(filters)
.filter((key) => !['categoryId'].includes(key))
.forEach((key) => {
params.push(`${key}=${filters[key]}`)
})
return `${pathname}?${params.sort().join('&')}`
}
/**
* Takes a dom element representing a merlins search result product tile and parses out an
* commerce-integrations ProductSearchResult type.
*
* @param {Object} productEl a {@link https://developer.mozilla.org/en-US/docs/Web/API/Element|Element} object
*
* @returns {module:types.ProductSearchResult}
*/
parseProductSearchResult(productEl) {
const linkEl = productEl.querySelector('.product-item-link')
const imageEl = productEl.querySelector('.product-image-photo')
const priceEl = productEl.querySelector('.price')
const stockEl = productEl.querySelector('.stock')
const productName = linkEl.textContent
const actionButtonData = productEl.querySelector('.towishlist').getAttribute('data-post')
const productId = PRODUCT_REGEXP.exec(actionButtonData)[1]
const available = !stockEl
let price
Eif (available) {
const priceMatch = priceEl.textContent.match(/\$(.+)/)
price = priceMatch ? parseFloat(priceEl.textContent.match(/\$(.+)/)[1]) : ''
} else {
price = -1 // Something obviously invalid
}
const image = {
alt: imageEl.getAttribute('alt'),
description: imageEl.getAttribute('alt'),
src: imageEl.getAttribute('src'),
title: imageEl.getAttribute('alt')
}
return {
available,
productId,
productName,
defaultImage: image,
price,
variationProperties: []
}
}
/**
* Takes a dom element representing a merlins sorting select and parses out an
* array od commerce-integrations SortOption type.
*
* @param {Object} sortEl a {@link https://developer.mozilla.org/en-US/docs/Web/API/Element|Element} object
*
* @returns {Array.<module:types.SortOption>}
*/
parseSortingOptions(sortEl) {
const optionEls = sortEl.querySelectorAll('option')
return [...optionEls].map((el) => ({
id: el.value,
label: el.innerHTML
}))
}
/**
* Takes a dom element representing a merlins filter and parses out an
* commerce-integrations Filter type.
*
* @param {Object} optionEl a {@link https://developer.mozilla.org/en-US/docs/Web/API/Element|Element} object
*
* @returns {module:types.Filter}
*/
parseFilter(optionEl) {
const label = optionEl.querySelector('.filter-options-title').textContent
const propertyId = label.toLowerCase()
const valueEls = optionEl.querySelectorAll('.items .item')
const values = [...valueEls].map((valueEl) => {
const countEl = valueEl.querySelector('.count')
const anchorEl = valueEl.querySelector('a')
// Parse out the count and then remove the element so we can get the label text.
const count = parseInt(countEl.textContent)
countEl.remove()
return {
count,
label: anchorEl.textContent.trim(),
value: anchorEl.search.match(/\w=([^&]+)/)[1]
}
})
return {
propertyId,
label,
values
}
}
/**
* Takes a dom element representing a merlins selected filter and parses out a
* commerce-integrations Filter type.
*
* @param {Object} selectedEl a {@link https://developer.mozilla.org/en-US/docs/Web/API/Element|Element} object
* @param {String} currentUrl The current page url used to help determine filter values.
*
* @returns {module:types.Filter}
*/
parseSelectedFilter(selectedEl, currentUrl) {
// Use an anchor to parse out the search string
const anchorEl = this.window.document.createElement('a')
anchorEl.href = currentUrl
const label = selectedEl.querySelector('.filter-label').textContent
const propertyId = label.toLowerCase()
const valueLabel = selectedEl.querySelector('.filter-value').textContent
const valueValue = anchorEl.search.match(new RegExp(`${propertyId}=([^&]+)`))[1]
return {
propertyId,
label,
values: [{
label: valueLabel,
value: valueValue
}]
}
}
/**
* Takes a dom element and parses out an array of commerce-integrations
* Filter type representing those filters that are selected.
*
* @param {Object} selectedFiltersEl a {@link https://developer.mozilla.org/en-US/docs/Web/API/Element|Element} object
* @param {String} currentUrl The current page url used to help determine filter values.
*
* @returns {Array.<module:types.Filter>}
*/
parseSelectedFilters(selectedFiltersEl, currentUrl) {
const selectedEls = selectedFiltersEl.querySelectorAll('.items .item')
return [...selectedEls].map((el) => this.parseSelectedFilter(el, currentUrl))
}
/**
* Takes a dom element and parses out an array of commerce-integrations
* Filter type.
*
* @param {Object} filterOptionsEl a {@link https://developer.mozilla.org/en-US/docs/Web/API/Element|Element} object
* @param {String} currentUrl The current page url used to help determine filter values.
*
* @returns {Array.<module:types.Filter>}
*/
parseFilters(filterOptionsEl, currentUrl) {
// Note: Merlin's Potion's is unique in the way that it handles filters, normally
// you'd see checkboxes of all the filters with those that are selected being filled
// in. That makes it easy to parse. But in this case they are split up in two sections,
// one is the filters that aren't selected and a list of links, and the other is a
// section of selected filters with it's value.
// we'll have to parse these both to get as close to a complete list of all the filters.
const optionsEls = filterOptionsEl.querySelectorAll('.filter-options-item')
return [...optionsEls].map((el) => this.parseFilter(el, currentUrl))
}
parseSearchProducts(htmlDoc, searchRequest) {
const {filters, query} = searchRequest
const is404 = htmlDoc.title === '404 Not Found'
const isEmpty = !!htmlDoc.querySelector('.message.info.empty')
Iif (is404 || isEmpty) {
return {
count: 0,
filters: [],
results: [],
selectedFilters: filters,
sortingOptions: [],
start: 0,
total: 0
}
}
// This is the current url of the page, it'll be used to get filter values, etc.
const currentUrl =
JSON.parse(htmlDoc.querySelector('.toolbar-products')
.getAttribute('data-mage-init'))
.productListToolbarForm
.url
// Parse the page into the models unique parts and assign them to the result.
const mainContent = htmlDoc.getElementById('maincontent')
const resultEls = mainContent.querySelectorAll('.products.product-items > .product-item')
const pageSize = parseInt(mainContent.querySelector('#limiter').value)
const pageEl = mainContent.querySelector('.pages .current span:last-child')
const page = pageEl ? parseInt(pageEl.textContent) - 1 : 0
const filterOptionsEl = mainContent.querySelector('.filter-options')
const selectedFiltersEl = mainContent.querySelector('.filter-current')
const filterOptions = filterOptionsEl ?
this.parseFilters(filterOptionsEl, currentUrl) : []
const selectedFilters = selectedFiltersEl ?
this.parseSelectedFilters(selectedFiltersEl, currentUrl) : []
const sortEl = mainContent.querySelector('#sorter')
const totalEl = mainContent.querySelector('#toolbar-amount .toolbar-number')
return {
count: resultEls.length,
query: htmlDoc.querySelector('#search').value || query,
filters: [...filterOptions, ...selectedFilters],
results: [...resultEls].map(this.parseProductSearchResult),
selectedFilters: selectedFilters.reduce((obj, curr) => {
obj[curr.propertyId] = curr.values[0].value
return obj
}, {}),
selectedSortingOption: sortEl ? sortEl.value : '',
sortingOptions: sortEl ? this.parseSortingOptions(sortEl) : [],
start: page * pageSize,
total: totalEl ? parseInt(totalEl.textContent) : 0,
}
}
/**
* @inheritDoc
*/
searchStores(storeSearchRequest) {
let count = storeSearchRequest.count > 0 ? storeSearchRequest.count : 20
const start = storeSearchRequest.start > 0 ? storeSearchRequest.start : 0
const latitude = storeSearchRequest.latlon.latitude
const longitude = storeSearchRequest.latlon.longitude
let total
if (isNaN(latitude) || isNaN(longitude)) {
throw new Error('Provide Latitude and Longitude coordinates')
}
const getStoresUrl = `${this.dondeApiBasePath}/near?center=${latitude},${longitude}&dondeKey=56c3681586312e000e000001&_=1527268304391`
return this.agent.get(getStoresUrl)
.then((res) => res.body)
.then((jsonRes) => {
total = jsonRes.length
const stores = jsonRes.map((store) => {
const storeId = store.llp_url.replace('.html', '').substring(1)
return this.getStore(storeId)
.then((data) => {
return data
})
})
return Promise.all(stores).then((stores) => {
let storesToReturn
const totalPages = Math.ceil(total / count)
Eif (totalPages === start + 1) { // on last page
const remainder = total % count
Eif (remainder > 0) {
count = remainder
}
storesToReturn = stores.slice(stores.length - remainder)
} else if (totalPages < start + 1) {
throw new Error('No stores found')
} else { // middle pages
storesToReturn = stores.slice(start * count, (start + 1) * count)
}
return {
count,
start,
total,
stores: storesToReturn,
}
})
})
}
}
|