UNPKG

@kwiz/common

Version:

KWIZ common utilities and helpers for M365 platform

176 lines 8.83 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.CONTENT_TYPES_SELECT_WITH_FIELDS = exports.CONTENT_TYPES_SELECT = exports.WEB_SELECT = exports.LIST_EXPAND = exports.LIST_SELECT = void 0; exports.hasGlobalContext = hasGlobalContext; exports.GetFileSiteUrl = GetFileSiteUrl; exports.GetSiteUrl = GetSiteUrl; exports.GetSiteUrlLocally = GetSiteUrlLocally; exports.GetRestBaseUrl = GetRestBaseUrl; exports.DecodeFieldValuesAsTextKey = DecodeFieldValuesAsTextKey; exports.EncodeFieldValuesAsTextKey = EncodeFieldValuesAsTextKey; exports.DecodeFieldValuesAsText = DecodeFieldValuesAsText; exports.DecodeFieldValuesForEdit = DecodeFieldValuesForEdit; exports.GetFieldNameFromRawValues = GetFieldNameFromRawValues; exports.getFieldNameForUpdate = getFieldNameForUpdate; exports.__isIRestError = __isIRestError; exports.__getSPRestErrorData = __getSPRestErrorData; exports.getResourceNonce = getResourceNonce; const collections_base_1 = require("../../helpers/collections.base"); const json_1 = require("../../helpers/json"); const strings_1 = require("../../helpers/strings"); const typecheckers_1 = require("../../helpers/typecheckers"); const url_1 = require("../../helpers/url"); const consolelogger_1 = require("../consolelogger"); const localstoragecache_1 = require("../localstoragecache"); const rest_1 = require("../rest"); const web_1 = require("./web"); const logger = consolelogger_1.ConsoleLogger.get("utils/sharepoint.rest/common"); exports.LIST_SELECT = `ListExperienceOptions,EffectiveBasePermissions,Description,Title,EnableAttachments,EnableModeration,BaseTemplate,BaseType,Id,Hidden,IsApplicationList,IsPrivate,IsCatalog,ImageUrl,ItemCount,ParentWebUrl,EntityTypeName,DefaultViewUrl,ParentWeb/Id,ParentWeb/Title`; exports.LIST_EXPAND = `ParentWeb/Id,ParentWeb/Title`; exports.WEB_SELECT = "Title,ServerRelativeUrl,Id,WebTemplate,Description,SiteLogoUrl"; exports.CONTENT_TYPES_SELECT = "Name,Description,StringId,Group,Hidden,ReadOnly,NewFormUrl,DisplayFormUrl,EditFormUrl,Sealed,MobileDisplayFormUrl,MobileNewFormUrl,MobileEditFormUrl,NewFormTemplateName,DisplayFormTemplateName,EditFormTemplateName"; exports.CONTENT_TYPES_SELECT_WITH_FIELDS = `${exports.CONTENT_TYPES_SELECT},Fields`; function hasGlobalContext() { //_spPageContextInfo.webServerRelativeUrl can be empty string return typeof (_spPageContextInfo) !== "undefined" && (0, typecheckers_1.isString)(_spPageContextInfo.webServerRelativeUrl); } function GetFileSiteUrl(fileUrl) { let siteUrl; let urlParts = fileUrl.split('/'); if (urlParts[urlParts.length - 1].indexOf('.') > 0) //file name urlParts.pop(); //file name let key = "GetSiteUrl|" + urlParts.join("/").toLowerCase(); siteUrl = (0, localstoragecache_1.getCacheItem)(key); if ((0, typecheckers_1.isNullOrUndefined)(siteUrl)) { while (!(0, typecheckers_1.isValidGuid)((0, web_1.GetWebIdSync)(urlParts.join('/')))) urlParts.pop(); siteUrl = (0, url_1.normalizeUrl)(urlParts.join('/')); (0, localstoragecache_1.setCacheItem)(key, siteUrl, rest_1.mediumLocalCache.localStorageExpiration); //keep for 15 minutes } //must end with / otherwise root sites will return "" and we will think there is no site url. return (0, url_1.makeServerRelativeUrl)((0, url_1.normalizeUrl)(siteUrl, true)); } /** gets a site URL or null, returns the current web URL or siteUrl as relative URL - end with / * If you send a guid - it will look for a site with that ID in the current context site collection */ function GetSiteUrl(siteUrlOrId) { if ((0, typecheckers_1.isValidGuid)(siteUrlOrId)) { if (hasGlobalContext() && (0, strings_1.normalizeGuid)(siteUrlOrId) === (0, strings_1.normalizeGuid)(_spPageContextInfo.webId)) { return (0, url_1.normalizeUrl)(_spPageContextInfo.webServerRelativeUrl, true); } const webInfo = (0, web_1.GetWebInfoSync)(null, siteUrlOrId); return (0, url_1.normalizeUrl)(webInfo.ServerRelativeUrl, true); } return GetSiteUrlLocally(siteUrlOrId); } /** gets a siteUrl locally (without making requests) (todo although currently GetFileSiteUrl does make requests...) */ function GetSiteUrlLocally(siteUrl) { if ((0, typecheckers_1.isNullOrUndefined)(siteUrl)) { if (hasGlobalContext()) { siteUrl = _spPageContextInfo.webServerRelativeUrl; if (_spPageContextInfo.isAppWeb) { //#1300 if in a classic app sub-site siteUrl = siteUrl.substring(0, siteUrl.lastIndexOf("/")); } } else { siteUrl = GetFileSiteUrl(window.location.pathname); } } //must end with / otherwise root sites will return "" and we will think there is no site url. return (0, url_1.makeServerRelativeUrl)((0, url_1.normalizeUrl)(siteUrl, true)); } /** gets a site url, returns its REST _api url */ function GetRestBaseUrl(siteUrl) { siteUrl = GetSiteUrlLocally(siteUrl); return siteUrl + '_api'; } /** Get the field internal name as you can find it in item.FieldValuesAsText[name] (Or FieldValuesForEdit) */ function DecodeFieldValuesAsTextKey(key) { return key.replace(/_x005f_/g, "_").replace('OData__', '_'); } /** Replaces _ with _x005f_, except OData_ at the start */ function EncodeFieldValuesAsTextKey(key) { return key.replace('OData_', '~').replace(/_/g, "_x005f_").replace('~', 'OData_'); } /** Gets REST FieldValuesAsText or FieldValuesForEdit and fix their column names so that you can get a field value by its internal name */ function DecodeFieldValuesAsText(FieldValuesAsText) { return DecodeFieldValuesForEdit(FieldValuesAsText); } /** Gets REST FieldValuesAsText or FieldValuesForEdit and fix their column names so that you can get a field value by its internal name */ function DecodeFieldValuesForEdit(FieldValuesForEdit) { let result = {}; Object.keys(FieldValuesForEdit).forEach(key => { result[DecodeFieldValuesAsTextKey(key)] = FieldValuesForEdit[key]; }); return result; } /** Get the field internal name as you can find it in the item[name] to get raw values */ function GetFieldNameFromRawValues(field, //ISSUE: 1250 options = { excludeIdFromName: false }) { let fieldName = field.InternalName; if (options.excludeIdFromName !== true && (field.TypeAsString === "User" || field.TypeAsString === "UserMulti" || field.TypeAsString === "Lookup" || field.TypeAsString === "LookupMulti" || field.InternalName === "ContentType")) { fieldName = fieldName += "Id"; } //issue 6698 fields that are too short will encode their first letter, and will start with _. this will add OData_ as a prefix in REST //Issue 336 _EndDate > OData__EndDate if (fieldName.startsWith('_')) { fieldName = "OData_" + fieldName; } return fieldName; } /** Get the field name to set on the item update REST request */ function getFieldNameForUpdate(field) { if (field.TypeAsString === "TaxonomyFieldTypeMulti") { //Updating multi taxonomy value is allowed as string to the associated hidden text field return field.HiddenMultiValueFieldName; } return GetFieldNameFromRawValues(field); } function __isIRestError(e) { let x = e; return !(0, typecheckers_1.isNullOrUndefined)(x) && !(0, typecheckers_1.isNullOrUndefined)(x.xhr) && (0, typecheckers_1.isString)(x.message); } /** extract the error message from a SharePoint REST failed request */ function __getSPRestErrorData(restError) { let code = "Unknown"; let errorMessage = "Unspecified error"; if (restError && restError.message) errorMessage = restError.message; if (restError && restError.xhr && !(0, typecheckers_1.isNullOrEmptyString)(restError.xhr.responseText)) { let errorData = (0, json_1.jsonParse)(restError.xhr.responseText); let error = errorData && errorData.error; if (!error && errorData) //in minimal rest - error is in "odata.error" error = errorData && errorData["odata.error"]; if (error) { if (error && error.message && error.message.value) errorMessage = error.message.value; if (error && error.code) code = error.code; } } logger.error(errorMessage); return { code: code, message: errorMessage }; } function getResourceNonce() { try { let scriptEles = Array.from(document.querySelectorAll("script[nonce]")); let scriptEle = (0, collections_base_1.firstOrNull)(scriptEles, (item) => { return item.nonce !== null; }); if (!(0, typecheckers_1.isNullOrUndefined)(scriptEle)) { return scriptEle.nonce; } } catch { } return ""; } //# sourceMappingURL=common.js.map