Code Monkey home page Code Monkey logo

pnpjs's Introduction

PnPjs is a fluent JavaScript API for consuming SharePoint and Microsoft Graph REST APIs in a type-safe way. You can use it with SharePoint Framework, Nodejs, or JavaScript projects. This an open source initiative complementing existing SDKs provided by Microsoft.

Please use http://aka.ms/community/home for the latest updates around the whole Microsoft 365 and Power Platform Community(PnP) initiative.

If you are moving from v2 please review the transition guide

Getting Started

Please see the Getting Started guide in the main documentation.

Documentation

Please review the documentation for the PnPjs libraries. This site is updated with each release. If cannot find what you need, please let us know by logging an documentation request.

Authors

This project's contributors include Microsoft and community contributors. Work is done as an open source community project.

Sponsors

We want to thank everyone that has sponsored us once or on an ongoing basis. We use the money to look for fun ways to invest in the growth of PnPjs. Thank you to each and every one of you for your support and belief in what we are doing!

Thank You

KEMiCZA Sympraxis Consulting thechriskent erwinvanhunen PopWarner VesaJuvonen LauraKokkarinen ricardocarneiro andrewconnell YannickRe jansenbe tdwhite0 wobba

Code of Conduct

This project has adopted the Microsoft Open Source Code of Conduct. For more information see the Code of Conduct FAQ or contact [email protected] with any additional questions or comments.

"Sharing is Caring"

Disclaimer

THIS CODE IS PROVIDED AS IS WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.

Supportability and SLA

This library is open-source and community provided library with active community providing support for it. This is not Microsoft provided module so there's no SLA or direct support for this open-source component from Microsoft. Please report any issues using the issues list.

pnpjs's People

Contributors

0xflotus avatar aaademosu avatar ajixumuk avatar baywet avatar bcameron1231 avatar bcdmi avatar dcashpeterson avatar dependabot[bot] avatar dylanbr0wn avatar jakestanger avatar joelfmrodrigues avatar juliemturner avatar kcasamento avatar kemicza avatar koltyakov avatar michael-ra avatar michaelmaillot avatar naugtur avatar olemp avatar patrick-rodgers avatar pedro-pedrosa avatar phawrylak avatar popwarner avatar ravichandran-blog avatar sympmarc avatar taaqif avatar tavikukko avatar thechriskent avatar valerasnarbutas avatar wilecoyotegenius 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  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

pnpjs's Issues

Setup cdnjs

Figure out best way to publish all the packages to cdnjs for each release and set it up.

Make getListItemChangesSinceToken return an object

Category

  • Enhancement
  • Bug
  • Question
  • Documentation gap/issue

Version

Please specify what version of the library you are using: [1.0.3]

Expected / Desired Behavior / Question

When using the sp.web.SomeList.getListItemChangesSinceToken() call, the return value is an XML string. This is very inconvenient.

After running it through xml2js, the result is not very friendly (empty result shown for terseness):

{
  "GetListItemChangesSinceTokenResult": {
    "listitems": [
      {
        "$": {
          "MinTimeBetweenSyncs": "0",
          "RecommendedTimeBetweenSyncs": "180",
          "MaxBulkDocumentSyncSize": "500",
          "MaxRecommendedEmbeddedFileSize": "500",
          "xmlns:rs": "urn:schemas-microsoft-com:rowset"
        },
        "Changes": [
          {
            "$": {
              "LastChangeToken": "1;3;d6b498bd-346a-4fe0-800a-f2cb44510949;636569147769100000;114019856"
            }
          }
        ],
        "rs:data": [
          {
            "$": {
              "ItemCount": "0"
            }
          }
        ]
      }
    ]
  }
}

it would be much nicer if the result was simply e.g. {ChangeToken, Items, MinTimeBetweenSyncs, ...}, converting the values where appropriate (folders, files, MinTimeBetweenSyncs is an integer, …)

The library is supposed to encapsulate the communication with sharepoint, using native objects, and this xml is a leaky abstraction.

At the very least it would be nice to see some documentation on best practices on how to handle this result in JS.

Documentation: logging\index.html

I'm interested to understand how the static Logger class handles usage in multiple SPFx components on the same page.

If we have a custom LogListener that's registered via the Logger's subscribe method, what is the scope of that subscription array?

For example, if the custom LogListener is defined with data specific to the calling web part, will it's data ever be used if the Logger static class is called in another context, e.g. another SPFx web part on the same page?

I suspect this relates to how TypeScript defines singleton / static classes, and possibly bundling, so references to relevant Typescript / webpack / build doco may help.

How do I execute getNext from a PagedItemCollection as part of a batch request?

Category

  • Enhancement
  • Bug
  • Question
  • Documentation gap/issue

Version

Please specify what version of the library you are using: [ 1.0.3 ]

Expected / Desired Behavior / Question

In this scenario, I want to get items from multiple lists using inBatch but paging each request so I can return the responses and use them to get the next batch of results, i.e:

let results: any[] = [];
let responses: PagedItemCollection[] = [];
const getItems = sp.web.createBatch();

sp.web.lists.getByTitle('List 1').items.top(5).inBatch(getItems).getPaged().then(response => {
  results = results.concat(response.results);
  responses = responses.concat(response);
});
sp.web.lists.getByTitle('List 2').items.top(5).inBatch(getItems).getPaged().then(response => {
  results = results.concat(response.results);
  responses = responses.concat(response);
});

await getItems.execute();

The results and responses are collected to be returned to the calling function. My question is, how do I use the responses to batch the getNext functions from each of them into a single request? From what I can tell, PagedItemCollection does not inherit from ODataQueryable, as such inBatch is not a public member of PagedItemCollection.

Web part data version attribute wrong

Category

  • Enhancement
  • Bug
  • Question
  • Documentation gap/issue

Version

Please specify what version of the library you are using: [ 1.0.3 ]

Expected / Desired Behavior / Question

Adding a new OOTB SharePoint 'People' web part and configuring via library. Trying to set this to use the 'Descriptive' layout.

Observed Behavior

Web part always defaults to 'Compact' layout

Steps to Reproduce

Fetch web part definitions
private getClientSideWebPartDefinitions(): Promise<ClientSidePageComponent[]>
{
return new Promise<ClientSidePageComponent[]>((resolve) =>
{
resolve(this.props.spRest.web.getClientSideWebParts());
});
}

Create custom interface to replicate OOTB people web part properties, importantly setting layout to 2

private getContactWebPartProperties() :ISharePointPersonContact
{
let contactUsers:IPersonsEntity[] =[];

const ownerUser = getMetadataItem(this.state.pageMetadata, "KIRA_CP_ContentOwner");
let ownerContact:IPersonsEntity = {
  id:ownerUser.fieldValue[0].tertiaryText,
  upn:ownerUser.fieldValue[0].secondaryText,
  role:"",
  department: "",
  phone:"",
  sip:""         
};

contactUsers.push(ownerContact);

let contactWebPartProps: ISharePointPersonContact=
{
  layout:2,
  persons:contactUsers      
};

return contactWebPartProps;

}

Find web part definition and add web part setting to properties created in snippet above.

// find the definition we want, here by id
// const partDef = parts.filter(c => c.Id.toLocaleLowerCase() === "{"+webPartId.toLowerCase()+"}");
let partDef = webPartDefinitions.filter(c => c.Id.toLocaleLowerCase() === "{"+webPartId.toLowerCase()+"}");

/*if its null could be because of issue where some web parts start 
with '{' and some don't. So first try with '{' then without*/
if(partDef == null || partDef.length ==0)
{
  partDef = webPartDefinitions.filter(c => c.Id.toLocaleLowerCase() === webPartId.toLowerCase());
}

// optionally ensure you found the def
if (partDef.length < 1) {
    // we didn't find it so we throw an error
    throw new Error("Could not find the web part");
}

// create a ClientWebPart instance from the definition
let part = ClientSideWebpart.fromComponentDef(partDef[0]);
part.webPartId = webPartId;

if(webPartProperties != null)
{
  part.setProperties<any>(webPartProperties);
}

//add web part    
page.sections[sectionNumber].columns[columnNumber].addControl(part);

Code all works ok but the web part is always in compact view. I think the issue is down to the web part definition dataVersion being set to 1.0 whereas the same web part added to the page manually shows the dataVersion of 1.2, see below

Debugging window
componentdataversion

Maintenance mode settings for manually added web part
contactwebpartsettingsmanuallyadded

Add error handling for fetching pages with invalid characters

Category

  • [ x] Enhancement
  • Bug
  • Question
  • Documentation gap/issue

Version

Please specify what version of the library you are using: [ 1.0.3 ]

Expected / Desired Behavior / Question

When fetching a page if you have a ' in the page name the request fails because the REST query doesn't like the unescaped '

See sample code below. I'm able to fetch the first page but the second executes an invalid REST call due to '.

Original Code
public componentDidMount()
{
this.loadPageDetails();
}

public async loadPageDetails()
{
try
{
const page = await ClientSidePage.fromFile(this.props.spRest.web.getFileByServerRelativeUrl("/sites/HR/SitePages/page-1.aspx"));
console.log(Page 1 ${page});
const page2 = await ClientSidePage.fromFile(this.props.spRest.web.getFileByServerRelativeUrl("/sites/HR/SitePages/page'1.aspx"));
console.log(Page 2 ${page2});
}
catch(error)
{
console.log(Error ${error});
}
}

Additional checks I added in my code
public async loadPageDetails()
{
const pageUrl1:string = encodeURIComponent("/sites/HR/SitePages/page-1.aspx");
let pageUrl2:string = encodeURIComponent("/sites/HR/SitePages/page'1.aspx");
/*special case where "'" isn't covered and REST doesn't like this
so manually replace this */
pageUrl2 = pageUrl2.split("'").join("''");

try
{
  const page = await ClientSidePage.fromFile(this.props.spRest.web.getFileByServerRelativeUrl(pageUrl1));
  console.log(`Page 1 ${page}`);
  const page2 = await ClientSidePage.fromFile(this.props.spRest.web.getFileByServerRelativeUrl(pageUrl2));
  console.log(`Page 2 ${page2}`);
}
catch(error)
{
  console.log(`Error ${error}`);
}

}

Custom Client-side web part not added to a page

Related article: https://pnp.github.io/pnpjs/sp/client-side-pages.html

Category

  • Enhancement
  • [Х] Bug
  • Question
  • Documentation gap/issue

Version

Versions tested with- 1.0.2 and 1.0.3

Expected / Desired Behavior / Question

Expecting that the web part is added to the provisioned page

Observed Behavior

Web part is not added for some reason. The same behaviour as described here is observed: #14

Steps to Reproduce

`btn.addEventListener("click", async evt => {

if (this._addingNewsArticle) {
  return;
}

this._addingNewsArticle = true;
$(btn).hide();
$(".adding-article").show();

evt.preventDefault();
let guid: Guid = Guid.newGuid();
const pageName = "NewPage_" + guid + ".aspx";
const page = await sp.web.addClientSidePage(pageName, "New Page");
const partDefs: ClientSidePageComponent[] = await sp.web.getClientSideWebParts();
const imageDef: ClientSidePageComponent[] = partDefs.filter(c => c.Id === "d1d91016-032f-456d-98a4-721247c305e8");
const imagePart: ClientSideWebpart = ClientSideWebpart.fromComponentDef(imageDef[0]);
const helloWorldPoCDef: ClientSidePageComponent[] = partDefs.filter((c: ClientSidePageComponent) => { return c.Name === "HelloWorld" || c.Id === "adc1b3d1-6511-48a5-9fba-6d34e231d694"; });
let helloWorldPoCPart: ClientSideWebpart = null;
if (helloWorldPoCDef.length > 0) {
  helloWorldPoCPart = ClientSideWebpart.fromComponentDef(helloWorldPoCDef[0]);
  console.log("HelloWorld found!");
} else {
  console.warn("HelloWorld NOT found!");
}

imagePart.setProperties({
  imageSource: this.context.pageContext.site.absoluteUrl + "/SiteAssets/SitePages/1/1863068161Fendi%20case.jpg"
});

const midSection = page.addSection();
midSection.order = 1;
const top = midSection.addColumn(12);
top.order = 1;
let text = top.addControl(new ClientSideText("Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Maecenas porttitor congue massa. Fusce posuere, magna sed pulvinar ultricies, purus lectus malesuada libero, sit amet commodo magna eros quis urna."));
let image = top.addControl(imagePart);
image.order = 2;
text.order = 1;

if (helloWorldPoCPart !== null) {
  let helloWorld = top.addControl(helloWorldPoCPart);
  helloWorld.order = 3;
}

await page.save();
await page.disableComments();

page.getItem().then((item: Item) => {
  item.update({
	"ContentTypeId": myCustomNewsContentTypeId,
	"PromotedState": 2
  }).then((pageItem) => {
	console.log("done creating new page");
	window.open(this.context.pageContext.site.absoluteUrl + "/SitePages/" + pageName);
  }).catch((err: any) => {
	console.error(err);
  });
}).catch((err: any) => {
  console.error(err);
});

});`

Context / SPFetchClietn breaks when multiple requests come into ExpressJs

Hi

  • Enhancement
  • Bug
  • Question
  • Documentation gap/issue

Version

@pnp/common: "^1.0.4"
@pnp/logging: "^1.0.4"
@pnp/nodejs: "^1.0.4"
@pnp/odata: "^1.0.4"
@pnp/sp: "^1.0.4"

Maybe I am getting it wrong, but shouldn't it be possible to run concurrent requests through the express Middlewares doing something with pnp/sp?
I have a Route that catches POST requests and should ensure a list and add a couple of items. This works perfectly as long, as I only issue one request at a time:

sppnp.sp.setup({
  sp: {
    fetchClientFactory: () => {
      return new fc.SPFetchClient(siteUrl, clientId, appSecret);
    },
  },
});

sppnp.sp.web.get().then(w => {
  log.info("[START] CRM Creating metadalist in web %s", siteUrl);
  sppnp.sp.web.lists.ensure('metadata').then(ler => {
    if (ler.created) {
      let batch = sppnp.sp.web.createBatch();
      ler.list.fields.inBatch(batch).addText('DataOwner');
        batch.execute().then(_ => {
        return ler.list.items.add({
          Title: "metadata",
          DataOwner: req.body.DataOwner,
        }).then(_ => {
          log.info("[END] Created metadatalist in web %s", siteUrl);
[...]

When I call a similar Route at the same time, that does another one like this (with another siteUrl of course):

sppnp.sp.setup({
  sp: {
    fetchClientFactory: () => {
      return new fc.SPFetchClient(siteUrl2, clientId, appSecret);
    },
  },
});

sppnp.sp.web.get().then(w => {
    log.info("[START] Creating metadalist in web %s", siteUrl);
    sppnp.sp.web.lists.ensure('metadata').then(ler => {
      if (ler.created) {
        let batch = sppnp.sp.web.createBatch();
        ler.list.fields.inBatch(batch).addText('DataOwner');
        batch.execute().then(_ => {
          return ler.list.items.add({
            Title: "metadata",
            DataOwner: dataOwner,
          }).then(_ => {
            log.info("[END] Created metadatalist in web %s", siteUrl);
[...]

The first request immediately crashes, giving me a 404:

{
  "name": "O365 SiteMaker Express",
  "hostname": "CL150078",
  "pid": 12752,
  "level": 50,
  "msg": "Error in CRM Create metadalist in web ProcessHttpClientResponseException: Error making HttpClient request in queryable: [404] Not Found",
  "time": "2018-04-23T15:57:23.919Z",
  "v": 0
}

I experienced the exact same behaviour using the older pnp-js-core libraries.

Steps to Reproduce

I simply do these two requests, at the same time. The first comes from an Angular App, calling createSite / createlist in sequence. I put a setTimeout between these two, to be able to fire the second request in between this.
The second request comes from a C# cli program, that calls a different API Endpoint that does site creation and list creation one after the other.
Each of these two run separately, perfectly works.

Did I get something totally wrong or should this be possible?

best regrads,
Markus Feldmann

@types Deinition not available for pnpjs

Category

  • Enhancement
  • Bug
  • Question
  • Documentation gap/issue

Version

Any version I guess

Expected / Desired Behavior / Question

When I like to use pnpjs from a CDN. I don't want to install the NPM package locally to get proper typings.

Observed Behavior

Let's assume I like to create a new web part using SPFx and embed pnpjs as an external resource I get errors because of missing typings. After I installed the pnpjs npm module the typings was provided directly from the npm package and the build error vanished.

I case I like to use only the CDN in my project I should have the possibility to add the typings independent from the core module.

Steps to Reproduce

  • Create SPFx project
  • Add pnpjs as CND external resource
  • Import and add some test to the web part, for example, the GUID generator and start gulp serve

Unable to add multiple columns to modern page

Category

  • Enhancement
  • [ x] Bug
  • Question
  • Documentation gap/issue

Version

Please specify what version of the library you are using: [ 1.0.2 ]

Expected

Add multiple columns to a page to try and change it from a single column to a three column layout. Get a page and change the default column to have a factor of 4 then add two new columns with a factor of 4 and save the page.

Observed Behavior

The code runs and the page appears to have the correct number of columns but each new column added seems to have an order of 1. When fetching the page again and inspecting the columns the middle one has a factor of undefined whereas the other two have a factor of 4.

Steps to Reproduce

Fetch the page then run code when user selects an option in a custom UI

let columnFactor: CanvasColumnFactorType[] = [6,6];
switch(option.key)
{
case "Three":
columnFactor.length = 0
columnFactor.push(4,4,4);
break;
case "ThirdRight":
columnFactor.length = 0
columnFactor.push(8,4);
break;
}

columnFactor.forEach((column, index) =>
{
  if(index ==0)
  {
    this.page.sections[0].columns[0].factor = column;
  }
  else
  {

//this adds the new column but both new columns have the same order of 1, this is down to the code in the 'getNextOrder' function. The first column has an order of 0.5, the second column gets an order of 1 and the third also gets an order or 1 because the check says is the second column doesn't have a order of great than 1
var newColumn = this.page.sections[0].addColumn(column);
}
});

this.page.save().then(result =>
{
  console.log(result);
})

See screenshot of updated page in UI

updatepagelayout

Data from page after changes have been applied, order looks ok but factor for column 1 is undefined

columnfactoring

Unable to add custom web parts to a page

Category

  • Enhancement
  • [x ] Bug
  • Question
  • Documentation gap/issue

Version

Please specify what version of the library you are using: [ 1.0.2 ]

Expected / Desired Behavior / Question

Ability to add custom web part to a column and have it render ok.

Observed Behavior

Web part is added to the page but the web part is blank because the web part Id doesn't match the one being added by @pnp

Steps to Reproduce

I have a custom web part deployed to my tenant which has a web part id of '4a28b74a-7d88-441b-807f-cc9c38049b48'. I have checked this against the solution deployed on the tenant. I have been able to add and configure an Embed web part as per the examples but when I add my custom web parts its fails you just get a blank web parts, see attached

blankwebpart

I noticed when debugging all my custom web parts the part Ids are prefix and appended with '{' '}'. Once I create my part from the part definition the new part has these brackets. Once the part has been created from the definition if i then manually remove these and add the web part it works and the web parts are added to the page ok. I have attached a screen shot of a debug point showing the differences in the web part ids betwen the OOTB embed and one of my custom ones. Part indexes 27 and 28 are custom whereas part 2 is OOTB

webpartsettings

Remove getRandomString

Two issues with common\util\getRandomString (https://pnp.github.io/pnp/common/util.html):

  1. It seems to be copied from Stackoverflow and attribution is not given: https://stackoverflow.com/questions/1349404/generate-random-string-characters-in-javascript
  2. I can't think of any case we actually need a random string (besides testing)? If we don't generally need a random string within SharePoint, we shouldn't have a method in /common for it

I can submit a pull request removing all references to getRandomString, but I wanted to ask first whether I am missing a real world use case for it to be within the common/util lib.

Web part ordering

Category

  • Enhancement
  • [ x] Bug
  • Question
  • Documentation gap/issue

Version

Please specify what version of the library you are using: [ 1.0.2 ]

Expected

Adding a new web part to a column and i would like to be able to force this to the top of the column i.e. if there are already 2 web parts in this column i would like to push my newly added web part to the top of the list.

Observed Behavior

The web part is added but regardless of the control ordering the new web part is added to the end

Steps to Reproduce

Create a new page, set the column layout to 3 columns, add two columns to the RHS column and save and publish the page.

Run code based on the sample to fetch the page and add a new web part. Added a line of code to then get the new web part and set the order to a low value to try and force it to the top via setting order to 0.5

//was a little unsure but seem to get a column back not a web part
const newcolumn = this.page.sections[sectionNumber].columns[columnNumber].addControl(part);

//default position is new web part is added at the end so change position
this.page.sections[sectionNumber].columns[columnNumber].controls[column.controls.length-1].order = webPartIndex;

see output in debug window below
webpartordering

see output on the page after the save is done
uipositionaftersaving

Setup guidance

Category

  • Enhancement
  • Bug
  • [x ] Question
  • Documentation gap/issue

Version

Please specify what version of the library you are using: [ 1.0.2 ]

Question

I was looking over the documentation and I was slightly confused as to the samples. On the page below one example initialized the object in the init whereas another just called directly using the object. What are the differences between these approaches or do they assume the init is always done?

https://github.com/pnp/pnp/blob/dev/packages/sp/docs/index.md

Also what are the best practices around this? Should we always setup in the init? Do we need to do this in each component and sub-component or can we do it once at the top level and pass as a property?

Cheers,

Ray

@pnp/graph: Error in graph.setup

Category

  • Enhancement
  • Bug
  • Question
  • Documentation gap/issue

Version

Please specify what version of the library you are using: [1.0.3]

Expected / Desired Behavior / Question

The following setup should work in an SPFX webpart:

import { graph } from "@pnp/graph";

public onInit(): Promise<void> {

  return super.onInit().then(_ => {

    // other init code may be present

    graph.setup({
      spfxContext: this.context
    });
  });
}

Observed Behavior

I get the error can not read fetchClientFactory of undefined.

Adding an empty graph object solves the issue:

public onInit(): Promise<void> {

  return super.onInit().then(_ => {

    // other init code may be present

    graph.setup({
      spfxContext: this.context,
      graph: {}
    });
  });
}

@pnp\logging installation issues

Hi,

I'm currently migrating some code and was trying to use the storage functions in the pnp/common package.

When executing this line: npm install @pnp\logging @pnp\common --save

I get the following issue:
Could not install from "@pnp\logging" as it does not contain a package.json file.

Am I doing something wrong here?

Thanks,

Rodrigo

sp.profiles.clientPeoplePickerSearchUser does not work with odata=verbose

Category

  • Enhancement
  • [ X] Bug
  • Question
  • Documentation gap/issue

Version

Please specify what version of the library you are using: [1.0.4]

Expected / Desired Behavior / Question

sp.profiles.clientPeoplePickerSearchUser should return data with when using odata=verbose:

Accept: 'application/json;odata=verbose'

Observed Behavior

Error:

Uncaught (in promise) SyntaxError: Unexpected token o in JSON at position 1
at JSON.parse ()
at eval (sp.es5.js:8390)

Steps to Reproduce

import { sp } from '@pnp/sp';

sp.setup({ sp: { headers: { Accept: '**application/json;odata=verbose**' } } });

sp.profiles.clientPeoplePickerSearchUser({
  MaximumEntitySuggestions: 5,
  PrincipalSource: 15,
  PrincipalType: 15,
  QueryString: 'test'
}).then((entiries) => console.log(entiries));

Temporary Workaround

Use odata=minimalmetadata

import { sp } from '@pnp/sp';

sp.setup({ sp: { headers: { Accept: '**application/json;odata=minimalmetadata**' } } });

sp.profiles.clientPeoplePickerSearchUser({
  MaximumEntitySuggestions: 5,
  PrincipalSource: 15,
  PrincipalType: 15,
  QueryString: 'test'
}).then((entiries) => console.log(entiries));

Ability to delete sections, columns and controls

Category

  • [ x] Enhancement
  • Bug
  • [x ] Question
  • Documentation gap/issue

Version

Please specify what version of the library you are using: [ 1.0.2 ]

Expected / Desired Behavior / Question

Looking over the client side pages functionality there is the ability to add new sections, columns and controls but there is nothing to delete them. This would be really useful

Setup CI for this repo

Thank you for reporting an issue, suggesting an enhancement, or asking a question. We appreciate your feedback - to help the team understand your
needs please complete the below template to ensure we have the details to help. Thanks!

Please check out the Docs to see if your question is already addressed there. This will help us ensure our documentation covers the most frequent questions.

Category

  • Enhancement
  • Bug
  • Question
  • Documentation gap/issue

Version

Please specify what version of the library you are using: [latest]

Expected / Desired Behavior / Question

Setup CI for this repo to ensure PRs are linted and basic tests run.

Documentation: nodejs\sp-fetch-client.html

I was unable to fetch data from my SharePoint Online site until I added the optional "realm" parameter to my new SPFetchClient object in the setup function. The error in Chrome before adding the realm:

Uncaught (in promise)
FetchError {name: "FetchError", message: "request to https://{site name}.sharepoint.com/vti_bin/client.svc failed, reason: Failed to fetch", type: "system", errno: undefined, code: undefined, …}

I believe this parameter should be included in the example, along with instructions for finding it:

  • Navigate to "https://{site name}-admin.sharepoint.com/_layouts/15/TA_AllAppPrincipals.aspx"
  • Copy the string that follows the '@' in the App identifier column for the app that was granted permissions

Thanks for the work you've done!

Documentation: getting-started.html

I think that quite many people are using this library outside of SharePoint framework and need to specify baseURL

sp.setup({
sp: {
headers: {
Accept: "application/json;odata=verbose",
},
baseUrl: "SharePoint URL"
},
});

Typescript def for 'sp' config in @pnp/common 'setup' function is not available

Category

  • Bug

Version

1.0.4

Expected / Desired Behavior / Question

As per this guide: https://github.com/SharePoint/PnP-JS-Core/wiki/Moving-from-2.0.-to-3.0.

I should be able to migrate my 'sp' settings object to setup({sp:myObject}), but the sp type is absent.

Observed Behavior

The sp type does not work, but if I cast the setup function as any it works fine.

Error:

Argument of type '{ sp: { headers: { "Accept": string; }; }; }' is not assignable to parameter of type 'LibraryConfiguration'. Object literal may only specify known properties, and 'sp' does not exist in type 'LibraryConfiguration'.

Steps to Reproduce

This doesn't work:

import {setup} from "@pnp/common";
setup({sp:{headers:{"Accept":"application/json;odata=verbose"}}});

This does actually work:

import {setup} from "@pnp/common";
(setup as any)({sp:{headers:{"Accept":"application/json;odata=verbose"}}});

Also I'm a bit confused about how this is doing setup: https://github.com/pnp/pnpjs/blob/dev/packages/sp-addinhelpers/docs/index.md

Doesn't seem to be doing it the same way as @pnp/sp. Is this fully baked? I could log another ticket for this...

Include CamlJs in @pnp

Category

  • Enhancement
  • Bug
  • Question
  • Documentation gap/issue

Question

Is it possible to incorporate CamlJs by @andrei-markeev into @pnp packages? This is really useful library and it would be great to have it maintained as @pnp package.

Documentation: sp\webs.html

Please describe how we can improve the doc page:
import pnp from '@pnp/sp'; throws an error 'no default import'.
It should be changed to import * as pnp from '@pnp/sp';

The same for import { Web } from "@pnp/sp";
It should be like:

import * as pnp from '@pnp/sp';
//...
const web = new pnp.Web('https://contoso.sharepoint.com/sites/web');

Library version: 1.0.3

Page column factors for multiple column sections

Category

  • Enhancement
  • [x ] Bug
  • Question
  • Documentation gap/issue

Version

Please specify what version of the library you are using: [ 1.0.2 ]

Expected

Load a page and check the column factors are as per the page section and column layout

Observed Behavior

When loading a page column factors always seem to default to 12

Steps to Reproduce

Setup a page in the browser with at least one section with multiple columns, see screenshots below

three column page setup
threecolumnlayout

two column page setup
twocolumnlayout

Once the page is setup access that page via PnP code. All sections seem to have a factor of 12 regardless of page setup, see debugging details below.

three column page open via pnp
threecolumndebugging

two column page open via pnp
twocolumndebugging

Code
ClientSidePage.fromFile(
this.props.spRest.web.getFileByServerRelativeUrl(
this.props.pageLocation)).then(page => { });

Documentation: common\storage.html

Isn't this wrong?
This is current caching configuration written in docs.

import { RuntimeConfig } from "@pnp/common";

RuntimeConfig.setup({
    enableCacheExpiration: true,
    cacheExpirationIntervalMilliseconds: 1000, // optional
});

I think it should be:

import { setup } from "@pnp/common";

setup({
    enableCacheExpiration: true,
    defaultCachingTimeoutSeconds: 1000, // optional
});

Example showing creating custom lib for a custom api secured with AzureAD

Thank you for reporting an issue, suggesting an enhancement, or asking a question. We appreciate your feedback - to help the team understand your
needs please complete the below template to ensure we have the details to help. Thanks!

Please check out the Docs to see if your question is already addressed there. This will help us ensure our documentation covers the most frequent questions.

Category

  • Enhancement
  • Bug
  • Question
  • Documentation gap/issue

Version

Please specify what version of the library you are using: [latest]

Expected / Desired Behavior / Question

Create a sample that shows extending pnp/odata for a custom REST API endpoint secured with AzureAD.

ClientSideText text property does not return full HTML

Category

  • Enhancement
  • Bug
  • Question
  • Documentation gap/issue

Version

Please specify what version of the library you are using: [1.0.3]

Expected / Desired Behavior / Question

It appears that the ClientSideText part is not returning the whole HTML block. During my investigation I had the following contents created in my text web part:

screenshot 2018-03-13 12 33 59

When I try to retrieve the HTML from this web part, it only returns the table, the text in red + quote is removed.

During a debug run I saw this:

screenshot 2018-03-13 13 33 35

After the regex match, I get this:

screenshot 2018-03-13 13 43 30

Testing out the used regex to get the HTML you see that part of it gets excluded:

screenshot 2018-03-13 13 56 50

The /<div[^>]*data-sp-rte[^>]*>(.*?)<\/div>/i should be changed to /<div[^>]*data-sp-rte[^>]*>(.*?)<\/div>$/i in order to get the whole HTML block:

screenshot 2018-03-13 13 57 34

Testing against SharePoint Documentation

Category

  • Enhancement
  • Bug
  • Question
  • Documentation gap/issue

Desired Behavior

The Debugging Guide for PnPJS mentions that the settings.js file will need to be updated with key information but doesn't outline the steps for registering an app and applying necessary permissions as done here: https://github.com/SharePoint/PnP-JS-Core/wiki/Testing-Against-SharePoint

This documentation should be included here to ensure contributors can get up and running. Thanks!

Create new site collection

Category

  • Enhancement
  • Bug
  • Question
  • Documentation gap/issue

Version

@pnp/sp v. 1.0.4

Question

Is there a way to create a new site collection with pnpjs?

Method to help find controls in client-side pages

Category

  • Enhancement
  • Bug
  • Question
  • Documentation gap/issue

Version

Please specify what version of the library you are using: [ 1.0.2 ]

If you are not using the latest release, please update and see if the issue is resolved before submitting an issue.

Expected / Desired Behavior / Question

Add support for a method to find web part instances within a client-side page's collection of sections and columns. Possibilities are by ID or Title in manifest maybe?

Typescript error TS1005 during gulp build

Thank you for reporting an issue, suggesting an enhancement, or asking a question. We appreciate your feedback - to help the team understand your
needs please complete the below template to ensure we have the details to help. Thanks!

Please check out the Docs to see if your question is already addressed there. This will help us ensure our documentation covers the most frequent questions.

Category

  • Enhancement
  • Bug
  • [x ] Question
  • Documentation gap/issue

Version

Please specify what version of the library you are using: [ 1.0.3 ]

If you are not using the latest release, please update and see if the issue is resolved before submitting an issue.

Expected / Desired Behavior / Question

Im running into some trouble using this library in an spfx webpart project. After running
npm install @pnp/logging @pnp/common @pnp/odata @pnp/sp --save

And adding my import to my ts file
import {sp} from "@pnp/sp";

The project then fails to build with gulp build. Many errors saying
"Error - Typescript - node_modules@pnp\odata\src\queryable.d.ts (89,10): error TS1005: ',' expected.

Otherwise uninstalling the module my project builds and runs fine. Where do I wven start

Why is this repository in this location?

So PnPJS was just officially announced: https://dev.office.com/blogs/introducing-pnpjs-client-side-libraries-for-office365

Everything links to this repository (pnp/pnp). Why is this repository here and not in https://github.com/sharepoint? Why is there a vorpal forked repository underneath pnp? This looks unprofessional and not very clean to me as I am used to having everything PnP related in the SharePoint repository.
On the same note - why is PnPJS in "pnp/pnp" - shouldn't it at least be "PnPJS" as a repository name? This confuses new developers and old ones alike. Also it is completely unclear how PnPJS relates to the core library (https://github.com/SharePoint/PnP-JS-Core) - is it built on JS-Core? Is it relying on it?

Please move this repository to where all other Patterns and Practices repositories are and clear up dependencies so we know what is what.

Clarification: any plans for GA before March 2018

Category

[ ] Enhancement
[ ] Bug
[x] Question

There is an ongoing discussion within my team and we would like to use 3.XX Version (and contribute to pnp if some roadblocks) for a new project that we already started, but the project release date is March 2018. In order to justify the use of beta library for that project I would like to ask for if any future plans for General Availability version rough release dates. Is there a chance the PnP 3.xx is GA before March 2018?

I know that it is too early for any dates, but some sort of information might help us to decide on whether we go with 3.XX and also contribute fixes.

Cheers,
Velin

Uncaught (in promise) TypeError: Cannot read property 'fetchClientFactory' of null

Category

  • Enhancement
  • [ X] Bug
  • [X ] Question
  • Documentation gap/issue

Version

Please specify what version of the library you are using: 1.0.3

Expected / Desired Behavior / Question

I am trying to make a simple graph api call to get the groups using new pnp js framework
( i tried that with the old framework as well and i still get the same error)

Dependencies in my package. json file is as below

"dependencies": {
    "@microsoft/sp-core-library": "~1.4.0",
    "@microsoft/sp-lodash-subset": "~1.4.0",
    "@microsoft/sp-office-ui-fabric-core": "~1.4.0",
    "@microsoft/sp-webpart-base": "~1.4.0",
    "@pnp/common": "^1.0.3",
    "@pnp/graph": "^1.0.3",
    "@pnp/logging": "^1.0.3",
    "@pnp/odata": "^1.0.3",
    "@types/webpack-env": ">=1.12.1 <1.14.0",

  },

Observed Behavior

I am getting the below error when i execute the code mentioned over here
https://pnp.github.io/pnp/graph/index.html

Uncaught (in promise) TypeError: Cannot read property 'fetchClientFactory' of null
at GraphRuntimeConfigImpl.get [as fetchClientFactory] (graphlibconfig.ts:60)
at new GraphHttpClient (graphhttpclient.ts:29)
at Object.clientFactory (graphqueryable.ts:127)
at pipeline.ts:222
at new Promise ()
at Function.PipelineMethods.send (pipeline.ts:203)
at descriptor.value (pipeline.ts:252)
at next (pipeline.ts:68)
at pipeline.ts:252

Steps to Reproduce

  1. Create a new spfx webpart project

  2. run below npm command
    npm install @pnp/logging @pnp/common @pnp/odata @pnp/graph --save

  3. update the code in your webpart typescript file as below

  public onInit(): Promise<void> {
    return super.onInit().then(_ => {
      graph.setup({
        spfxContext: this.context
      });
    });
  }

public render(): void {
    graph.v1.groups.get().then(groups => {

      console.log(`Groups: ${JSON.stringify(groups, null, 4)}`);
      this.domElement.innerHTML = `Groups: <ul>${groups.map(g => `<li>${g.displayName}</li>`).join("")}</ul>`;
    });
  }

Issue exist with the Old PNP framework as well

When i tried to run the similar code using sp-pnp-js framework, i get the same error.

import pnp from "pnp";

pnp.graph.v1.groups.get().then((result)=>{
	console.log(result);
}).catch((error)=>{
	console.log(error);
})

Ability to order by multiple values when fetching list items

Category

  • [ x] Enhancement
  • Bug
  • [x ] Question
  • Documentation gap/issue

Version

Please specify what version of the library you are using: [ 1.0.4 ]

Expected / Desired Behavior / Question

It would be nice to be able to add multiple ordering clauses for example order by field A then field B.

Observed Behavior

Currently only seems to accept a single field with an ascending flag

Issue saving a user field value

Category

  • Enhancement
  • [x ] Bug
  • Question
  • Documentation gap/issue

Version

Please specify what version of the library you are using: [ 1.0.3 ]

Expected / Desired Behavior / Question

Ability to save/update single select user fields

Observed Behavior

I have tried numerous ways but either the value isn't respected or I get an error back

Steps to Reproduce

Use code to fetch the page then from the page fetch the list item. Once i have the list item batch up an array of ListItemFormUpdateValue objects. This all works fine for boolean, taxonomy, date and SLOT but I can't get it to work for user fields.

I found some documentation around updating user fields at the link below but this doesn't seem to work
https://github.com/pnp/pnp/blob/dev/packages/sp/docs/items.md

I can fetch the value by using column name with 'Id', see below.
image

If I try and update using 'KIRA_CP_ContentOwnerId' it gives me the standard SP error saying the field can't be found. If I try and use the actual field internal name 'KIRA_CP_ContentOwner' it never sets the value. I'm using the 'validateUpdateListItem' function on the list item

public savePageMetadata(pageListItem:Item): Promise
{
return new Promise((resolve) =>
{
//my list of objects to pass to the function
let fieldValues = this.createItemUpdateValues();
console.log(fieldValues);
pageListItem.validateUpdateListItem(fieldValues).then((updateResult) =>
{
//check if there are any errors
let fieldErrors = updateResult.filter(itemUpdate => itemUpdate.HasException);
//if we have errors
if(fieldErrors != null && fieldErrors.length>0)
{
console.log("savePageMetadata Errors");
console.log(fieldErrors);
}
else
{
console.log("savePageMetadata ok");
//otherwise ok
resolve();
}
}).catch((error) =>
{
console.log(error);
});
});
}

adalfetchclient: Type definition is not found

Category

  • Enhancement
  • Bug
  • Question
  • Documentation gap/issue

Version

Please specify what version of the library you are using: [1.0.3]

Expected / Desired Behavior / Question

Typings reference for types.d.ts is not found. When transpiling TS to JS I get the following error:

node_modules/@pnp/nodejs/src/net/adalfetchclient.d.ts(1,22): error TS6053: File '/Users/user/project/packages/nodejs/src/net/types.d.ts' not found.

screenshot 2018-03-12 19 38 10

Enumerable Search Result Properties

Category

  • Enhancement
  • Bug
  • Question
  • Documentation gap/issue

Version

1.0.2

Can we make it so that the properties surfaced through the search results are returned as enumerable (see: https://github.com/pnp/pnp/blob/dev/packages/sp/src/search.ts#L372, currently set to false)? I'm trying to pass through my search results object to a React component using a spread operator, but because they are not enumerable they do not get passed through. It's a bit of a pain, because it means I either need to change the way data is passed through my React/Redux flow, or craft a copy of the results object myself before passing it through.

Is there value in setting them to non-enumerable that I am missing?

Ability to determine if comments are enabled

Category

  • [ x] Enhancement
  • Bug
  • [x ] Question
  • Documentation gap/issue

Version

Please specify what version of the library you are using: [ 1.0.2 ]

Question

There are various methods for updating and interacting with modern pages, including the ability to enable and disable comments, however I can't see a way to check if comments are enabled or not. In my case I'm providing a wrapper UI to allow users to toggle comments on or off and I would like to be able to check what the current status of the page is first. I've looked but I can't see any way to do this.

How to rename SharePoint folder with pnp/sp?

Category

  • Enhancement
  • Bug
  • Question
  • Documentation gap/issue

Version

@pnp/sp v. 1.0.4

Question

I need to rename SharePoint folder. How can I do that?

Observed Behavior

I looked into Folder class source code and found update() function. Tried to use it like this:

sp.web.getFolderByServerRelativePath('/my/path/here').update({Name: 'newName'})

Request is getting passed, but it doesn't affect the folder name.

Thank you in advance for the help.

parentWeb endpoint missing

Category

  • [*] Enhancement
  • Bug
  • Question
  • Documentation gap/issue

Version

Please specify what version of the library you are using: [1.0.4]

Expected / Desired Behavior / Question

ParentWeb is available as an endpoint on _api/web but not yet implemented in code

Observed Behavior

endpoint is missing from Web object

Is this endpoint slated to be added anytime soon?

If not, is it possible to use whatever http fetcher pnp uses under the hood to cheekily call web/parentWeb and cast the returned data into a pnp Web object?

nodejs + getPaged / getNext [403] Forbidden with custom header (ADAL)

Category

  • Enhancement
  • Bug
  • Question
  • Documentation gap/issue

Version

Please specify what version of the library you are using: [ 1.0.3 ]

Expected / Desired Behavior / Question

Running the getPaged method, then getNext will throw a [403] Forbidden when using ADAL (custom Authorization header).
I suspect it could be because headers are not copied over in getNext.

Steps to Reproduce

This is my demo-code

const pnp = require('@pnp/sp');
const fetch = require('node-fetch');

const settings = require('./settings.json');

global.fetch = fetch;
global.Request = fetch.Request;
global.Headers = fetch.Headers;

(async () => {
  const sp = pnp.sp.configure({
    headers: {
      Authorization: `Bearer ${settings.token}`
    }
  }, settings.url);

  let page = await sp.web.getList(settings.list).items.select('Id').getPaged();
  // This throws a 403
  await page.getNext();
})();

settings.json has the token hard coded (for testing purposes), a (absolute) URL to the SharePoint Online SPWeb and a server relative URL to a list.

Note, this also affects getAll, since this method uses getPaged.

Site name when working with batch

Category

  • Enhancement
  • [x ] Bug
  • Question
  • Documentation gap/issue

Version

Please specify what version of the library you are using: [ 1.0.4 ]

Expected / Desired Behavior / Question

I was working with batching for updating lists as per documentation at link below and expected to be able to batch add/update items

https://github.com/pnp/pnpjs/blob/37f54d4ac5544315e65579d8850f2b4b1ab94fe5/packages/sp/docs/items.md

Observed Behavior

I kept getting an error back from each request with the message below.

Error: Error making HttpClient request in queryable: [400] Bad Request

Eventually after poking around I discovered it was because when creating my pnp web object the URL I was using didn't 100% match the site name. I was able to use the web object to query the list to get list items or the entity name but it broke when it came to using the batch request, see examples below based on a site called HR-Dev. The only difference is a lower case 'd' in the Url

Broken Example
const webUrl:string = "https://tenantname.sharepoint.com/sites/HR-dev";
const listName:string = "Test List"
const rootWeb = new pnp.Web(webUrl);
const list = rootWeb.lists.getByTitle(listName);
//get entity name
const listEntityName = await list.getListItemEntityTypeFullName();

  let batch = rootWeb.createBatch();

  const numberOfItems:number = 10;

  for(var index=0;index<numberOfItems;index++)
  {            
    list.items.inBatch(batch).add(
    { 
        Title: `Test ${index}`
    }, 
    listEntityName).then(b => 
    {
        console.log(b);
    }).catch((e) =>
    {            
        console.log(e);
    });
  }
  
  batch.execute().then(d => 
  {
      console.log(d);
      console.log("Done");
  }).catch((e) =>
  {          
      console.log(e);
  });

Working Example
const webUrl:string = "https://tenantname.sharepoint.com/sites/HR-Dev";
const listName:string = "Test List"
const rootWeb = new pnp.Web(webUrl);
const list = rootWeb.lists.getByTitle(listName);
//get entity name
const listEntityName = await list.getListItemEntityTypeFullName();

  let batch = rootWeb.createBatch();

  const numberOfItems:number = 10;

  for(var index=0;index<numberOfItems;index++)
  {            
    list.items.inBatch(batch).add(
    { 
        Title: `Test ${index}`
    }, 
    listEntityName).then(b => 
    {
        console.log(b);
    }).catch((e) =>
    {            
        console.log(e);
    });
  }
  
  batch.execute().then(d => 
  {
      console.log(d);
      console.log("Done");
  }).catch((e) =>
  {          
      console.log(e);
  });

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.