amazon-modern-widgets
Version:
Amazon Modern Widgets for Amazon affiliate websites based on Amazon PAAPI v5
160 lines • 6.2 kB
JavaScript
;
/**
* API Implementation.
* ----------------------------------------------
* Amazon Modern Widgets (AMW).
*
* @author : Ludovic Toinel <ludovic@toinel.com>
* @src : https://github.com/ltoinel/amw
*/
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.AmwApi = void 0;
// Lets import our required libraries
const config_1 = __importDefault(require("config"));
const path_1 = __importDefault(require("path"));
const Paapi_1 = require("./Paapi");
const ConfigLog4j_1 = require("../utils/ConfigLog4j");
/**
* API Implementation.
*/
class AmwApi {
/**
* Main AmwServer constructor.
*/
constructor(cache) {
this.ttl = config_1.default.get('Redis.expire');
// Initialize the logger.
this.log = (0, ConfigLog4j_1.getLogger)("AmwApi");
// The cache to optimize the API calls to Amazon.
this.cache = cache;
// Initialize the Paapi client.
this.paapi = new Paapi_1.Paapi();
}
;
/**
* Set the API Search endpoint.
*
* @param req The request object.
* @param res The response object.
*/
setProductEndpoint(req, res) {
return __awaiter(this, void 0, void 0, function* () {
var _a;
// Log the call to the API
const ip = ((_a = req.headers['x-forwarded-for']) === null || _a === void 0 ? void 0 : _a.split(',')[0].trim()) || req.ip;
this.log.info(`GET /product | id=${req.query.id} | keyword=${req.query.keyword} | IP=${ip} | Referer=${req.get('referer')}`);
// Search a product by ID
if (req.query.id) {
var productFound = yield this.findInCache(req.query.id, req, res);
if (!productFound) {
// We get the Item information on Amazon API
this.paapi.getItemApi(req.query.id).then(product => this.returnResponse(req.query.id, product, req, res, true));
}
// Search a product by keyword
}
else if (req.query.keyword) {
var productFound = yield this.findInCache(req.query.keyword, req, res);
if (!productFound) {
// We search the Item information on Amazon API
this.paapi.searchItemApi(req.query.keyword).then(product => this.returnResponse(req.query.keyword, product, req, res, true));
}
}
});
}
/**
* Return the response about the product.
*
* @param key The key to find in the cache.
* @param product The product to return.
* @param req The request object.
* @param res The response object.
* @returns The product
*/
returnResponse(key, product, req, res, saveInCache) {
var _a;
// We save in cache if the product has been found or not.
if (saveInCache) {
this.saveInCache(key, product);
}
// We return the result only if it has been found
if (product !== undefined && product !== null) {
res.json(product);
}
else {
// We log that the product has not been found
const identifier = (_a = req.query.id) !== null && _a !== void 0 ? _a : req.query.keyword;
this.log.info(`Product not found in Amazon : ${identifier}`);
res.status(404).json("Product Not found");
}
return;
}
/**
* Set the API Card endpoint.
*
* @param req The request object.
* @param res The response object.
*/
setCardEndpoint(req, res) {
res.sendFile(path_1.default.join(AmwApi.PROJECT_DIR + '/resources/html/card.html'));
}
/**
* Set the Test Page endpoint.
*
* @param req The request object.
* @param res The response object.
*/
setRootEndpoint(req, res) {
res.sendFile(path_1.default.join(AmwApi.PROJECT_DIR + '/resources/html/home.html'));
}
/**
* Find the product in the cache.
*
* @param key The key to find in the cache.
* @param req The request object.
* @param res The response object.
* @returns True if the product has been found in the cache. False otherwise.
*/
findInCache(key, req, res) {
return __awaiter(this, void 0, void 0, function* () {
if (this.cache !== undefined) {
const cachedData = yield this.cache.get(key);
if (cachedData) {
this.log.info(`Product found in cache : ${key}`);
this.returnResponse(key, JSON.parse(cachedData), req, res, false);
return true;
}
this.log.info(`Product not found in cache : ${key}`);
}
return false;
});
}
/**
* Save the product in the cache.
*
* @param key The key to save in the cache.
* @param product The product to save.
*/
saveInCache(key, product) {
// We save the response if the cache is enabled
if (this.cache !== undefined) {
this.log.info(`Saving product in cache : ${key}`);
this.cache.set(key, JSON.stringify(product), 'EX', this.ttl);
}
}
}
exports.AmwApi = AmwApi;
// Static attributes
AmwApi.PROJECT_DIR = config_1.default.get('Server.projectDir');
//# sourceMappingURL=AmwApi.js.map