Giter Club home page Giter Club logo

sprestlib's Introduction

npm version MIT License Known Vulnerabilities Package Quality jsDelivr Stats

SpRestLib

Microsoft SharePoint REST JavaScript Library

SpRestLib is a lightweight wrapper around the SharePoint REST API that can be used in client browsers or server-side.

This library is for developers who build web parts embedded into Content Editor/Script Editor, SPFx web parts, Angular/React apps, Node.js/npm-based solutions, etc. Using SpRestLib greatly simplifies SharePoint integration by reducing common operations to concise Promise-based methods.

Library Features

  • Simple - Clean, concise API: Get users, sites, list items, etc. in 1-3 lines of code
  • Modern - Lightweight, pure JavaScript solution with no other dependencies
  • Elegant - Utilizes the new ES6 Promise architecture for asynchronous operations
  • Robust - Handles authentication, asynchronous errors, results paging and more

SharePoint Interfaces

  • List Methods - Create, read, update, and delete (CRUD) List/Library items, including support for paging/next
  • User Methods - Get User information: Basic (ID, Email, LoginName, etc.) and UserProfile (Manager, 100+ Properties)
  • Site Methods - Get Site information (Lists, Groups, Users, Roles, Subsites and Permissions)
  • File Methods - Get files, file properties/permissions, delete/recycle files
  • Folder Methods - Get folder contents, folder properties/permissions, create/delete/recycle folders
  • REST Methods - Execute REST API calls against any available SharePoint REST API endpoint
  • Form Population - Populate form elements using data-bind declarative binding system like Knockout or AngluarJS

Supported Environments

  • SharePoint 2013 (SP2013), SharePoint 2016 (SP2016), SharePoint 2019 (SP2019), SharePoint Online (SPO)

Method Overview

REST API

List/Library

  • sprLib.list(listName).items() - Returns an array of SP.ListItem objects using a variety of query options
  • sprLib.list(listName).create() - Create a new list item using JSON data
  • sprLib.list(listName).update() - Update an existing item using JSON data
  • sprLib.list(listName).delete() - Delete an existing item using JSON data (permanently delete)
  • sprLib.list(listName).recycle() - Recycle an existing item using JSON data (move to Recycle Bin)
  • sprLib.list(listName).cols() - Returns an array of column properties (datatype, default values, etc.)
  • sprLib.list(listName).info() - Returns SP.List properties (last modified, number of items, etc.)
  • sprLib.list(listName).perms() - Returns an array of the list's Member Role assignments

File

  • sprLib.file(fileName).get() - Returns a file (binary/text) as a blob which can be saved
  • sprLib.file(fileName).info() - Returns SP.File properties (Created, GUID, HasUniquePerms, etc.)
  • sprLib.file(fileName).perms() - Returns an array of the file's Member Role assignments
  • sprLib.file(fileName).checkin() - Check in a file (supports optional comments/checkin types)
  • sprLib.file(fileName).checkout() - Check out a file
  • sprLib.file(fileName).delete() - Permanently deletes a file (bypasses recycle bin)
  • sprLib.file(fileName).recycle() - Moves file to the site Recycle Bin

Folder

  • sprLib.folder(folderName).files() - Returns an array of file objects contained in the folder
  • sprLib.folder(folderName).folders() - Returns an array of folder objects contained in the folder
  • sprLib.folder(folderName).info() - Returns SP.Folder properties (Created, GUID, HasUniquePerms, etc.)
  • sprLib.folder(folderName).perms() - Returns an array of the folder's Member Role assignments
  • sprLib.folder(folderName).add() - Creates a new folder under the parent folder
  • sprLib.folder(folderName).delete() - Permanently deletes a folder (bypasses recycle bin)
  • sprLib.folder(folderName).recycle() - Moves folder to the site Recycle Bin

Site Collection/Subsite

  • sprLib.site(siteUrl).groups() - Returns an array of the site's Groups and Members
  • sprLib.site(siteUrl).info() - Returns SP.Web site properties (ID, Owner, Language, Logo, etc.)
  • sprLib.site(siteUrl).lists() - Returns an array of the site's Lists/Libraries
  • sprLib.site(siteUrl).perms() - Returns an array of the site's Member/Roles objects
  • sprLib.site(siteUrl).roles() - Returns an array of the site's Roles
  • sprLib.site(siteUrl).subsites() - Returns an array of the site's Subsites
  • sprLib.site(siteUrl).users() - Returns an array of the site's Users and their base permissions

User Groups/Info/Profile

  • sprLib.user(options).groups() - Returns SP.Group group properties (Id, Owner, Title, etc.)
  • sprLib.user(options).info() - Returns SP.User user properties (Id, Email, Login, Title, etc.)
  • sprLib.user(options).profile() - Returns SP.UserProfile.PersonProperties (DirectReports, PictureUrl, etc.)

Utility Methods

  • sprLib.renewSecurityToken() - Refreshes the SharePoint page security digest token (__REQUESTDIGEST)

SpRestLib-UI :: Form Population

  • data-sprlib{options} - Populates the parent tag using the options provided


Library Demo

Demo via Browser Console

It's really easy to test drive SpRestLib!

Just open your browser's Developer Tools window anywhere on your SharePoint site, then run the following code snippet which will load the SpRestLib bundle script dynamically:

// Load/Demo SpRestLib via CDN
var script = document.createElement('script');
script.src = "https://cdn.jsdelivr.net/gh/gitbrent/[email protected]/dist/sprestlib.bundle.js";
script.onload = function(){
    // Demo library method - show current user info
    console.log('Current SharePoint User: ');
    sprLib.user().info().then( objUser => console.log(objUser) );
}
document.getElementsByTagName('head')[0].appendChild(script);

Try It Out

Demo via Page Web Part

Upload the example/sprestlib-demo.html file to SiteAssets on your SharePoint site and add it into a web part for a live demo of all available methods.

Demo SharePoint Web Part


Installation

CDN

<script src="https://cdn.jsdelivr.net/gh/gitbrent/[email protected]/dist/sprestlib.min.js"></script>
// Use bundle for IE11 support
<script src="https://cdn.jsdelivr.net/gh/gitbrent/[email protected]/dist/sprestlib.bundle.js"></script>

Download

<script src="/subsite/SiteAssets/js/sprestlib.min.js"></script>
// Use bundle for IE11 support
<script src="/subsite/SiteAssets/js/sprestlib.bundle.js"></script>

npm

npm install sprestlib

var sprLib = require("sprestlib");

yarn

yarn install sprestlib

Method Reference

REST API Methods

REST API Methods

List/Library Methods (SP.List)

List/Library Methods

File Methods (SP.File)

File Methods

Folder Methods (SP.Folder)

Folder Methods

Site Methods (SP.Web)

Site Methods

User Methods (SP.User)

User Methods

Utility Methods

Utility Methods

Form Binding (SpRestLib UI)

Form Binding


Library Features and Notes

Async Operations via Promises

JavaScript Async Promises

SharePoint Authentication Notes

SharePoint Authentication Notes

Integration with Other Libraries

Using SpRestLib with React, Angular, SharePoint Electron, etc. Integration with Other Libraries

Connect to SharePoint Online/Office.com with Node.js

  • SpRestLib can be utilized via Node.js to perform powerful operations, generate reports, etc.
  • See the example directory for a complete, working demo of connecting to SharePoint Online.

Issues / Suggestions

Authentication

See SharePoint Authentication Notes for issues with authentication.

Bugs

Please file issues or suggestions on the issues page on GitHub, or even better, submit a pull request. Feedback is always welcome!

When reporting issues, please include a code snippet or a link demonstrating the problem.


Supported SharePoint Versions

Backwards Compatibility

Does SpRestLib support SharePoint 2010 or 2007?
Unfortunately, older versions cannot be supported. The SharePoint 2007/2010 API utilized SOAP web services with XML (_vti_bin/lists.asmx endpoints) while the current API uses a completely new (_api/web/lists() endpoint) backed by REST services.


Special Thanks

  • Marc D Anderson - SpRestLib is built in the spirit of the late, great SPServices library
  • Microsoft - for the SharePoint.com developer account
  • Everyone who submitted an Issue or Pull Request

License

Copyright © 2016-2019 Brent Ely

MIT

sprestlib's People

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

sprestlib's Issues

Error in list('listname').create({data})

Good day!

When I try to create an item in a list I get the following error:

400 - {"error":{"code":"-1, Microsoft.SharePoint.Client.InvalidClientQueryException","message":{"lang":"en-US","value":"A node of type 'EndOfInput' was read from the JSON reader when trying to read the start of an entry. A 'StartObject' node was expected."}}}

const body = {
                Name: action.userData.name,
                Surname: action.userData.surname,
                Alias: action.userData.alias,
                Gin: action.userData.gin,
                Location: action.userData.location,
                Email: action.userData.email
            };
            return sprLib.list('NgPeople').create(body);

I guess it is related to sending 'data' or 'body' object during request.

Regards,
Zhandos

ERROR in ./node_modules/sprestlib/dist/sprestlib.js

Hi,

I'm using Angular 4 and I'm trying to use: var sprLib = require("sprestlib");

I keep getting this error:
ERROR in ./node_modules/sprestlib/dist/sprestlib.js
Module not found: Error: Can't resolve 'https' in 'C:\Users\USER\Documents\spapp\sp-app\node_modules\sprestlib\dist'

regards

'listGUID' not supported when with ‘baseUrl’

Hello,
I like this lib very much.
but it seems the following is not support right now. I wanted to always use the GUID because the list title can be changed by others.

sprLib.list({ listGUID:"the GUID", baseUrl:"the url" }).getItems...

Latest npm package

Hi,
I need to have the npm package which contains the last commits

Thank you

sprLib.folder().add() requires requestDigest / security token

Hi,

I'm using the SpRestLib in Node and was unable to make sprLib.folder().add() work, I always got the error message "The security validation for this page is invalid. Click Back in your Web browser, refresh the page, and try your operation again.".
When I do the call manually via
sprLib.rest({ type: "POST", url: vURL, requestDigest: token, metadata: false })

It does work, it seems that SharePoint expects the requestDigest for folder add operations as well.

File uploading api

Hi,
I want upload files to a Sharepoint library, but didnt found a method to do this, do you plan to add it in the soonly?

Thanks

Addtional call made when using sprLib.user(options).profile()

I noticed when I only execute sprLib.user(options).profile() I saw below call is made, but we don't get any info from this call because we are trying to get info from sprLib.user(options).profile()

siteUrl/_api/Web/siteusers?$filter=Email%20eq%20%27UserMailID%27&$select=Id,Title,Email,LoginName,IsSiteAdmin,PrincipalType

Set default "queryLimit" to 1000

In the early versions (e.g. 1.4.0-beta) you have set default "queryLimit" to 1000 using "'$top=' + ( inObj.queryLimit ? inObj.queryLimit : APP_OPTS.maxRows );" but now this has been dropped in the last version. I understood you want to align with the default sharepoint behavior, however this is something we often forget and in most of the case we want to set the limit more than 100. So we have to give this parameter for each call , or if we forget users will only see 100 items and the issue would be reported sooner after we deploy the app.

If we still have 1000 as default value life will be much earlier for us :-) Because we don't need to take care of this (in most of the cases 1000 items can meet the needs). Maybe I am talking about my particular environment where we don't work with huge items in SP.

Modify user() method option names to be case insensitive

The user() method takes options with names like title, email, etc.

If a user doesn't utilize the correct case, the user method returns the current user's properties (the API treats it as if a null value was passed). This is both an unwanted design outcome and a potentially confusing response for users.

The option names should be made case insensitive to correct the issue.

sprLib.user({ title:'Bill Gates' }).then(...) // Returns Bill's user properties
sprLib.user({ Title:'Bill Gates' }).then(...) // Returns the current users properties

Returning all ltems from a list

The methods available for returning list items are paged. Can the pattern below be made more general or idiomatic?

The desired function

getRecords('Test',['ID', 'Title', 'SupplierId'])
         .then(function(ret) {
            console.log(ret);
         });

returns

{list: 'Test', listCols: ['ID', 'Title', 'SupplierId'], data: [{},...]}

implementation

function getRecords(list, listCols) {
         return new Promise(function(resolve) {         
            var data = [];
            function innerGetRecords(dataPage) {
               if (dataPage) {
                  data = data.concat(dataPage);
                  if ('__next' in dataPage[0]) {
                     sprLib.list(list)
                        .items({
                           listCols: listCols,
                           queryNext: dataPage[0].__next
                        })
                        .then(innerGetRecords)
                        .catch(errMsg => console.error(errMsg));
                  } else {
                     resolve({list: list,listCols: listCols,data: data})
                  }

               } else {
                  sprLib.list(list)
                     .items({
                        listCols: listCols,
                        queryLimit: 5000 // library's upper limit
                     })
                     .then(innerGetRecords)
                     .catch(errMsg => console.error(errMsg));
               };
            }
            innerGetRecords(); 
         });
      }

Paging capability

Hello!

How is it possible to access __next property for pagination using List methods? I couldn't find any hints for paging in sprestlib documentation. API is really lightweight and very handy, it would be great to have paging options as well.

Regards,
Zhandos

sprLib.user(options).profile() using "post" ?

Hello,

I run below query but I saw it is a "POST" action and I got error:

"error":{"code":"-2130575251, Microsoft.SharePoint.SPException","message":{"lang":"en-US","value":"The security validation for this page is invalid and might be corrupted. Please use your web browser's Back button to try your operation again."}}}

I tried to add the digest token but it did not work.

I used this API before but I used the "GET" Method and it worked for me.

//////////////////////////////
sprLib.user({
baseUrl: 'https://xxxx.sharepoint.com/teams/StrategyandPOA',
email: '[email protected]',
}).profile().then(function (objUser) {
console.log(objUser)
});

capture

site url cannot be called in user() method after introduction of "sprLib.baseUrl()"

Hello,

in issue# 8 (#8) we discussed to add the site url to the user methods, and It work at that time but it seems this is no long working after you introduced the "sprLib.baseUrl()"

error from console:
Warning: Check your options! Available user() options are: id,email,login,title

var siteUrl = 'https://xxx.sharepoint.com/teams/xxx'
sprLib.user({
	baseUrl: siteUrl
}).info().then(function (objUser) {
	console.log(objUser)
});

however this is working

sprLib.baseUrl('https://xxx.sharepoint.com/teams/xxxx');
sprLib.user().info().then(function (objUser) {
	console.log(objUser)
});

Query options passed to .rest() are only parsed when 'queryCols' exists

The .rest() method is ignoring options (not including them in REST queries) when queryCols is not included:

CODE:

sprLib.rest({ url:'/sites/dev/_api/web/lists', queryFilter:'ID eq 99' })

RequestURL:
/sites/dev/_api/web/lists?_=1507783353329

CODE:

sprLib.rest({ url:'/sites/dev/_api/web/lists', queryCols:'ID', queryFilter:'ID eq 99' })

RequestURL:
/sites/dev/_api/web/lists?$select=ID&$top=1000&$filter=ID%20eq%2099&_=1507783353336

Incorrect request parameter when using only one queryNext option

When I use only one option sprLib.list().items({ queryNext: { prevId: 29, maxItems: 5 } }), it requests like this http://localhost:3000/_api/lists/getbytitle('UsersDetail')/items&p_ID=29&$top=5.
You can see than before p_ID=29 stand & intstead of ?.
And I get an error Invalid argument.

But if I add more than one option on request, like this:
sprLib.list(usersList).items({ listCols: ['ID'], queryNext: { prevId: 29, maxItems: 5 } });, my request is good http://localhost:3000/_api/lists/getbytitle('UsersDetail')/items?%24skiptoken=Paged%3dTRUE%26p_ID%3d29&%24select=ID&p_ID=29&$top=5 and before my first GET argument stands question symbol ?

Lib folders managing

I want a direct method (instead of using sprestLib.rest), to create and edit documents library folders.

Using SPRestLib in an Office Add-in

Hi,

Do you have any examples of access SharePoint List from within a Office Add-in. I've tried the following:

 sprLib.rest({ url: '_api/contextinfo', type: 'POST' })
            .then(arr => {
                var strReqDig = arr[0].GetContextWebInformation.FormDigestValue;
                return sprLib.list({ name: 'Tasks', requestDigest: strReqDig, baseUrl: '{url}' }).items()
                    .then(function (arrItems) {
                        showNotification("length: ", arrItems.length)
                    })
            })
            .then(obj => {
                console.log('Item created!');
            })
            .catch(function (strErrMsg) { showNotification("Error: ",strErrMsg) });

{url} is pointing to my sharepoint site. when running, the error message i'm getting is:

The resource you are looking for has been removed, had its name changed, or is temporarily unavailable.
Requested URL | https://localhost:44304/_api/contextinfo

Thanks

Defect: The list() `baseUrl` option is ignored by the underlying versions query.

Desc:

  • The lists() baseUrl option is ignored by the underlying versions query.

Test Case:

  • Run from: /sites/dev/
sprLib.list({ name:'Site Assets', baseUrl:'/sites/dev/sandbox' }).items({
  listCols: {
    id: {dataName: 'Id'},
    file: {dataName:'FileLeafRef', getVersions:true }
  }
})
.then(function(data){ return data; });

Result:

  • baseUrl was ignored and the current site was queried

screen shot 2018-06-28 at 19 03 31

profile() only accepts properties from UserProfileProperties

To implement the enhancement in #38 you have made changes to sprLib.user(options).profile(). Now it seems we cannot provide any Properties from Person Properties like 'DirectReports', 'DisplayName' etc

sprLib.user(options).profile('DirectReports') -->this is not working, error: DirectReports"DirectReports property does not exist in SP.UserProfiles.PeopleManager.UserProfileProperties"

sprLib.user(options).profile('Department')-->this is working fine, 'Department' is part of the UserProfileProperties

How to simplify the lookup column return to a list of ids

I am trying to simplify the returned values for a lookup column down to a list of Ids.

The Events list has a Supplier lookup column.

Initially I tried,

sprLib.list('Events').items({
    listCols: {
        EventId: { dataName: 'ID' },
        SupplierIds: { dataFunc: function (objItem) { return objItem.SupplierId.results } }
    }
})

But this doesn't work because SupplierId is not returned by the query. Instead it appears that this is required:

sprLib.list('Events').items({
    listCols: {
        EventId: { dataName: 'ID' },
        SupplierId: { dataName: 'SupplierId' },
        SupplierIds: { dataFunc: function (objItem) { return objItem.SupplierId.results } }
    }
})

Is there a way to return SupplierIds without also returning the SupplierId object?

David

Webpack jQuery dependency

Hello,
When I am building my application based on sprLib, with npm and webpack, the file included in the build is sprestlib.js which does not contains the Jquery dependency.
import sprLib from 'sprestlib' is including this file instead of sprestlib.bundle.js which contains the jquery dependency.
To bypass this I modified the file sprestlib/package.json:

"main": "dist/sprestlib.js", --> "main": "dist/sprestlib.bundle.js",

Is this the expected behavior? Do I misunderstood something?
Why don't replace Jquery by a more specific library such as axios, lodash, etc...?

Thank you

List Workflow managment

Hi,
Is there any planning to implement some methods to manage (list, start & stop) list workflow instances?

Thanks,

sprLib.list cannot fetch more than a 100 items

When calling sprLib.list() on a list with more than a 100 items, only the first 100 items are returned. How to set $top?

sprLib.list('list').items().then( data => { console.log(data) } )

(v1.7.0)

sprLib.file(somefile).checkout is not a function

Uncaught TypeError: sprLib.file(...).checkout() is not a function
Was returned for the first time.

Any clue as to why this is so? I have been using this since June without issue, now today there is an issue.
sprLib.file(somefile).info() functions just fine!

New issue with Response Header...

-Type: application/atom+xml;type=feed;charset=utf-8

Perhaps in an afront to my sanity, one of the sharepoint servers I am querying, despite requesting a JSON response, seems to be returning application/atom+xml.

I am certain when I ran the exact code about 4 weeks ago it was working, so I am assuming something may have changed in the server configuration that I wasn't aware of. It looks like the data is still being returned if I look at the raw response data, , but I am guessing SPRestLib isn't parsing it anymore..

Has anyone dealt with something similar to this?

image

Add new option for auth DigestToken

Source: Issue #5

Desc: Add new option to .rest() and List CRUD API's for "DigestToken" value to be passed (fall back to form element if available, thereby keeping current functionality intact)

Demo doesn't work from sub-folder off sitepages

Hi

Small detail, if the sprestlib-demo.html is added in a subfolder of sitepages and then made available through an demo.aspx in the same folder API accesses fail with 404 errors.

David

SP Rest API support for adding Groups

It appears that SP REST Api support for adding and updating groups is relatively weak compared wtih other APIs. Is there anything that can be done witha d]

standalone call for "UserProfileProperties"

Hi,
again this is a great library!

if I only need the "UserProfileProperties" the call will return all other "Person Properties" though the API will return only "UserProfileProperties" with function sprLib.user(options).profile('UserProfileProperties')

from the performance perspective the call returns a lot of info that we don't need, especially when the user has many peers or direct reports etc. If possible you may create a standalone function for UserProfileProperties only with below query :

Url = "https://xx.sharepoint.com/teams/3wuam/_api/SP.UserProfiles.PeopleManager/GetPropertiesFor(accountName=@v)/UserProfileProperties?@v='i:0%23.f|membership|" + mailID + "'"

with above query we can get the UserProfileProperties much faster

just a suggestion but the existing functions are already great to go with :)

Error in list('listname').create({data})

Hello,
I am facing the same problem as discussed on issue #5, I am using SpRestLib in a Sharepoint hosted app, into the default.aspx page, when making GET calls no problem, but when I call list('listname').create({data}),
with data as JSON object {name:"test", ...}, I get an error about page validation etc, in devtools I noted that there is no X-RequestDigest nor Payload in the post call.
image

How can I resolve the issue as there is no solution mentioned in the previous discussion #5 ?
Thanks in advance

sprLib.site().groups() fails on SP2013

Really enjoying the SpRestLib - fantastic and stable tool. I'm now porting code from SPOnline back to Onprem 2013 and what initially seemed to be a permission issue, appears to be a API difference between SPOnline and SP2013?

Using the demo sandbox on SPOnline

sprLib.site().groups()

works as expected. On SP2013 onprem

sprLib.site().groups()

generates an unending request to sign-in with different credentials and when the dialog is cancelled, the error message is:

ERROR
(401) Access denied. You do not have permission to perform this action or access this resource.

URL used: ../_api/web/SiteGroups?$select=Id,Title,Description,OwnerTitle,PrincipalType,AllowMembersEditMembership,Users/Id,Users/LoginName,Users/Title&$top=5000&$expand=Users/Id,Users/LoginName,Users

But if we modify the call to eliminate the $expand, directly calling the rest end point it works!

sprLib.rest({
  url: '_api/web/SiteGroups?$select=Id,Title,Description,OwnerTitle,PrincipalType,AllowMembersEditMembership,Users/Id,Users/LoginName,Users/Title&$top=5000'
})
.------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------.
|                                                  Users                                                  | Id  |                       Title                        | PrincipalType | AllowMembersEditMembership |                                                                                   Description                                                                                   |        OwnerTitle        |
|---------------------------------------------------------------------------------------------------------|-----|----------------------------------------------------|---------------|----------------------------|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|--------------------------|
....

This appears to be an API difference between SPOnline and SP2013?

David

not able to pass site url for "User Methods"

Hello,
I looked into the source code too but I did not find a way to pass the site url for "User Methods". I usually complete the application (js, css, html) locally and then when everything is fine I upload the package to sharepoint folder then users can access the .aspx pages (changed extension from html to aspx) So I always use the complete sharepoint site url.

So if you can set global var for the baseUrl for all functions or at least for the User Methods then it will be much more useful.

Currently I use the original Ajax call for all the projects

function currentLogin() {
     $.ajax({
         url: "xxxx/teams/apmt/_api/SP.UserProfiles.PeopleManager/GetMyProperties?$select=DisplayName,Email",
         async: false,
         type: 'get',
         headers: {
             "Accept": "application/json;odata=verbose"
         },
         cache: false,
         //dataType: 'json',
         success: function(spJsonData) {
             //get user name
             var pageDisplayName;
             var displayName = spJsonData.d.DisplayName
             var isLongerDisplayName = displayName.search(/[(]/)
             if (isLongerDisplayName != -1) {
                 var bracketStart = displayName.indexOf("(")
                 pageDisplayName = displayName.substring(0, bracketStart)
             } else(pageDisplayName = spJsonData.d.DisplayName)
             var loginMsg = "Welcome " + pageDisplayName
             $("#login-name").html(loginMsg)
             //get user mail id
             $("#userMail").html(spJsonData.d.Email)
             var picURL = "url(https://outlook.office365.com/owa/service.svc/s/GetPersonaPhoto?email=" + spJsonData.d.Email + ")"
             $("#login-image").css("background-image", picURL)
         },
         error: function() {
             $("#login-name").html("Welcome ,[...]")
         }
     });
 }

SP.Folder does not return data related to current site

#site location of code:
/sites/uat/vanilla

code:

 script.onload = function () {
       sprLib.folder("SiteAssets").info().then(objSiteInfo => console.log(objSiteInfo));
       }

results:

Created: "2018-09-05T16:25:54"
FolderCount: 9
HasSubdirs: true
HasUniqueRoleAssignments: false
Hidden: false
ItemCount: 13
ListGUID: "{CB79ACA3-9E86-4C55-8DCE-88E6CD0E14ED}"
Modified: "2019-03-19T22:02:33"
Name: "SiteAssets"
ServerRelativeUrl: "/sites/UAT/SiteAssets"
TotalSize: 4812042

alternate code:

script.onload = function () {
    sprLib.folder("/sites/uat/vanilla/SiteAssets").info().then(objSiteInfo => console.log(objSiteInfo));
    }

alternate results:

Uncaught (in promise) (404) List does not exist.

The page you selected contains a list that does not exist. It may have been deleted by another user.

URL used: ../_api/web/Lists(guid'5519F739-A6AB-4D49-ABF1-EC6348B314AD')/rootFolder/Folders?$select=ListItemAllFields/Id&$expand=ListItemAllFields

Notes:

may be related/similar to issue #27
GUID in alternate results is correct for the list requested.

sprLib.list().cols() alignment with sprLib.list().items() returned column names

My use case is about handling empty lists. It would greatly simplify some code if I didn't have to treat the empty list case as a special one.

Is it possible to have a canonical list of columns that sprLib identifies as columns shared by sprLib.list().items() and sprLib.list().cols()?

I would like to use sprLib.list().cols() to extract the schema returned by sprLib.list().items(). However, sprLib.list().cols() has one view and sprLib.list().items() another?

At the moment the list of columns returned by sprLib.list().items() is only knowable by introspection of the result which fails in the case of zero items.

Thanks

David

listCols dateFormat issue

Hello,
Thanks for your interactif collaboration, I am want to format a Date field as I get items via sprLib.List().getItems(listCols), I user listCols Obj and set date:

{dataName:'DateFieldName',formatDate:'DATE'}

But I always get the unformatted date format

When I search in your code, there is no mention of the formatDate in getItems function.

Can´t view new column in default view

Not add in default view the new created column, only inserted in edit mode:

      var StartDate = {
        '__metadata': {'type':'SP.FieldDateTime'},
        'FieldTypeKind': 4,
        'Title': 'Start Date',
        'DisplayFormat': 0 
      };
. . .
   sprLib.rest({
        url: '/sites/MyDemo/_api/contextinfo',
        type:'POST',
        requestDigest: diggestCode,
        data: JSON.stringify(StartDate)
      }).then( alert( "Column has been created!"););
    ).catch( alert( "cant insert")
  );
...

sprestlib-demo-people-picker.aspx to be mentioned in the API manual

SpRestLib is a great lib for sharepoint ! As a sharepoint client side developer(20% of my role) I liked the elegant & powerful APIs. It makes my work so easy and amazing output.

Especially I liked the people-picker a lot. I was trying to find a solution for almost a year and tried many libraries from GitHub but none worked for me. This one just worked after I passed the "requestDigest" to the query. And we don't need to load a lot of other sharepoint js files like what mentioned in other solutions.

however, this great feature is not even mentioned in the user manual, I think others like me might also miss this if they search in GitHub. I strongly suggest to mention the people picker in the user manual page: https://gitbrent.github.io/SpRestLib/docs/api-rest.html

Or if possible maintain this as a unique project and I believe many people will benefit from this a lot!

Again thanks a million for this great library. By the way I used "PptxGenJS" a lot. It saved me !

$expand available?

I like this library a lot, but am I able to use $expand? I have a column which is a lookup to another list - it would be great if I could use this library to expand the results - I can get $expand to work in a normal rest url but it doesn't look like $expand is a parameter option in sprLib? If it is, can you please point me to the demo page which shows how?
thanks

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.