UNPKG

@pgprojectx/bazaarvoice-sdk

Version:
68 lines (55 loc) 1.8 kB
const axios = require('axios') const get = require('lodash.get') const debug = require('debug')('@pgalchemy/bazaarvoice') module.exports = config => { if (!config) throw new Error('`config` is required') if (!config.host) throw new Error('`config.host` is required') if (!config.apiVersion) throw new Error('`config.apiVersion` is required') if (!config.apiKey) throw new Error('`config.apiKey` is required') const request = (method, path, query = {}) => { const opts = { method, url: `${config.host}${path}`, params: { ...query, apiversion: config.apiVersion, passKey: config.apiKey } } return axios(opts) } const getProductReviews = async (productId, raw) => { if (!productId) throw new Error('`productId` is required') let reviewCount = 0 let reviews = [] let rating = false let error, key, product try { const path = '/data/reviews.json' const query = { Filter: `ProductID:${productId}`, Include: 'Products', Stats: 'Reviews' } const { data } = await request('GET', path, query) if (data.HasErrors) throw new Error(data.Errors[0].Code) if (raw) return data try { [key] = Object.keys(data.Includes.Products) product = get(data, `Includes.Products[${key}]`) } catch (err) { // $lab:coverage:off$ debug(`Rating not found for product id ${productId}`) // $lab:coverage:on$ } reviewCount = data.TotalResults reviews = data.Results rating = get(product, 'ReviewStatistics.AverageOverallRating') || false } catch (err) { error = err } if (error) throw error return { reviewCount, reviews, rating } } return { getProductReviews } }