UNPKG

@botonic/plugin-contentful

Version:

## What Does This Plugin Do?

62 lines 2.5 kB
import { MultiContextCms } from '../cms/cms-multilocale'; import { shallowClone } from '../util'; import { Contentful } from './cms-contentful'; /** * Set it to ContentfulOptions.contentfulFactory to connect to * different Contentful environments depending on the Context's Locale * for each call to CMS */ export function multiEnvironmentFactory(environmentByLocale) { const multiFactory = new MultiEnvironmentFactory(environmentByLocale); return contOptions => new MultiContextCms((ctx) => multiFactory.get(contOptions, ctx)); } /** * 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 */ export class MultiEnvironmentFactory { constructor(environmentByLocale, contentfulFactory = (o) => new 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 = 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; } } //# sourceMappingURL=multi-environment.js.map