Your IP : 216.73.216.91


Current Path : /var/node/inatote/qa_inatote/products/
Upload File :
Current File : /var/node/inatote/qa_inatote/products/product.js

import requiredParam from '../helpers/required-param.js'
import { InvalidPropertyError } from '../helpers/errors.js'
import isValidEmail from '../helpers/is-valid-email.js'
import upperFirst from '../helpers/upper-first.js'
import makeproductList from './product-list.js'

export default function makeProduct(productInfo = requiredParam('productInfo')) {
    const validproduct = validate(productInfo)
    const normalproduct = normalize(validproduct)
    return Object.freeze(normalproduct)

    function validate({
        categoryId = requiredParam('categoryId'),
        vendorId = requiredParam('vendorId'),
        productName = requiredParam('productName'),
        description = requiredParam('description'),
        imageURL = requiredParam('imageURL'),
        unitPrice = requiredParam('unitPrice'),
        ...otherInfo
    } = {}) {

        validateProductrName(productName)
        validateUnitPrice(unitPrice)
        validateImageUrl(imageURL)
        
        return { categoryId, vendorId, productName, description, imageURL, unitPrice, ...otherInfo }

        function validateProductrName(name) {
            if (name.length < 2) {
                throw new InvalidPropertyError(
                    `A product's name must be at least 2 characters long.`
                )
            }
        }


        function validateImageUrl(url) {
            if (url.length < 1) {
                throw new InvalidPropertyError("Atleast one image is required")
            }
        }


        function validateUnitPrice(unitPrice) {
            if (parseFloat(unitPrice) == undefined || !parseFloat(unitPrice)) {
                throw new InvalidPropertyError(
                    `Invalid price format.`
                )
            }
        }

        function validateQuantity(quantity) {
            if (parseFloat(quantity) == undefined || !parseFloat(quantity)) {
                throw new InvalidPropertyError(
                    `Invalid quantity format.`
                )
            }
        }
    }


    function normalize({ productName, ...otherInfo }) {
        return {
            ...otherInfo,
            productName: upperFirst(productName),
            ratingAverage : otherInfo.ratingAverage ? otherInfo.ratingAverage : 0,
            ratingCount : otherInfo.ratingCount ? otherInfo.ratingCount : 0,
            ratingSum: otherInfo.ratingSum ? otherInfo.ratingSum : 0,
        }
    }
}