UNPKG

@flike/recommend

Version:

Wrapper for the Flike Recommendation API.

272 lines (271 loc) 12 kB
"use strict"; var __assign = (this && this.__assign) || function () { __assign = Object.assign || function(t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; } return t; }; return __assign.apply(this, arguments); }; 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 __generator = (this && this.__generator) || function (thisArg, body) { var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; function verb(n) { return function (v) { return step([n, v]); }; } function step(op) { if (f) throw new TypeError("Generator is already executing."); while (_) try { if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; if (y = 0, t) op = [op[0] & 2, t.value]; switch (op[0]) { case 0: case 1: t = op; break; case 4: _.label++; return { value: op[1], done: false }; case 5: _.label++; y = op[1]; op = [0]; continue; case 7: op = _.ops.pop(); _.trys.pop(); continue; default: if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } if (t[2]) _.ops.pop(); _.trys.pop(); continue; } op = body.call(thisArg, _); } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } }; Object.defineProperty(exports, "__esModule", { value: true }); exports.Recommender = exports.BatchRecommendationsJob = void 0; var axios = require("axios").default; var parseApiError = function (e) { if (e.response && [400, 401, 403].includes(e.response.status)) { var res = e.response.data; return { error: res.error, statusCode: e.response.status, detail: res.detail || undefined, hint: res.hint || undefined, }; } else { return { error: "Unknown", hint: e.message, }; } }; var BatchRecommendationsJob = /** @class */ (function () { /** @internal */ function BatchRecommendationsJob(recommender, creationResponse) { this.recommender = recommender; this.jobId = creationResponse.jobId; this.numUsers = creationResponse.numUsers; this.submittedAt = new Date(creationResponse.submittedAt); this.status = creationResponse.status; this.inputsFile = creationResponse.inputsFile; } /** * Update the job's execution status. * * Updates the job in-place. * * @returns A reference to the job itself * * @throws FlikeError when information about the job is not available. * */ BatchRecommendationsJob.prototype.update_status = function () { return __awaiter(this, void 0, void 0, function () { var res; return __generator(this, function (_a) { switch (_a.label) { case 0: return [4 /*yield*/, this.recommender.batch_recommend_query(this.jobId)]; case 1: res = _a.sent(); this.status = res.status; this.completedAt = res.status === "completed" ? new Date(res.completedAt) : undefined; this.resultsFile = res.status === "completed" ? res.resultsFile : undefined; return [2 /*return*/, this]; } }); }); }; /** * Poll until the job completes. * * It is strongly recommended to instead use the webhook callback parameter * when creating the job. * * @param interval Interval in seconds between polling the server for status changes (default: 60). * * @throws FlikeError when information about the job is not available. */ BatchRecommendationsJob.prototype.poll = function (interval) { var _this = this; if (interval === void 0) { interval = 60; } return new Promise(function (resolve) { var poller = setInterval(function () { return __awaiter(_this, void 0, void 0, function () { var stat; return __generator(this, function (_a) { switch (_a.label) { case 0: return [4 /*yield*/, this.update_status()]; case 1: stat = _a.sent(); if (stat.status === "completed") { clearInterval(poller); resolve(stat); } return [2 /*return*/]; } }); }); }, interval * 1000); }); }; return BatchRecommendationsJob; }()); exports.BatchRecommendationsJob = BatchRecommendationsJob; /** * Flike Recommender lets you easily recommend content items to users based on their interactions. */ var Recommender = /** @class */ (function () { /** * * * @param api_key Your API key. * @param server_url (only used for internal testing) * @param version Version of the API to use. Defaults to the most current version. */ function Recommender(api_key, server_url, version) { /** @internal */ this.server_url = "https://api.flike.app"; /** @internal */ this.version = "v0"; this.api_key = api_key; this.server_url = server_url !== null && server_url !== void 0 ? server_url : this.server_url; this.version = version !== null && version !== void 0 ? version : "v0"; this.axiosInstance = axios.create({ baseURL: "".concat(this.server_url, "/").concat(this.version, "/recommender/"), timeout: 60000, headers: { "x-api-key": api_key, "Content-Type": "application/json", }, }); } /** * Validates the connectivity to the API. * * @returns Resolves to `true` if the connection is successful, `false` otherwise. */ Recommender.prototype.validate = function () { return __awaiter(this, void 0, void 0, function () { return __generator(this, function (_a) { return [2 /*return*/, this.axiosInstance .get("status") .then(function (res) { return res.status === 200; }) .catch(function (e) { return false; })]; }); }); }; /** * Get an array of content items that a user is probable to consume/buy/subscribe/like or similar. * Recommendations are sorted by descending probability of a user 'liking' them. * * @param userId The unique identifier of the user. * @param numResults Number of content items that should be suggested. * @returns Resolves to a `RecommendationsResponse` if successful. Otherwise, it will throw an exception. * * @throws FlikeError when the recommendation fails. */ Recommender.prototype.recommend = function (userId, numResults, context) { return __awaiter(this, void 0, void 0, function () { return __generator(this, function (_a) { return [2 /*return*/, this.axiosInstance .post("recommend", { userId: userId, numResults: numResults, context: context, }) .then(function (res) { return ({ items: res.data.items, correlationId: res.data.correlationId, }); }) .catch(function (e) { throw parseApiError(e); })]; }); }); }; /** * Create a new batch recommendation job for a large quantity of users. * * This starts a long-running computation whose status you can check with the * {@link batch_recommend_query} method. * * @param numResults Number of results to compute per user. * @param options: Optional settings for the batch job (see {@link BatchRecommendOptions}). * @returns Resolves to a `BatchRecommendationsJob` if successful. Otherwise, throws an exception. * * @throws FlikeError when the job cannot be created. */ Recommender.prototype.batch_recommend = function (numResults, options) { return __awaiter(this, void 0, void 0, function () { var response; return __generator(this, function (_a) { switch (_a.label) { case 0: return [4 /*yield*/, this.axiosInstance .post("batch-recommend", __assign({ numResults: numResults }, options)) .then(function (res) { return res.data; }) .catch(function (e) { throw parseApiError(e); })]; case 1: response = _a.sent(); return [2 /*return*/, new BatchRecommendationsJob(this, response)]; } }); }); }; /** * Check the status of a batch recommendation job. * * The job must have previously been created using {@link batch_recommend}. * * Note that instead of polling, you can pass a webhook URL to {@link * batch_recommend}. This webhook will be invoked whenever the job status * changes to receive a POST request with the `BatchRecommendationsResponse` * as payload. * * @see {@link batch_recommend} * @param jobId The UUID of the job to query. * @returns Resolves to a `BatchRecommendationsResponse` if successful. Otherwise, throws an exception. * * @throws FlikeError when information about the job is not available. */ Recommender.prototype.batch_recommend_query = function (jobId) { return __awaiter(this, void 0, void 0, function () { return __generator(this, function (_a) { return [2 /*return*/, this.axiosInstance .get("batch-recommend/" + jobId) .then(function (res) { return res.data; }) .catch(function (e) { throw parseApiError(e); })]; }); }); }; return Recommender; }()); exports.Recommender = Recommender;