methods/img.js

  1. import _config from './../lib/config'
  2. /**
  3. * @method
  4. * @memberof ecomUtils
  5. * @name img
  6. * @description Returns img object (with url and alt) from product body or pictures list.
  7. * @param {object|array} product - Product body object or list of picture objects
  8. * @param {string} [pictureId] - ObjectID of preferred picture to find in the list
  9. * @param {string} [size=$ecomConfig.get('default_img_size')] - Preferred image size
  10. * (generally `normal`) to find on picture object
  11. * @returns {object|undefined}
  12. *
  13. * @example
  14. * const product = { 'pictures': [ { 'small': { 'url': 'https://ecom.com/imgs/100px/64gb.jpg'}, 'big': { 'url': 'https://ecom.com/imgs/700px/64gb.jpg' }, '_id': '694890155127368133600000' }, { 'small': { 'url': 'https://ecom.com/imgs/100px/e-5-64gb.jpg' }, 'big': { 'url': 'https://ecom.com/imgs/700px/e-5-64gb.jpg' }, '_id': '694890155127368133600001' }, { 'small': { 'url': 'https://ecom.com/imgs/100px/5-64gb.jpg' }, 'big': { 'url': 'https://ecom.com/imgs/700px/5-64gb.jpg' }, '_id': '694890155127368133600002' } ], 'name': 'Smartphone Xiaomi' }
  15. * const id = '694890155127368133600001'
  16. * const size = 'big'
  17. * ecomUtils.img(product, id, size)
  18. * // => {url: 'https://ecom.com/imgs/700px/e-5-64gb.jpg'}
  19. */
  20. const img = (product, pictureId, size) => {
  21. if (!size) {
  22. size = _config.get('default_img_size') || 'normal'
  23. }
  24. if (product) {
  25. // product object has 'pictures'
  26. // cart item object has 'picture'
  27. let { pictures, picture } = product
  28. if (!picture) {
  29. if (!pictures) {
  30. if (Array.isArray(product)) {
  31. // received list of pictures ?
  32. pictures = product
  33. } else {
  34. // received picture object ?
  35. picture = product
  36. }
  37. }
  38. }
  39. if (Array.isArray(pictures)) {
  40. // select one img object from product pictures
  41. picture = (pictureId && pictures.filter(pic => pic._id === pictureId)[0]) || pictures[0]
  42. }
  43. let img
  44. if (typeof picture === 'object' && picture !== null) {
  45. img = picture[size]
  46. if (!img) {
  47. // try predefined any size
  48. let sizes
  49. switch (size) {
  50. case 'small':
  51. sizes = ['normal', 'big']
  52. break
  53. case 'normal':
  54. sizes = ['big', 'zoom', 'small']
  55. break
  56. case 'big':
  57. sizes = ['zoom', 'normal']
  58. break
  59. case 'zoom':
  60. sizes = ['big']
  61. break
  62. default:
  63. sizes = ['big', 'zoom', 'normal', 'small']
  64. }
  65. for (let i = 0; i < sizes.length; i++) {
  66. const size = sizes[i]
  67. if (picture[size]) {
  68. return picture[size]
  69. }
  70. }
  71. // last try with custom sizes
  72. for (const size in picture) {
  73. if (picture[size] && picture[size].url) {
  74. return picture[size]
  75. }
  76. }
  77. }
  78. }
  79. return img
  80. }
  81. return undefined
  82. }
  83. export default img