@sitecore-jss/sitecore-jss
Version:
This module is provided as a part of Sitecore JavaScript Rendering SDK. It contains the core JSS APIs (layout service) and utilities.
65 lines (64 loc) • 2.99 kB
JavaScript
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());
});
};
import { NativeDataFetcher } from '../native-fetcher';
import { fetchData } from '../data-fetcher';
import { DictionaryServiceBase } from './dictionary-service';
import debug from '../debug';
/**
* Fetch dictionary data using the Sitecore Dictionary Service REST API.
* Uses NativeDataFetcher as the default data fetcher (@see NativeDataFetcher).
* @augments DictionaryServiceBase
*/
export class RestDictionaryService extends DictionaryServiceBase {
constructor(options) {
super(options);
this.options = options;
}
/**
* Provides default @see NativeDataFetcher data fetcher
*/
get defaultFetcher() {
const dataFetcher = new NativeDataFetcher({
debugger: debug.dictionary,
// CORS issue: Sitecore provides 'Access-Control-Allow-Origin' as wildcard '*', so we can't include credentials for the dictionary service
credentials: 'omit',
});
return (url) => dataFetcher.fetch(url);
}
/**
* Fetch dictionary data for a language.
* @param {string} language the language to be used to fetch the dictionary
* @returns {Promise<DictionaryPhrases>} dictionary phrases
*/
fetchDictionaryData(language) {
return __awaiter(this, void 0, void 0, function* () {
const endpoint = this.getUrl(language);
const cachedValue = this.getCacheValue(endpoint);
if (cachedValue) {
debug.dictionary('using cached dictionary data for %s %s', language, this.options.siteName);
return cachedValue;
}
debug.dictionary('fetching dictionary data for %s %s', language, this.options.siteName);
const fetcher = this.options.dataFetcher || this.defaultFetcher;
const response = yield fetchData(endpoint, fetcher, {
sc_apikey: this.options.apiKey,
});
return this.setCacheValue(endpoint, response.phrases);
});
}
/**
* Generate dictionary service url
* @param {string} language the language to be used to fetch the dictionary
* @returns {string} dictionary service url
*/
getUrl(language) {
return `${this.options.apiHost}/sitecore/api/jss/dictionary/${this.options.siteName}/${language}`;
}
}