Giter VIP home page Giter VIP logo

gitbrent / sprestlib Goto Github PK

View Code? Open in Web Editor NEW
120.0 12.0 52.0 7.07 MB

JavaScript SharePoint REST Web Services Library

Home Page: https://gitbrent.github.io/SpRestLib/

License: MIT License

HTML 42.48% CSS 11.83% JavaScript 45.70%
sharepoint sharepoint-online sharepoint-crudoperation sharepoint-2013 sharepoint-lists sharepoint-user sharepoint-rest sharepoint-webpart sharepoint-webservices sharepoint-appmodel

sprestlib's People

Contributors

csoren avatar gitbrent avatar jandos22 avatar kelvinbell avatar wmertens avatar

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 ./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

List Workflow managment

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

Thanks,

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

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

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)

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

$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

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

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 !

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

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

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 ?

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

Lib folders managing

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

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

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

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 ,[...]")
         }
     });
 }

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 :)

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.

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

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

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]

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.

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

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!

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.

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")
  );
...

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

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

'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...

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(); 
         });
      }

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.

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

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)

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

Latest npm package

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

Thank you

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

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)
});

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.