UNPKG

@jss-rule-engine/edge

Version:

202 lines (201 loc) 11.8 kB
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 = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype); return g.next = verb(0), g["throw"] = verb(1), g["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 (g && (g = 0, op[0] && (_ = 0)), _) 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 }; } }; import { GraphQLRequestClient } from '@sitecore-jss/sitecore-jss/graphql'; import { debug } from '@sitecore-jss/sitecore-jss'; import { isTimeoutError } from '@sitecore-jss/sitecore-jss/utils'; import { MemoryCacheClient } from './cache-client'; import { JssRuleEngine } from '@jss-rule-engine/core'; import { registerNextJS } from '../../rule-engine/ruleEngineProvider'; import { getScPersonalizedVariantIds } from '../../lib/personalizationUtils'; var GraphQLSCPersonalizeService = /** @class */ (function () { /** * Fetch personalize data using the Sitecore GraphQL endpoint. * @param {GraphQLPersonalizeServiceConfig} config */ function GraphQLSCPersonalizeService(config) { this.config = config; this.config.timeout = config.timeout || 400; this.graphQLClient = this.getGraphQLClient(); this.cache = this.getCacheClient(); } Object.defineProperty(GraphQLSCPersonalizeService.prototype, "query", { get: function () { return /* GraphQL */ "\n query($siteName: String!, $language: String!, $itemPath: String!) {\n layout(site: $siteName, routePath: $itemPath, language: $language) {\n item {\n id\n version\n personalizationRule:field(name:\"PersonalizationRules\"){\n value\n },\n personalizeOnEdge:field(name:\"PersonalizeOnEdge\"){\n value\n }\n }\n }\n }\n "; }, enumerable: false, configurable: true }); GraphQLSCPersonalizeService.prototype.setPersonalizeContext = function (context) { this.personalizeContext = context; }; /** * Get personalize information for a route * @param {string} itemPath page route * @param {string} language language * @param {string} siteName site name * @returns {Promise<PersonalizeInfo | undefined>} the personalize information or undefined (if itemPath / language not found) */ GraphQLSCPersonalizeService.prototype.getPersonalizeInfo = function (itemPath, language, siteName) { return __awaiter(this, void 0, void 0, function () { var cacheKey, data, error_1, variantIds, activeVariantid, personalizeOnEdge, ruleEngineInstance, ruleXml, ruleEngineContext, result; var _a, _b, _c, _d, _e, _f; return __generator(this, function (_g) { switch (_g.label) { case 0: debug.personalize('fetching personalize info for %s %s %s', siteName, itemPath, language); console.log('fetching personalize info for %s %s %s', siteName, itemPath, language); cacheKey = this.getCacheKey(itemPath, language, siteName); data = this.cache.getCacheValue(cacheKey); if (!!data) return [3 /*break*/, 5]; _g.label = 1; case 1: _g.trys.push([1, 3, , 4]); return [4 /*yield*/, this.graphQLClient.request(this.query, { siteName: siteName, itemPath: itemPath, language: language, })]; case 2: //console.log('personalize info cache is empty - making graphQL call.', this.query); data = _g.sent(); this.cache.setCacheValue(cacheKey, data); return [3 /*break*/, 4]; case 3: error_1 = _g.sent(); if (isTimeoutError(error_1)) { return [2 /*return*/, undefined]; } throw error_1; case 4: return [3 /*break*/, 5]; case 5: variantIds = null; activeVariantid = null; personalizeOnEdge = (_c = (_b = (_a = data.layout) === null || _a === void 0 ? void 0 : _a.item) === null || _b === void 0 ? void 0 : _b.personalizeOnEdge) === null || _c === void 0 ? void 0 : _c.value; if (!(personalizeOnEdge == "1")) return [3 /*break*/, 8]; console.log("Personalizing on edge", personalizeOnEdge); ruleEngineInstance = new JssRuleEngine(); if (!ruleEngineInstance) return [3 /*break*/, 7]; console.log('Registering NextJS commands for rule engine'); registerNextJS(ruleEngineInstance); ruleXml = (_f = (_e = (_d = data.layout) === null || _d === void 0 ? void 0 : _d.item) === null || _e === void 0 ? void 0 : _e.personalizationRule) === null || _f === void 0 ? void 0 : _f.value; //console.log("Rule xml", ruleXml, ruleXml.replace) if (this.personalizeContext) { console.log('Current url - ', this.personalizeContext.url); ruleEngineInstance.setRequestContext({ url: this.personalizeContext.url }); } ruleEngineContext = ruleEngineInstance.getRuleEngineContext(); console.log('Parsing rule'); return [4 /*yield*/, ruleEngineInstance.parseAndRunRule(ruleXml, ruleEngineContext)]; case 6: _g.sent(); if (ruleEngineContext.ruleExecutionResult && ruleEngineContext.ruleExecutionResult.parsedRule) { console.log('Rule parsed - getting variant ids', ruleEngineContext.ruleExecutionResult); activeVariantid = this.getActiveVariantId(ruleEngineContext.ruleExecutionResult); console.log('Active variant id - ', activeVariantid); variantIds = getScPersonalizedVariantIds(ruleEngineContext.ruleExecutionResult.parsedRule); console.log('Variant ids - ', variantIds); } _g.label = 7; case 7: return [3 /*break*/, 9]; case 8: console.log('Edge personalization is disabled for this item in Sitecore.'); _g.label = 9; case 9: result = { contentId: itemPath, variantIds: variantIds, activeVariantid: activeVariantid }; console.log('====='); return [2 /*return*/, result]; } }); }); }; GraphQLSCPersonalizeService.prototype.getActiveVariantId = function (ruleExecutionResults) { if (!(ruleExecutionResults === null || ruleExecutionResults === void 0 ? void 0 : ruleExecutionResults.ruleResults)) { return null; } var ruleResults = ruleExecutionResults.ruleResults; console.log('Getting active variant for ', ruleResults); var result = ""; var isAnyRuleTrue = false; if (ruleResults && ruleResults.forEach) { ruleResults.forEach(function (ruleRes) { result += ruleRes ? "1" : "0"; if (ruleRes) isAnyRuleTrue = true; }); } console.log("Active variant result: ", isAnyRuleTrue, result); return isAnyRuleTrue ? result : null; }; /** * Gets cache client implementation * Override this method if custom cache needs to be used * @returns CacheClient instance */ GraphQLSCPersonalizeService.prototype.getCacheClient = function () { var _a, _b; return new MemoryCacheClient({ cacheEnabled: (_a = this.config.cacheEnabled) !== null && _a !== void 0 ? _a : true, cacheTimeout: (_b = this.config.cacheTimeout) !== null && _b !== void 0 ? _b : 10, }); }; GraphQLSCPersonalizeService.prototype.getCacheKey = function (itemPath, language, siteName) { return "".concat(siteName, "-").concat(itemPath, "-").concat(language); }; /** * Gets a GraphQL client that can make requests to the API. Uses graphql-request as the default * library for fetching graphql data (@see GraphQLRequestClient). Override this method if you * want to use something else. * @returns {GraphQLClient} implementation */ GraphQLSCPersonalizeService.prototype.getGraphQLClient = function () { return new GraphQLRequestClient(this.config.endpoint, { apiKey: this.config.apiKey, debugger: debug.personalize, fetch: this.config.fetch, timeout: this.config.timeout, }); }; return GraphQLSCPersonalizeService; }()); export { GraphQLSCPersonalizeService };