pnp / pnpjs Goto Github PK
View Code? Open in Web Editor NEWFluent JavaScript API for SharePoint and Microsoft Graph REST APIs
Home Page: https://pnp.github.io/pnpjs/
License: Other
Fluent JavaScript API for SharePoint and Microsoft Graph REST APIs
Home Page: https://pnp.github.io/pnpjs/
License: Other
Please specify what version of the library you are using: [ 1.0.3 ]
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
.
Please specify what version of the library you are using: [ 1.0.3 ]
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}`);
}
}
Please specify what version of the library you are using: [ 1.0.2 ]
Ability to add custom web part to a column and have it render ok.
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
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
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
Where can I find examples of how to use sppnpjs. I have seen one example which uses knockout (https://docs.microsoft.com/en-us/sharepoint/dev/spfx/web-parts/guidance/use-sp-pnp-js-with-spfx-web-parts), but no React examples. As a minimum, As Microsoft use React themselves, I would have thought there should be at least a React version of the above example)
Please specify what version of the library you are using: [1.0.4]
Related to SharePoint/sp-dev-docs#1693 similar to #76
Today there's no wrapper around the like endpoint of the REST API, it'd be nice to get one.
Please specify what version of the library you are using: [1.0.4]
Related to SharePoint/sp-dev-docs#1692
Today it doesn't look like pnp-js has a wrapper around the comments endpoint. It'd be nice if we could have one.
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
Please specify what version of the library you are using: [1.0.4]
ParentWeb is available as an endpoint on _api/web but not yet implemented in code
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?
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.
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.
Please specify what version of the library you are using: [latest]
Setup CI for this repo to ensure PRs are linted and basic tests run.
Please specify what version of the library you are using: [ 1.0.3 ]
Adding a new OOTB SharePoint 'People' web part and configuring via library. Trying to set this to use the 'Descriptive' layout.
Web part always defaults to 'Compact' layout
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
Please specify what version of the library you are using: [ 1.0.2 ]
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.
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.
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
Data from page after changes have been applied, order looks ok but factor for column 1 is undefined
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
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?
Please specify what version of the library you are using: [ 1.0.2 ]
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
Please specify what version of the library you are using: [ 1.0.3 ]
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.
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
.
Please specify what version of the library you are using: [ 1.0.2 ]
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
Please specify what version of the library you are using: [1.0.3]
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.
Please specify what version of the library you are using: [ 1.0.2 ]
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.
Related article: https://pnp.github.io/pnpjs/sp/client-side-pages.html
Versions tested with- 1.0.2 and 1.0.3
Expecting that the web part is added to the provisioned page
Web part is not added for some reason. The same behaviour as described here is observed: #14
`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);
});
});`
It would be nice to mention that HttpClient should be replaced by SPHttpClient
Please specify what version of the library you are using: [ 1.0.4 ]
It would be nice to be able to add multiple ordering clauses for example order by field A then field B.
Currently only seems to accept a single field with an ascending flag
@pnp/sp v. 1.0.4
Is there a way to create a new site collection with pnpjs?
Please specify what version of the library you are using: [1.0.3]
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
});
});
}
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: {}
});
});
}
Please specify what version of the library you are using: 1.0.3
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",
},
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
Create a new spfx webpart project
run below npm command
npm install @pnp/logging @pnp/common @pnp/odata @pnp/graph --save
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>`;
});
}
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);
})
Please specify what version of the library you are using: [1.0.4]
sp.profiles.clientPeoplePickerSearchUser should return data with when using odata=verbose:
Accept: 'application/json;odata=verbose'
Error:
Uncaught (in promise) SyntaxError: Unexpected token o in JSON at position 1
at JSON.parse ()
at eval (sp.es5.js:8390)
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));
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));
1.0.4
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.
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'.
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...
Please specify what version of the library you are using: [1.0.3]
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.
Config-Store
Is it required to call getConfiguration() on the provider in order to load the values from the SharePoint list.
I've tried the syntax here but it doesn't seem to work: config-store
tks.
Please specify what version of the library you are using: [ 1.0.2 ]
Load a page and check the column factors are as per the page section and column layout
When loading a page column factors always seem to default to 12
Setup a page in the browser with at least one section with multiple columns, see screenshots below
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
Code
ClientSidePage.fromFile(
this.props.spRest.web.getFileByServerRelativeUrl(
this.props.pageLocation)).then(page => { });
Please specify what version of the library you are using: [ 1.0.2 ]
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.
The web part is added but regardless of the control ordering the new web part is added to the end
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;
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.
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?
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.
[ ] 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
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"
},
});
Please specify what version of the library you are using: [ 1.0.3 ]
Ability to save/update single select user fields
I have tried numerous ways but either the value isn't respected or I get an error back
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.
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);
});
});
}
Hi
@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.
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
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
});
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!
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:
Thanks for the work you've done!
Any version I guess
When I like to use pnpjs from a CDN. I don't want to install the NPM package locally to get proper typings.
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.
Figure out best way to publish all the packages to cdnjs for each release and set it up.
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.
Please specify what version of the library you are using: [latest]
Create a sample that shows extending pnp/odata for a custom REST API endpoint secured with AzureAD.
Please specify what version of the library you are using: [ 1.0.4 ]
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
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);
});
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.
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.
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
@pnp/sp v. 1.0.4
I need to rename SharePoint folder. How can I do that?
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.
Two issues with common\util\getRandomString
(https://pnp.github.io/pnp/common/util.html):
/common
for itI 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.
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.
Please specify what version of the library you are using: [1.0.3]
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:
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:
After the regex match, I get this:
Testing out the used regex to get the HTML you see that part of it gets excluded:
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:
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.