UNPKG

@botonic/plugin-contentful

Version:

Botonic Plugin Contentful is one of the **[available](https://github.com/hubtype/botonic/tree/master/packages)** plugins for Botonic. **[Contentful](http://www.contentful.com)** is a CMS (Content Management System) which manages contents of a great variet

67 lines 2.81 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.MultiEnvironmentFactory = exports.multiEnvironmentFactory = void 0; const cms_multilocale_1 = require("../cms/cms-multilocale"); const util_1 = require("../util"); const cms_contentful_1 = require("./cms-contentful"); /** * Set it to ContentfulOptions.contentfulFactory to connect to * different Contentful environments depending on the Context's Locale * for each call to CMS */ function multiEnvironmentFactory(environmentByLocale) { const multiFactory = new MultiEnvironmentFactory(environmentByLocale); return contOptions => new cms_multilocale_1.MultiContextCms((ctx) => multiFactory.get(contOptions, ctx)); } exports.multiEnvironmentFactory = multiEnvironmentFactory; /** * Creates a different Contentful environments for each configured Locale. * When the call to CMS does not specify a locale, it uses the credentials from * ContentfulOptions and it informs through the logger */ class MultiEnvironmentFactory { constructor(environmentByLocale, contentfulFactory = (o) => new cms_contentful_1.Contentful(o), logger = console.error) { this.environmentByLocale = environmentByLocale; this.contentfulFactory = contentfulFactory; this.logger = logger; this.cache = new Map(); } get(contOptions, ctx) { const credentials = this.getCredentials(ctx); if (!credentials) { if (!this.defaultCms) { this.defaultCms = this.contentfulFactory(contOptions); } return this.defaultCms; } const locale = ctx.locale; let cms = this.cache.get(locale); if (!cms) { const opts = (0, util_1.shallowClone)(contOptions); opts.spaceId = credentials.spaceId; opts.environment = credentials.environment; opts.accessToken = credentials.accessToken; cms = this.contentfulFactory(opts); this.cache.set(locale, cms); } return cms; } getCredentials(ctx) { if (!ctx) { this.logger('MultiLocaleCmsFactory called with no context. Using default credentials'); return undefined; } if (!ctx.locale) { this.logger('MultiLocaleCmsFactory called with no context locale. Using default credentials'); return undefined; } const credentials = this.environmentByLocale[ctx.locale]; if (!credentials) { this.logger(`MultiLocaleCmsFactory has no credentials for locale '${ctx.locale}'. Trying with default credentials`); return undefined; } return credentials; } } exports.MultiEnvironmentFactory = MultiEnvironmentFactory; //# sourceMappingURL=multi-environment.js.map