"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.getServiceObjectTransformFactory = void 0;
var _lruCache = _interopRequireDefault(require("lru-cache"));
var _objectVersioning = require("@kbn/object-versioning");
/*
 * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
 * or more contributor license agreements. Licensed under the Elastic License
 * 2.0 and the Server Side Public License, v 1; you may not use this file except
 * in compliance with, at your election, the Elastic License 2.0 or the Server
 * Side Public License, v 1.
 */

/**
 * We keep a cache of compiled service definition to avoid unnecessary recompile on every request.
 */
const compiledCache = new _lruCache.default({
  max: 50
});

/**
 * Wrap the "getContentManagmentServicesTransforms()" handler from the @kbn/object-versioning package
 * to be able to cache the service definitions compilations so we can reuse them accross request as the
 * services definitions won't change until a new Elastic version is released. In which case the cache
 * will be cleared.
 *
 * @param contentTypeId The content type id for the service definition
 * @returns A "getContentManagmentServicesTransforms()"
 */
const getServiceObjectTransformFactory = (contentTypeId, _requestVersion, {
  cacheEnabled = true
} = {}) => (definitions, requestVersionOverride) => {
  const requestVersion = requestVersionOverride !== null && requestVersionOverride !== void 0 ? requestVersionOverride : _requestVersion;
  if (cacheEnabled) {
    const compiledFromCache = compiledCache.get(contentTypeId);
    if (compiledFromCache) {
      return (0, _objectVersioning.getContentManagmentServicesTransforms)(definitions, requestVersion, compiledFromCache);
    }
  }
  const compiled = (0, _objectVersioning.compileServiceDefinitions)(definitions);
  if (cacheEnabled) {
    compiledCache.set(contentTypeId, compiled);
  }
  return (0, _objectVersioning.getContentManagmentServicesTransforms)(definitions, requestVersion, compiled);
};
exports.getServiceObjectTransformFactory = getServiceObjectTransformFactory;