@contentstack/utils
Version:
Contentstack utilities for Javascript
70 lines • 2.91 kB
JavaScript
import regionsData from './assets/regions.json';
/**
* Returns the Contentstack API endpoint(s) for a given region and optional service.
* Region can be an ID (e.g. `'us'`, `'eu'`) or an alias. Throws if the region is
* invalid or empty.
*
* @param region - Region ID or alias (e.g. `'us'`, `'eu'`). Default: `'us'`.
* @param service - Optional service name to return a single endpoint (e.g. `'delivery'`). If empty, returns all endpoints for the region.
* @param omitHttps - If true, strips the `https://` prefix from the returned URL(s). Default: false.
* @returns A single endpoint URL string if `service` is provided, otherwise the full endpoints object for the region.
* @throws Error if region is empty, invalid, or if the requested service is not found.
*/
export function getContentstackEndpoint(region, service, omitHttps) {
if (region === void 0) { region = 'us'; }
if (service === void 0) { service = ''; }
if (omitHttps === void 0) { omitHttps = false; }
// Validate empty region before any processing
if (region === '') {
throw new Error('Empty region provided. Please put valid region.');
}
var regions = regionsData;
// Normalize the region input
var normalizedRegion = region.toLowerCase().trim() || 'us';
// Check if regions data is malformed
if (!Array.isArray(regions.regions)) {
throw new Error('Invalid Regions file. Please install the SDK again to fix this issue.');
}
// Find the region by ID or alias
var regionData = findRegionByIDOrAlias(regions.regions, normalizedRegion);
if (!regionData) {
throw new Error("Invalid region: ".concat(region));
}
// Get the endpoint(s)
if (service) {
// Return specific service endpoint
var endpoint = regionData.endpoints[service];
if (!endpoint) {
throw new Error("Service \"".concat(service, "\" not found for region \"").concat(regionData.id, "\""));
}
return omitHttps ? stripHttps(endpoint) : endpoint;
}
else {
return omitHttps ? stripHttps(regionData.endpoints) : regionData.endpoints;
}
}
function findRegionByIDOrAlias(regions, regionInput) {
// First try to find by exact ID match
var region = regions.find(function (r) { return r.id === regionInput; });
if (region) {
return region;
}
// Then try to find by alias
region = regions.find(function (r) {
return r.alias.some(function (alias) { return alias.toLowerCase() === regionInput.toLowerCase(); });
});
return region || null;
}
function stripHttps(endpoint) {
if (typeof endpoint === 'string') {
return endpoint.replace(/^https?:\/\//, '');
}
else {
var result = {};
for (var key in endpoint) {
result[key] = stripHttps(endpoint[key]);
}
return result;
}
}
//# sourceMappingURL=endpoints.js.map