UNPKG

@apihawk/billia-sdk

Version:

The ApiHawk Billia SDK

77 lines (76 loc) 3.44 kB
"use strict"; var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { 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) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; Object.defineProperty(exports, "__esModule", { value: true }); const billia_sdk_service_base_1 = require("../lib/billia-sdk-service-base"); exports.SEARCH_RESOURCES = [ 'database[order]', 'database[order-purchase]', 'customer[product]', 'document[to-resource]', 'billing[product]' ]; class BilliaSDKSearch extends billia_sdk_service_base_1.BilliaSDKServiceBase { find(session, searchParams) { return __awaiter(this, void 0, void 0, function* () { if (typeof searchParams.limit === 'undefined') { searchParams.limit = 10; } if (typeof searchParams === 'undefined' || !searchParams.resource) { searchParams.resource = exports.SEARCH_RESOURCES; } const defaultParams = { q: '', limit: 10, resource: exports.SEARCH_RESOURCES }; const query = Object.assign({}, defaultParams, searchParams); const elasticSearchResults = yield this.api.call({ url: `/search/find`, method: 'GET', query, session }); /** * The UI requires the Category ID to be present in the search results * for customer products and customer product options in order to construct * the front-end path to the related pages. */ const customerProductResults = elasticSearchResults.filter(this.isCustomerProduct); const restResults = elasticSearchResults.filter((r) => !this.isCustomerProduct(r)); // fetch the product details for each customer product const customerProductsWithCategoryId = Promise.all(customerProductResults.map((searchResult) => this.getProductDetails(session, searchResult._source.product_id).then((product) => { searchResult._source.product = product; return searchResult; }))); const [elastic, customerProducts] = yield Promise.all([ restResults, customerProductsWithCategoryId ]); return [...elastic, ...customerProducts].sort(this.sortByRelevance); }); } getProductDetails(session, productId) { return __awaiter(this, void 0, void 0, function* () { const product = yield this.api.call({ url: `/billing/product/${productId}`, method: 'GET', session }); return product; }); } isCustomerProduct(searchResult) { return searchResult._index === 'customer[product]'; } sortByRelevance(result1, result2) { return result2._score - result1._score; } } exports.BilliaSDKSearch = BilliaSDKSearch;