Skip to content

Instantly share code, notes, and snippets.

@zplume
Last active June 30, 2023 15:04
Show Gist options
  • Star 20 You must be signed in to star a gist
  • Fork 5 You must be signed in to fork a gist
  • Save zplume/1395dee6b8b2e38e5927 to your computer and use it in GitHub Desktop.
Save zplume/1395dee6b8b2e38e5927 to your computer and use it in GitHub Desktop.
SharePoint 2013 REST / JSOM / Utility functions (work in progress)
(function() {
var nsName = "LS"; // root namespace name
var ns = window[nsName]; // root namespace alias
var utils = ns.Utils; // utils alias
ns.SP = ns.SP || {};
ns.SP.JSOM = {
Data: {
Sites: {} // cache for Taxonomy terms JSON
},
Lists: {
getLists: function() {
// get lists for the current web
var ctx = SP.ClientContext.get_current(),
lists = ctx.get_web().get_lists();
ctx.load(lists);
return ns.SP.JSOM.executeQuery(ctx, lists, true);
},
getList: function(siteUrl, listTitle) {
// example usage
// ns.SP.JSOM.GetList("http://siteurl", "Site Assets")
// .then(function (list) {
// LogMsg(list.get_title());
// });
var ctx = siteUrl != _spPageContextInfo.webAbsoluteUrl ? new SP.ClientContext(siteUrl) : SP.ClientContext.get_current(),
list = ctx.get_web().get_lists().getByTitle(listTitle);
ctx.load(list);
return ns.SP.JSOM.executeQuery(ctx, list);
},
getListById: function(siteUrl, listId) {
// example usage
// ns.SP.JSOM.GetList("http://siteurl", "(guid)")
// .then(function (list) {
// LogMsg(list.get_title());
// });
var ctx = siteUrl != _spPageContextInfo.webAbsoluteUrl ? new SP.ClientContext(siteUrl) : SP.ClientContext.get_current(),
list = ctx.get_web().get_lists().getById(listId);
ctx.load(list);
return ns.SP.JSOM.executeQuery(ctx, list);
},
Items: {
getItemById: function(list, id) {
var ctx = list.get_context(),
item = list.getItemById(id);
ctx.load(item);
return ns.SP.JSOM.executeQuery(ctx, item);
},
getItems: function(list, caml) {
var ctx = list.get_context(),
camlQuery = new SP.CamlQuery();
camlQuery.set_viewXml(caml);
var items = list.getItems(camlQuery);
ctx.load(items);
return ns.SP.JSOM.executeQuery(ctx, items, true);
},
add: function(list, data) {
var ctx = list.get_context(),
itemCreateInfo = new SP.ListItemCreationInformation(),
newItem = list.addItem(itemCreateInfo);
jQuery.each(data, function(key, value) {
newItem.set_item(key, value);
});
newItem.update();
return ns.SP.JSOM.executeQuery(ctx, newItem);
},
update: function(list, id, data) {
var ctx = list.get_context();
function setData(item) {
jQuery.each(data, function(key, value) {
item.set_item(key, value);
});
item.update();
return ns.SP.JSOM.executeQuery(ctx, item);
}
return ns.SP.JSOM.Lists.Items.getItemById(list, id)
.then(setData);
},
delete: function(list, id) {
var ctx = list.get_context();
function deleteItem(item) {
item.deleteObject();
return ns.SP.JSOM.executeQuery(ctx);
}
return ns.SP.JSOM.Lists.Items.getItemById(list, id)
.then(deleteItem);
},
like: function(list, id, like) {
var ctx = list.get_context();
function setLike() {
var reputation = Microsoft.Office.Server.ReputationModel.Reputation;
reputation.setLike(ctx, list.get_id().toString(), id, like);
return ns.SP.JSOM.executeQuery(ctx);
}
return ns.SP.JSOM.loadReputationScripts()
.then(setLike);
},
rate: function(list, id, rating) {
var ctx = list.get_context();
function setRating() {
var reputation = Microsoft.Office.Server.ReputationModel.Reputation;
reputation.setRating(ctx, list.get_id().toString(), id, rating);
return ns.SP.JSOM.executeQuery(ctx);
}
return ns.SP.JSOM.loadReputationScripts()
.then(setRating);
},
UserField: {
contains: function(item, fieldName, user) {
var userField = item.get_fieldValues()[fieldName];
return userField !== null ?
jQuery.grep(userField, function(userValue, i) {
return userValue.get_lookupId() == user.get_id();
}).length > 0 : false;
},
add: function(item, fieldName, user) {
var userField = item.get_fieldValues()[fieldName],
fieldUserValue = new SP.FieldUserValue(),
data = {};
fieldUserValue.set_lookupId(user.get_id());
userField.push(fieldUserValue);
data[fieldName] = userField;
return ns.SP.JSOM.Lists.Items.update(item.get_parentList(), item.get_id(), data);
},
remove: function(item, fieldName, user) {
var userField = item.get_fieldValues()[fieldName],
users = userField !== null ? jQuery.grep(userField, function(userValue, i) {
return userValue.get_lookupId() !== user.get_id();
}) : null,
data = {};
data[fieldName] = users;
return ns.SP.JSOM.Lists.Items.update(item.get_parentList(), item.get_id(), data);
}
}
},
Fields: {
getFields: function(list, propertyArray) {
// example usage
// ns.SP.JSOM.Lists.GetList("http://siteurl", "Site Assets")
// .then(function (list) {
// return ns.SP.JSOM.Lists.GetFields(list, ["Title", "InternalName"]);
// }).then(function (data) {
// LogMsg(data);
// });
var ctx = list.get_context(),
fields = list.get_fields();
if (propertyArray)
ctx.load(fields, 'Include(' + propertyArray.join(', ') + ')');
else
ctx.load(fields);
return ns.SP.JSOM.executeQuery(ctx, fields, true);
},
getFieldByInternalName: function(fields, internalFieldName) {
// example usage
//ns.SP.JSOM.Lists.GetList("http://siteurl", "Documents")
// .then(ns.SP.JSOM.GetFields)
// .then(function (data) { return ns.SP.JSOM.Lists.GetFieldByInternalName(data, "Title"); })
// .done(LogMsg);
return jQuery.grep(fields, function(field, index) {
return field.get_internalName() == internalFieldName;
})[0];
}
}
},
Users: {
doesUserHavePermission: function(ctx, spPermissionKind) {
var web = ctx.get_web();
ctx.load(web);
ctx.load(web, 'EffectiveBasePermissions');
return ns.SP.JSOM.executeQuery(ctx)
.then(function() {
return web.get_effectiveBasePermissions().has(spPermissionKind);
});
},
getCurrent: function() {
var ctx = SP.ClientContext.get_current(),
user = ctx.get_web().get_currentUser();
ctx.load(user);
return ns.SP.JSOM.executeQuery(ctx, user);
}
},
// get metadata terms for a term group, in the context of the specified site collection
Taxonomy: {
Sites: {}, // JSOM cache for Taxonomy objects
getTerms: function(url, groupName) {
var ctx,
siteData = ns.SP.JSOM.Data.Sites[url] || {},
siteObjects = ns.SP.JSOM.Taxonomy.Sites[url] || {};
function getTermStores() {
ctx = new SP.ClientContext(url);
// load from sessionStorage if possible and return, or carry on and load from taxonomy term store...
var taxonomyJSONString = sessionStorage.getItem(nsName + ".SP.JSOM.Data.Sites[" + url + "]");
if (taxonomyJSONString !== null) {
siteData = JSON.parse(taxonomyJSONString);
if (siteData.TermGroups[groupName]) {
ns.SP.JSOM.Data.Sites[url] = siteData;
LogMsg("Terms loaded from sessionStorage.");
return jQuery.Deferred().reject().promise(); // don't continue the promise chain
}
}
// Cache TaxonomySession as a global variable to avoid uninitialized error when making multiple requests against the term store (i.e. when querying more than one group)
siteObjects.taxonomySession = siteObjects.taxonomySession || SP.Taxonomy.TaxonomySession.getTaxonomySession(ctx);
siteObjects.termStores = siteObjects.taxonomySession.get_termStores();
ctx.load(siteObjects.termStores);
return ns.SP.JSOM.executeQuery(ctx, siteObjects.termStores, true);
}
function getTermGroups(termStores) {
siteObjects.termStores = termStores;
siteObjects.termStore = siteObjects.termStores[0];
LogMsg("Retrieved term store '{0}'".format(siteObjects.termStore.get_name()));
siteObjects.termGroups = siteObjects.termStore.get_groups();
ctx.load(siteObjects.termGroups);
LogMsg("Loading term groups");
return ns.SP.JSOM.executeQuery(ctx, siteObjects.termGroups, true);
}
function getTermGroup(termGroups) {
siteObjects.termGroups = termGroups;
siteObjects.termGroup = jQuery.grep(siteObjects.termGroups, function(value, index) {
return value.get_name() == groupName;
})[0];
if (siteObjects.termGroup) {
LogMsg("Match '{0}' found, loading Term Group".format(siteObjects.termGroup.get_name()));
ctx.load(siteObjects.termGroup);
return ns.SP.JSOM.executeQuery(ctx);
} else {
LogMsg("Error: Term Group '{0}' not found".format(groupName));
return jQuery.Deferred().reject().promise(); // don't continue the promise chain
}
}
function getTermSets() {
siteData.TermGroups = siteData.TermGroups || {};
siteData.TermGroups[groupName] = {};
siteObjects.termSets = siteObjects.termGroup.get_termSets();
ctx.load(siteObjects.termSets);
LogMsg("Getting Term Sets for group '{0}'".format(groupName));
return ns.SP.JSOM.executeQuery(ctx, siteObjects.termSets, true);
}
function getAllTerms(termSets) {
siteObjects.termSets = termSets;
siteData.TermGroups[groupName].TermSets = siteData.TermGroups[groupName].TermSets || {};
var termSetsPromises = jQuery.map(siteObjects.termSets, function(termSet, i) {
return getTermsForTermSet(termSet); // load term set terms async
});
return jQuery.when.apply(jQuery, termSetsPromises) // when all terms are loaded
.then(function() {
ns.SP.JSOM.Data.Sites[url] = siteData;
ns.SP.JSOM.Taxonomy.Sites[url] = siteObjects;
return;
})
.done(function() {
LogMsg("Terms loaded.");
sessionStorage.setItem(nsName + ".SP.JSOM.Data.Sites[" + url + "]", JSON.stringify(siteData)); // cache in sessionStorage
LogMsg("Terms cached in sessionStorage.");
});
}
function getTermsForTermSet(termSet, termSetsPromises) {
var termSetName = termSet.get_name();
siteData.TermGroups[groupName].TermSets[termSetName] = {};
siteData.TermGroups[groupName].TermSets[termSetName].Terms = siteData.TermGroups[groupName].TermSets[termSetName].Terms || {};
LogMsg("Getting Terms for Term Set '{0}'".format(termSetName));
var terms = termSet.get_terms(),
termsGlobal = siteData.TermGroups[groupName].TermSets[termSetName].Terms;
return getTermsRecursive(terms, termsGlobal);
}
function getTermsRecursive(terms, termsGlobal) {
// populate global variable with terms and child terms recursively
ctx.load(terms);
return ns.SP.JSOM.executeQuery(ctx)
.then(function() {
return getTerms(terms, termsGlobal);
});
}
function getTerms(terms, termsGlobal) {
terms = ns.SP.JSOM.enumerableToArray(terms);
var childTermsPromises = jQuery.map(terms, function(term, i) {
var termName = term.get_name();
termsGlobal[termName] = {};
termsGlobal[termName].Label = termName;
termsGlobal[termName].TermGuid = term.get_id().toString();
// get child terms
return term.get_termsCount() > 0 ? (function() {
termsGlobal[termName].Terms = termsGlobal[termName].Terms || {};
return getTermsRecursive(term.get_terms(), termsGlobal[termName].Terms);
})() : null;
});
return jQuery.when.apply(jQuery, childTermsPromises);
}
return ns.SP.JSOM.loadMetadataScripts()
.then(getTermStores)
.then(getTermGroups)
.then(getTermGroup)
.then(getTermSets)
.then(getAllTerms);
}
},
Pages: {
getPagesLibrary: function() {
var ctx = SP.ClientContext.get_current(),
url = _spPageContextInfo.webAbsoluteUrl,
pageListId = _spPageContextInfo.pageListId.replace("{", "").replace("}", "");
return ns.SP.JSOM.Lists.getListById(url, _spPageContextInfo.pageListId)
.then(function(list) {
ctx.load(list);
return ns.SP.JSOM.executeQuery(ctx, list);
});
},
getPage: function(pageLibrary, pageId) {
return ns.SP.JSOM.Lists.Items.getItemById(pageLibrary, pageId);
},
getCurrent: function() {
return ns.SP.JSOM.Pages.getPagesLibrary()
.then(function(pageLibrary) {
return ns.SP.JSOM.Pages.getPage(pageLibrary, _spPageContextInfo.pageItemId);
});
}
},
Social: {
userCommentedOnCurrentPage: function() {
var user,
resultThread,
ctx = SP.ClientContext.get_current(),
feedMgr = new SP.Social.SocialFeedManager(ctx),
getCurrentUser = ns.SP.JSOM.Users.getCurrent;
function getCurrentPage(currentUser) {
user = currentUser;
return ns.SP.JSOM.Pages.getCurrent();
}
function createPost(page) {
var pageTitle = page.get_fieldValues()["Title"];
var pageUrl = window.location.href.split('?')[0].split('#')[0];
var userDataItem = new SP.Social.SocialDataItem();
userDataItem.set_itemType(SP.Social.SocialDataItemType.user);
userDataItem.set_accountName(user.get_loginName());
var linkDataItem = new SP.Social.SocialDataItem();
linkDataItem.set_itemType(SP.Social.SocialDataItemType.link);
linkDataItem.set_text(pageTitle);
linkDataItem.set_uri(pageUrl);
var socialDataItems = [userDataItem, linkDataItem];
var postCreationData = new SP.Social.SocialPostCreationData();
postCreationData.set_contentText('{0} commented on page {1}');
postCreationData.set_contentItems(socialDataItems);
postCreationData.set_source(linkDataItem);
// null here indicates a root post
resultThread = feedMgr.createPost(null, postCreationData);
return ns.SP.JSOM.executeQuery(ctx, resultThread);
}
return ns.SP.JSOM.loadUserProfileScripts()
.then(getCurrentUser)
.then(getCurrentPage)
.then(createPost);
},
userRepliedToPageComment: function(commentAuthor) {
var user,
resultThread,
ctx = SP.ClientContext.get_current(),
feedMgr = new SP.Social.SocialFeedManager(ctx),
getCurrentUser = ns.SP.JSOM.Users.getCurrent;
function getCurrentPage(currentUser) {
user = currentUser;
return ns.SP.JSOM.Pages.getCurrent();
}
function createPost(page) {
var pageTitle = page.get_fieldValues()["Title"];
var pageUrl = window.location.href.split('?')[0].split('#')[0];
var currentUserLink = new SP.Social.SocialDataItem();
currentUserLink.set_itemType(SP.Social.SocialDataItemType.user);
currentUserLink.set_accountName(user.get_loginName());
var authorUserLink = new SP.Social.SocialDataItem();
authorUserLink.set_itemType(SP.Social.SocialDataItemType.user);
authorUserLink.set_accountName(commentAuthor);
var linkDataItem = new SP.Social.SocialDataItem();
linkDataItem.set_itemType(SP.Social.SocialDataItemType.link);
linkDataItem.set_text(pageTitle);
linkDataItem.set_uri(pageUrl);
var socialDataItems = [currentUserLink, authorUserLink, linkDataItem];
var postCreationData = new SP.Social.SocialPostCreationData();
postCreationData.set_contentText('{0} replied to a comment by {1} on page {2}');
postCreationData.set_contentItems(socialDataItems);
postCreationData.set_source(linkDataItem);
// null here indicates a root post
resultThread = feedMgr.createPost(null, postCreationData);
return ns.SP.JSOM.executeQuery(ctx, resultThread);
}
return ns.SP.JSOM.loadUserProfileScripts()
.then(getCurrentUser)
.then(getCurrentPage)
.then(createPost);
},
followPage: function() {
var pageUrl = window.location.href.split('?')[0].split('#')[0];
return ns.SP.JSOM.Social.followDocument(pageUrl);
},
followDocument: function(url) {
var ctx = SP.ClientContext.get_current();
var followingManager = new SP.Social.SocialFollowingManager(ctx);
var socialActorInfo = new SP.Social.SocialActorInfo();
socialActorInfo.set_actorType(SP.Social.SocialActorTypes.documents);
socialActorInfo.set_contentUri(url);
followingManager.follow(socialActorInfo);
return ns.SP.JSOM.executeQuery(ctx);
}
},
enumerableToArray: function(enumerable) {
var enumerator = enumerable.getEnumerator();
var array = [];
while (enumerator.moveNext()) {
var current = enumerator.get_current();
array.push(current);
}
return array;
},
executeQuery: function(ctx, returnObject, toArray) {
var def = new jQuery.Deferred();
ctx.executeQueryAsync(function() {
returnObject ?
toArray ?
def.resolve(ns.SP.JSOM.enumerableToArray(returnObject)) : // resolve returnObject as an array
def.resolve(returnObject) : // resolve returnObject
def.resolve(); // resolve undefined
}, function(sender, args) {
LogMsg(args);
def.reject(args);
});
return def.promise();
},
Scripts: {
Base: _spPageContextInfo.webAbsoluteUrl + "/_layouts/15/",
CrossDomain: {
Global: "SP.RequestExecutor",
Scripts: ["sp.js", "sp.requestexecutor.js"]
},
Taxonomy: {
Global: "SP.Taxonomy",
Scripts: ["sp.js", "sp.taxonomy.js"]
},
UserProfiles: {
Global: "SP.Social",
Scripts: ["sp.js", "sp.userprofiles.js"]
},
Reputation: {
Global: "Microsoft.Office.Server.ReputationModel.Reputation",
Scripts: ["sp.js", "sp.core.js", "reputation.js"]
}
},
ensureLibraries: function(scriptDependency) {
var dfd = new jQuery.Deferred();
if (!utils.globalExists(scriptDependency.Global)) {
jQuery.each(scriptDependency.Scripts, function(i, url) {
if (!ns.SP.JSOM.scriptIsLoaded(url)) {
LogMsg("Loading script " + url);
utils.addScript(ns.SP.JSOM.Scripts.Base + url);
}
});
}
utils.executeOnGlobal(scriptDependency.Global, function() {
dfd.resolve();
});
return dfd.promise();
},
scriptIsLoaded: function(scriptFileName) {
var scriptIsLoaded = false,
scripts = jQuery("script");
function getFileName(url) {
return url.split('/').reverse()[0].toLowerCase();
}
scripts.each(function() {
var script = jQuery(this);
var url = script.attr("src");
if (url !== undefined) {
if (url.indexOf(".axd") == -1 && url.indexOf(".ashx") == -1) {
var thisScriptFileName = getFileName(url);
if (thisScriptFileName == scriptFileName.toLowerCase())
scriptIsLoaded = true;
}
}
});
return scriptIsLoaded;
},
loadUserProfileScripts: function() {
return ns.SP.JSOM.ensureLibraries(ns.SP.JSOM.Scripts.UserProfiles);
},
loadCrossDomainScripts: function() {
return ns.SP.JSOM.ensureLibraries(ns.SP.JSOM.Scripts.CrossDomain);
},
loadMetadataScripts: function() {
return ns.SP.JSOM.ensureLibraries(ns.SP.JSOM.Scripts.Taxonomy);
},
loadReputationScripts: function() {
return ns.SP.JSOM.ensureLibraries(ns.SP.JSOM.Scripts.Reputation);
},
displayError: function(args) {
LogMsg(args.get_message());
}
};
})();
(function() {
var nsName = "LS"; // root namespace name
var ns = window[nsName]; // root namespace alias
var utils = ns.Utils; // utils alias
ns.SP = ns.SP || {};
ns.SP.REST = {
Webs: {
getWebs: function() {
// URL exclusions (don't include the protocol or tenant sub-domain: i.e. "company365")
var trimDuplicates = false,
queryText = 'contentclass:"STS_Web" SPSiteUrl:' + _spPageContextInfo.siteAbsoluteUrl, // get webs for the site collection
sites;
LogMsg("Search query: " + queryText);
var queryUrl = window.location.protocol + "//" + window.location.hostname + "/_api/search/query?querytext='" +
queryText + "'&rowlimit=500&trimduplicates=" + trimDuplicates.toString() +
"&selectproperties='Path,Title'"; // reduce the amount of data returned to required fields
return jQuery.ajax({
url: queryUrl,
async: true,
method: "GET",
headers: {
"Accept": "application/json; odata=verbose"
}
})
.then(function (data) {
var results = data.d.query.PrimaryQueryResult.RelevantResults.Table.Rows.results,
sites = jQuery.map(results, function (result, resultIndex) {
var web = {};
jQuery.each(result.Cells.results, function(propIndex, prop) {
web[prop.Key] = prop.Value;
}); // map array dictionary to a simple object
return web;
});
return sites;
}, utils.displayAJAXError);
}
},
Sites: {
// get a list of private site collections
getSites: function() {
// Credit: http://social.msdn.microsoft.com/Forums/sharepoint/en-US/34441fc0-50c8-4db0-b539-05a9b9e28a3b/get-a-list-with-all-sharepoint-sites-with-javascript?forum=sharepointdevelopment
// URL exclusions (don't include the protocol or tenant sub-domain: i.e. "company365")
var urlExclusions = [".sharepoint.com/sites/contentTypeHub", "-public.sharepoint.com", "-my.sharepoint.com"],
trimDuplicates = false,
queryText = 'contentclass:"STS_Site"', // get site collections
sites,
// get SharePoint Online tenant sub-domain
subDomain = window.location.hostname.split('.')[0].replace("-my", "").replace("-public", "");
// add URL exclusions to query
jQuery.each(urlExclusions, function (index, value) {
queryText += ' -path:"' + window.location.protocol + '//' + subDomain + value + '"';
});
LogMsg("Search query: " + queryText);
var queryUrl = window.location.protocol + "//" + window.location.hostname + "/_api/search/query?querytext='" + queryText + "'&rowlimit=500&trimduplicates=" + trimDuplicates.toString(); // 500 is max per page. Exclusions must be included in the query to get the desired results in the first page (or you could implement paging).
return jQuery.ajax({
url: queryUrl,
async: true,
method: "GET",
headers: {
"Accept": "application/json; odata=verbose"
}
})
.then(function (data) {
var results = data.d.query.PrimaryQueryResult.RelevantResults.Table.Rows.results,
sites = jQuery.map(results, function (value, index) {
return value.Cells.results[6].Value;
});
return utils.arrayUnique(sites); // prevent duplicates
}, utils.displayAJAXError);
},
// get a list of personal site collections
getMySites: function() {
var trimDuplicates = false,
// get SharePoint Online tenant sub-domain
subDomain = window.location.hostname.split('.')[0].replace("-my", "").replace("-public", ""),
personalSitePath = "https://" + subDomain + "-my.sharepoint.com/personal",
rowLimit = 500, // this is the max possible page size
queryText = 'contentclass:"STS_Site" path:' + personalSitePath;
allSites = []; // array to store sites while iterating over results pages
function getSites(startRow) {
if(!startRow)
startRow = 0;
var queryUrl = window.location.protocol + "//" + window.location.hostname + "/_api/search/query?querytext='" + queryText + "'&rowlimit=" + rowLimit + "&startrow=" + startRow + "&trimduplicates=" + trimDuplicates.toString();
return jQuery.ajax({
url: queryUrl,
async: true,
method: "GET",
headers: {
"Accept": "application/json; odata=verbose"
}
})
.then(function (data) {
var totalRowCount = data.d.query.PrimaryQueryResult.RelevantResults.TotalRows,
results = data.d.query.PrimaryQueryResult.RelevantResults.Table.Rows.results,
sites = jQuery.map(results, function (value, index) {
return value.Cells.results[6].Value;
}),
sites = utils.arrayUnique(sites); // prevent duplicates
allSites = sites.concat(allSites); // add sites to allSites array
// if there are more results ? get the next page : return the results
return startRow + rowLimit < totalRowCount ? getSites(startRow + rowLimit) : allSites;
}, utils.displayAJAXError);
}
return getSites();
}
},
Lists: {
getItemType: function (url, listName) {
return jQuery.ajax({
url: url + "/_api/web/lists/getbytitle('" + listName + "')",
type: "GET",
dataType: 'json',
beforeSend: function (xhr) {
xhr.setRequestHeader("accept", "application/json; odata=verbose");
}
})
.then(function (data) {
LogMsg("ListItemEntityTypeFullName: " + data.d.ListItemEntityTypeFullName);
return data.d.ListItemEntityTypeFullName;
}, utils.displayAJAXError);
},
// http://www.plusconsulting.com/blog/2013/05/crud-on-list-items-using-rest-services-jquery/
getItem: function (url, listName, id) {
LogMsg("Getting item '" + id + "' from list '" + listName + "'");
return jQuery.ajax({
url: url + "/_api/web/lists/getbytitle('" + listName + "')/items(" + id + ")",
method: "GET",
headers: {
"Accept": "application/json; odata=verbose"
}
});
},
getItems: function (url, listName) {
return jQuery.ajax({
url: url + "/_api/web/lists/getbytitle('" + listName + "')/items",
type: 'GET',
dataType: 'json',
beforeSend: function (xhr) {
xhr.setRequestHeader("accept", "application/json; odata=verbose");
}
})
.then(function(data) {
return data.d.results;
});
},
getFields: function (url, listName, fieldInternalNames) {
return jQuery.ajax({
url: url + "/_api/web/lists/getbytitle('" + listName + "')/fields?$select=Title,InternalName,TypeAsString",
type: 'GET',
dataType: 'json',
beforeSend: function (xhr) {
xhr.setRequestHeader("accept", "application/json; odata=verbose");
}
})
.then(function (data) {
var array = data.d.results;
if (fieldInternalNames) {
array = jQuery.grep(array, function (value, index) {
return jQuery.inArray(value.InternalName, fieldInternalNames) > -1;
});
}
return array;
});
},
addItem: function (url, listName, metadata) {
return ns.SP.REST.Lists.getItemType(url, listName)
.then(function (listItemType) {
var data = jQuery.extend({
'__metadata': {
'type': listItemType
}
}, metadata);
LogMsg("Adding list item");
LogMsg(data);
return jQuery.ajax({
url: url + "/_api/web/lists/getbytitle('" + listName + "')/items",
type: "POST",
contentType: "application/json;odata=verbose",
data: JSON.stringify(data),
dataType: 'json',
headers: {
"Accept": "application/json;odata=verbose",
"X-RequestDigest": ns.SP.REST.getRequestDigest()
}
});
}, utils.displayAJAXError);
},
updateItem: function (url, listName, id, metadata) {
return ns.SP.REST.Lists.getItemType(url, listName)
.then(function (listItemType) {
var data = jQuery.extend({
'__metadata': {
'type': listItemType
}
}, metadata);
LogMsg("Updating list item " + id);
LogMsg(data);
return ns.SP.REST.Lists.getItem(url, listName, id)
.then(function (item) {
return jQuery.ajax({
url: item.d.__metadata.uri,
type: "POST",
contentType: "application/json;odata=verbose",
data: JSON.stringify(data),
dataType: 'json',
headers: {
"Accept": "application/json;odata=verbose",
"X-RequestDigest": ns.SP.REST.getRequestDigest(),
"X-HTTP-Method": "MERGE",
"If-Match": "*"
}
});
})
.then(function () {
LogMsg("Item updated");
return;
}, utils.displayAJAXError);
});
},
deleteItem: function (url, listName, id) {
LogMsg("Deleting list item " + id);
return ns.SP.REST.Lists.getItem(url, listName, id)
.then(function (item) {
return jQuery.ajax({
url: item.d.__metadata.uri,
type: "POST",
headers: {
"Accept": "application/json;odata=verbose",
"X-Http-Method": "DELETE",
"X-RequestDigest": ns.SP.REST.getRequestDigest(),
"If-Match": "*"
}
});
})
.then(function () {
LogMsg("Item deleted");
return;
}, utils.DisplayAJAXError);
}
},
Permissions: {
getSitePermissionLevels: function(url) {
// get an array of SP.RoleDefinition objects representing the Permission Levels for the site
return jQuery.ajax({
url: url + "/_api/web/RoleDefinitions?$select=Name,Description,Id,BasePermissions",
cache: false,
async: true,
dataType: "json",
beforeSend: function (xhr) {
xhr.setRequestHeader("accept", "application/json; odata=verbose");
}
})
.then(function (data) {
return data.d.results;
});
}
},
Users: {
getGroupMembers: function (url, groupTitle) {
return jQuery.ajax({
url: url + "/_api/web/SiteGroups?$select=Users&$expand=Users&$filter=Title eq '" + groupTitle + "'",
method: "GET",
headers: {
"Accept": "application/json; odata=verbose"
}
})
.then(function (data) {
var results = data.d.results[0].Users.results;
return results;
});
},
currentUserIsMemberOfGroup: function (groupTitle) {
return ns.SP.REST.Users.getGroupMembers(_spPageContextInfo.webAbsoluteUrl, groupTitle)
.then(function (data) {
var user = jQuery.grep(data, function (v, i) {
return v.Id == _spPageContextInfo.userId; // _spPageContextInfo.userId is the current user's ID for the current site collection
});
var userIsMember = user.length > 0;
return userIsMember;
});
},
doesUserHavePermission: function (url, spPermissionKind) {
var restEndpoint = url + "/_api/web/effectiveBasePermissions";
return jQuery.ajax({
url: restEndpoint,
type: 'GET',
dataType: 'json',
beforeSend: function (xhr) {
xhr.setRequestHeader("accept", "application/json; odata=verbose");
}
})
.then(function (data) {
var d = data.d;
var permissions = new SP.BasePermissions();
permissions.fromJson(d.EffectiveBasePermissions);
return permissions.has(spPermissionKind);
});
},
getUserId: function (url, loginName) {
return jQuery.ajax({
url: "{0}/_api/Web/SiteUsers(@v)?@v='{1}'".format(url, encodeURIComponent(loginName)),
type: "GET",
dataType: 'json',
beforeSend: function (xhr) {
xhr.setRequestHeader("accept", "application/json; odata=verbose");
}
})
.then(function (data) {
return data.d.Id;
});
},
ensureUser: function (url, loginName) {
return jQuery.ajax({
url: "{0}/_api/Web/EnsureUser(@v)?@v='{1}'".format(url, encodeURIComponent(loginName)),
type: "POST",
dataType: 'json',
headers: {
"Accept": "application/json;odata=verbose",
"X-RequestDigest": ns.SP.REST.getRequestDigest()
}
})
.then(function (data) {
return data.d.Id;
});
},
getUserById: function (url, id) {
return jQuery.ajax({
url: "{0}/_api/Web/GetUserById({1})".format(url, id),
type: "GET",
dataType: 'json',
beforeSend: function (xhr) {
xhr.setRequestHeader("accept", "application/json; odata=verbose");
}
})
.then(function (data) {
return data.d.LoginName;
});
},
getUserProperties: function (accountName) {
return jQuery.ajax({
url: "{0}/_api/SP.UserProfiles.PeopleManager/GetPropertiesFor(accountName=@v)?@v='{1}'".format(_spPageContextInfo.webAbsoluteUrl, encodeURIComponent(accountName)),
type: "GET",
dataType: 'json',
beforeSend: function (xhr) {
xhr.setRequestHeader("accept", "application/json; odata=verbose");
}
})
.then(function (data) {
var userProps = {};
jQuery.each(data.d.UserProfileProperties.results, function(i,v) { userProps[v.Key] = v.Value; });
return userProps;
});
}
},
getRequestDigest: function () {
UpdateFormDigest(_spPageContextInfo.webServerRelativeUrl, _spFormDigestRefreshInterval);
return jQuery('#__REQUESTDIGEST').val();
}
};
})();
(function() {
var nsName = "LS"; // root namespace name
// replacement function for console.log(), which avoids 'undefined' exception in IE 8
window.LogMsg = function(msg) {
if (window.console) {
console.log(msg);
}
};
var prototypeExtensions = function() {
var stringExtensions = function() {
// source: http://cwestblog.com/2011/07/25/javascript-string-prototype-replaceall/
if (!String.prototype.replaceAll) {
String.prototype.replaceAll = function(target, replacement) {
return this.split(target).join(replacement);
};
}
if (!String.prototype.format) {
String.prototype.format = function () {
var str = this.toString();
if (!arguments.length)
return str;
for (var i = 0; i < arguments.length; i++)
str = str.replaceAll("{" + i + "}", arguments[i]);
return str;
};
}
}(),
dateExtensions = function() {
var getFriendlyDate = (function () {
var monthNames,
dayNames,
MakeArray = function (n) {
this.length = n;
return this;
},
getOrdinal = function (o) {
return o + (['st', 'nd', 'rd'][(o + '').match(/1?\d\b/) - 1] || 'th');
},
formatFriendlyDate = function (date) {
return [
getOrdinal(date.getDate()),
monthNames[date.getMonth() + 1],
date.getFullYear()
].join(' ');
};
monthNames = new MakeArray(12);
monthNames[1] = "January";
monthNames[2] = "February";
monthNames[3] = "March";
monthNames[4] = "April";
monthNames[5] = "May";
monthNames[6] = "June";
monthNames[7] = "July";
monthNames[8] = "August";
monthNames[9] = "September";
monthNames[10] = "October";
monthNames[11] = "November";
monthNames[12] = "December";
dayNames = new MakeArray(7);
dayNames[1] = "Sunday";
dayNames[2] = "Monday";
dayNames[3] = "Tuesday";
dayNames[4] = "Wednesday";
dayNames[5] = "Thursday";
dayNames[6] = "Friday";
dayNames[7] = "Saturday";
return formatFriendlyDate;
})();
if (!Date.addYears) {
Date.prototype.addYears = function(modifier) {
return new Date(this.getFullYear() + modifier, this.getMonth(), this.getDate());
};
}
if (!Date.addMonths) {
Date.prototype.addMonths = function(modifier) {
return new Date(this.getFullYear(), this.getMonth() + modifier, this.getDate());
};
}
if (!Date.addDays) {
Date.prototype.addDays = function(modifier) {
return new Date(this.getFullYear(), this.getMonth(), this.getDate() + modifier);
};
}
if (!Date.toFriendlyDate) {
Date.prototype.toFriendlyDate = function () {
return getFriendlyDate(this);
};
}
if (!Date.fromISO) {
Date.prototype.fromISO = function (isoDateString) {
var d = isoDateString.substr(0, 10).split('-'); // yyyy,MM,dd
this.setFullYear(d[0]);
this.setMonth(d[1]-1);
this.setDate(d[2]);
return this;
};
}
}();
}(),
createRootNamespace = function() {
return window[nsName] = {};
},
ns = createRootNamespace();
ns.Utils = {
// namespace creation function
ensureNamespace: function(ns) {
if (!ns.Utils.globalExists(ns)) {
var nsArr = ns.split('.'); // split into array
var obj = window; // start at window object
for (var i = 0; i < nsArr.length; i++) {
if (nsArr[i] == "window") // skip window if this is included in string
continue;
obj[nsArr[i]] = obj[nsArr[i]] || {}; // create an empty object
obj = obj[nsArr[i]]; // get the new object and continue
}
LogMsg("Added namespace: " + ns);
}
},
// check if a global variable exists
globalExists: function(global) {
return ns.Utils.getGlobal(global) != null;
},
// return a global from a string representation of its path
getGlobal: function(globalString) {
var globalArr = globalString.split('.'); // split into array
var obj = window; // start at window object
for (var i = 0; i < globalArr.length; i++) {
if (globalArr[i] == "window") // skip window if this is included in string
continue;
if (!obj[globalArr[i]])
return null; // the global namespace does not exist
obj = obj[globalArr[i]]; // get the new object and continue
}
return obj; // the global namespace exists
},
// execute a callback when a global is present
executeOnGlobal: function(global, func) {
if (!ns.Utils.globalExists(global)) {
setTimeout(function() {
ns.Utils.executeOnGlobal(global, func);
}, 100);
} else {
func();
}
},
// add a script to the page
addScript: function(url) {
var script = document.createElement("script");
script.setAttribute("src", url);
var head = document.getElementsByTagName("head")[0];
head.appendChild(script);
},
// check for a global variable, load a script if it doesn't exist and execute a callback once the global variable is present
ensureLibrary: function(global, url, func) {
if (!ns.Utils.globalExists(global))
ns.Utils.addScript(url);
if (func)
ns.Utils.executeOnGlobal(global, func);
},
// adapted from http://stackoverflow.com/a/21152762
getQueryString: (function() {
var queryStrings = {},
qs = window.location.search.substr(1).split("&");
for (var i = 0; i < qs.length; i++) {
var item = qs[i];
queryStrings[item.split("=")[0]] = decodeURIComponent(item.split("=")[1]);
}
return function(key) {
return queryStrings[key];
};
})(),
// Source: SR http://code.msdn.microsoft.com/office/SharePoint-2013-Folder-661709eb
replaceQueryStringAndGet: function(url, key, value) {
var re = new RegExp("([?|&])" + key + "=.*?(&|$)", "i");
var separator = url.indexOf('?') !== -1 ? "&" : "?";
if (url.match(re)) {
return url.replace(re, '$1' + key + "=" + value + '$2');
} else {
return url + separator + key + "=" + value;
}
},
// helper for sorting arrays by property value (where getObjectProperty is a function that gets the object property that you would like to sort by)
sortFunction: function(getObjectProperty, sortAscending) {
return function(objA, objB) {
var a = getObjectProperty(objA),
b = getObjectProperty(objB);
if (!sortAscending)
var c = a,
a = b,
b = c; // swap a and b
if (a < b)
return -1;
if (a > b)
return 1;
return 0;
};
},
// if string 'str' contains a string in the array 'arr' return true, otherwise return false
stringContainsArrayString: function(str, arr) {
return (jQuery.grep(arr, function(value, index) {
return str.indexOf(value) > -1;
})).length > 0;
},
// return a copy of the array with duplicates removed
arrayUnique: function(array) {
var uniqueArray = [];
jQuery.each(array, function(index, value) {
if (jQuery.inArray(value, uniqueArray) === -1)
uniqueArray.push(value);
});
return uniqueArray;
},
// AJAX error callback
displayAJAXError: function(request, status, error) {
LogMsg(["Error", error]);
},
displayError: function() {
LogMsg(Array.prototype.slice.call(arguments));
},
// source: SO http://stackoverflow.com/a/2117523
createGuid: function() {
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
var r = Math.random() * 16 | 0,
v = c == 'x' ? r : (r & 0x3 | 0x8);
return v.toString(16);
});
},
rateLimit: (function() {
var dictionary = {};
function unlock(key) {
dictionary[key].timer = -1; /* allow execution of 'func' when 'rate' timeout has expired */
if (dictionary[key].queued) { /* if requested during the cooldown, trigger the function when the cooldown has finished */
dictionary[key].queued = false;
execute(key);
}
}
function execute(key) {
var item = dictionary[key];
item.timer = setTimeout(function() {
unlock(key);
}, item.rate);
item.onExecute();
}
function executeOrQueue(key) {
/* allow the function to be executed subsequent times at the rate specified */
if (dictionary[key].timer == -1) {
execute(key);
} else {
dictionary[key].queued = true;
}
}
function addAndExecute(key, func, rate) {
dictionary[key] = {
onExecute: func,
timer: -1,
queued: false,
rate: rate
};
execute(key); /* execute the function the first time and start the rate limit timer */
}
return function(key, func, rate) {
if (!dictionary[key]) { /* add the key to the dictionary if it doesn't already exist */
addAndExecute(key, func, rate);
} else {
executeOrQueue(key);
}
};
})(),
loadjQuery: function(callBack) {
ns.Utils.ensureLibrary("jQuery", "//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js", callBack);
}
};
})();
@TDK1964
Copy link

TDK1964 commented Jan 13, 2016

Nice library :) Did you ever get the cross domain code incorporated?

@akhileshnirapure
Copy link

Great stuff.. really lean

@Rohitwghela
Copy link

very helpful library. Amazing..

@nagendrarao1
Copy link

Excellent library....

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment