UNPKG

amazon-modern-widgets

Version:

Amazon Modern Widgets for Amazon affiliate websites based on Amazon PAAPI v5

216 lines 8.73 kB
"use strict"; /** * Amazon Product API Class. * ---------------------------------------------- * Amazon Modern Widgets (AMW). * * @author : Ludovic Toinel <ludovic@toinel.com> * @src : https://github.com/ltoinel/amw */ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; var desc = Object.getOwnPropertyDescriptor(m, k); if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { desc = { enumerable: true, get: function() { return m[k]; } }; } Object.defineProperty(o, k2, desc); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; })); var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); var __importStar = (this && this.__importStar) || (function () { var ownKeys = function(o) { ownKeys = Object.getOwnPropertyNames || function (o) { var ar = []; for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; return ar; }; return ownKeys(o); }; return function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); __setModuleDefault(result, mod); return result; }; })(); var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.Paapi = void 0; const ConfigLog4j_1 = require("../utils/ConfigLog4j"); const config_1 = __importDefault(require("config")); const amazonPaapi = __importStar(require("amazon-paapi")); /** * Paapi Wrapper using amazon-paapi library */ class Paapi { /** * Default constructor */ constructor() { // Default resources to retrieve from Amazon this.defaultResources = [ 'Images.Primary.Large', 'ItemInfo.Title', 'Offers.Listings.Price', 'Offers.Listings.DeliveryInfo.IsPrimeEligible', 'Offers.Listings.Promotions' ]; // Debug the API calls this.debug = config_1.default.get('Server.debug'); // Setup the logger this.log = (0, ConfigLog4j_1.getLogger)("Paapi"); // Initialize common parameters for amazon-paapi this.commonParameters = { AccessKey: config_1.default.get('Amazon.accessKey'), SecretKey: config_1.default.get('Amazon.secretKey'), PartnerTag: config_1.default.get('Amazon.partnerTag'), PartnerType: config_1.default.get('Amazon.partnerType'), Marketplace: config_1.default.get('Amazon.marketplace') }; this.condition = config_1.default.get('Amazon.condition'); this.log.info(`Amazon PAAPI initialized for marketplace: ${this.commonParameters.Marketplace}`); } /** * Log success response for debugging */ // eslint-disable-next-line @typescript-eslint/no-explicit-any onSuccess(response) { this.log.debug('API called successfully.'); this.log.debug('Complete Response: \n' + JSON.stringify(response, null, 1)); if (response.Errors !== undefined) { this.log.debug('\nErrors:'); this.log.debug('Complete Error Response: ' + JSON.stringify(response.Errors, null, 1)); this.log.debug('Printing 1st Error:'); const error = response.Errors[0]; this.log.debug('Error Code: ' + error.Code); this.log.debug('Error Message: ' + error.Message); } } /** * On Error Handler */ // eslint-disable-next-line @typescript-eslint/no-explicit-any onError(error) { this.log.error('Error calling PA-API 5.0!'); this.log.error('Error details: ' + JSON.stringify(error, null, 1)); } /** * This function allows to search a product by its ID. * * @param {string} itemId The product ID to search. */ getItemApi(itemId) { return __awaiter(this, void 0, void 0, function* () { const requestParameters = { ItemIds: [itemId], ItemIdType: 'ASIN', Condition: this.condition, Resources: this.defaultResources }; try { // Call Amazon PAAPI using amazon-paapi library const data = yield amazonPaapi.GetItems(this.commonParameters, requestParameters); if (this.debug) { this.onSuccess(data); } // Check if we have items in the response if (!data.ItemsResult || !data.ItemsResult.Items || data.ItemsResult.Items.length === 0) { this.log.warn(`No product found for: ${itemId}`); return null; } // Build and return the product from the first item const product = this.buildProduct(data.ItemsResult.Items[0]); return product; } catch (error) { this.onError(error); return null; } }); } /** * This functions allows to search a product by a keyword. * * @param {string} keyword The keyword that describes the product to search. */ searchItemApi(keyword) { return __awaiter(this, void 0, void 0, function* () { const requestParameters = { Keywords: keyword, ItemCount: 1, Condition: this.condition, Resources: this.defaultResources }; try { // Call Amazon PAAPI using amazon-paapi library const data = yield amazonPaapi.SearchItems(this.commonParameters, requestParameters); if (this.debug) { this.onSuccess(data); } // Check if we have search results if (!data.SearchResult || !data.SearchResult.Items || data.SearchResult.Items.length === 0) { this.log.warn(`No product found for: ${keyword}`); return null; } // Build and return the product from the first search result const product = this.buildProduct(data.SearchResult.Items[0]); return product; } catch (error) { this.onError(error); return null; } }); } /** * Build a product from an item. * Using any type due to Amazon PAAPI SDK not exporting item types * * @param item the item to build */ // eslint-disable-next-line @typescript-eslint/no-explicit-any buildProduct(item) { const product = { image: item.Images.Primary.Large.URL, title: item.ItemInfo.Title.DisplayValue, url: item.DetailPageURL, prime: false, price: -1, timestamp: Date.now(), savings: 0 }; // Get the first offer only if (item.Offers && item.Offers.Listings && item.Offers.Listings.length > 0) { product.price = item.Offers.Listings[0].Price.DisplayAmount; product.prime = item.Offers.Listings[0].DeliveryInfo.IsPrimeEligible; // If savings exists if (item.Offers.Listings[0].Price.Savings) { product.savings = item.Offers.Listings[0].Price.Savings.Percentage; } } else { this.log.warn('No offer found for : ' + item.ASIN); } return product; } } exports.Paapi = Paapi; //# sourceMappingURL=Paapi.js.map