Add @select and @expand decorators in PnP JS Core sample and update package json versions (#252)

* update package versions taxonomypicker

* update package json versions react-async-await-sp-pnp-js

* PnP JS Core with select and expand decorators SPFx sample

* update readme property decorators
This commit is contained in:
José Quinto 2017-07-21 19:00:52 +01:00 committed by Vesa Juvonen
parent d44be59fbe
commit b8405c728a
38 changed files with 1246 additions and 35 deletions

View File

@ -6,23 +6,22 @@
"node": ">=0.10.0"
},
"dependencies": {
"@microsoft/sp-client-base": "~1.0.0",
"@microsoft/sp-core-library": "~1.0.0",
"@microsoft/sp-webpart-base": "~1.0.0",
"@types/react": "0.14.46",
"@types/react-addons-shallow-compare": "0.14.17",
"@types/react-addons-test-utils": "0.14.15",
"@types/react-addons-update": "0.14.14",
"@types/react-dom": "0.14.18",
"@microsoft/sp-core-library": "~1.1.0",
"@microsoft/sp-webpart-base": "~1.1.1",
"@types/webpack-env": ">=1.12.1 <1.14.0",
"react": "15.5.4",
"react-dom": "15.5.4",
"sp-pnp-js": "^2.0.4"
"react": "15.4.2",
"react-dom": "15.4.2",
"@types/react": "0.14.46",
"@types/react-dom": "0.14.18",
"@types/react-addons-shallow-compare": "0.14.17",
"@types/react-addons-update": "0.14.14",
"@types/react-addons-test-utils": "0.14.15",
"sp-pnp-js": "2.0.6"
},
"devDependencies": {
"@microsoft/sp-build-web": "~1.0.1",
"@microsoft/sp-module-interfaces": "~1.0.0",
"@microsoft/sp-webpart-workbench": "~1.0.0",
"@microsoft/sp-build-web": "~1.1.0",
"@microsoft/sp-module-interfaces": "~1.1.0",
"@microsoft/sp-webpart-workbench": "~1.1.0",
"gulp": "~3.9.1",
"@types/chai": ">=3.4.34 <3.6.0",
"@types/mocha": ">=2.2.33 <2.6.0"

View File

@ -6,6 +6,7 @@
"jsx": "react",
"declaration": true,
"sourceMap": true,
"experimentalDecorators": true,
"types": [
"es6-promise",
"es6-collections",

View File

@ -0,0 +1,25 @@
# EditorConfig helps developers define and maintain consistent
# coding styles between different editors and IDEs
# editorconfig.org
root = true
[*]
# change these settings to your own preference
indent_style = space
indent_size = 2
# we recommend you to keep these unchanged
end_of_line = lf
charset = utf-8
trim_trailing_whitespace = true
insert_final_newline = true
[*.md]
trim_trailing_whitespace = false
[{package,bower}.json]
indent_style = space
indent_size = 2

View File

@ -0,0 +1 @@
* text=auto

View File

@ -0,0 +1,32 @@
# Logs
logs
*.log
npm-debug.log*
# Dependency directories
node_modules
# Build generated files
dist
lib
solution
temp
*.sppkg
# Coverage directory used by tools like istanbul
coverage
# OSX
.DS_Store
# Visual Studio files
.ntvs_analysis.dat
.vs
bin
obj
# Resx Generated Code
*.resx.ts
# Styles Generated Code
*.scss.ts

View File

@ -0,0 +1,14 @@
# Folders
.vscode
coverage
node_modules
sharepoint
src
temp
# Files
*.csproj
.git*
.yo-rc.json
gulpfile.js
tsconfig.json

View File

@ -0,0 +1,8 @@
{
"@microsoft/generator-sharepoint": {
"libraryName": "react-sp-pnp-js-property-decorators",
"framework": "react",
"version": "1.0.2",
"libraryId": "a843ff35-51f4-4e36-99f7-f077a93f8d37"
}
}

View File

@ -0,0 +1,52 @@
# React sample showing the use of PnP JS Core custom objects with @select and @expand decorators
## Summary
This webpart demonstrates how to use [PnP JS Core](https://github.com/SharePoint/PnP-JS-Core) Custom Objects with @select and @expand TypeScript decorators.
If you are going to use PnP JS Core library and you've plans for [extending it with Custom Business Objects](https://github.com/SharePoint/PnP-JS-Core/wiki/Extending-with-Custom-Business-Objects), then this project will show you some best practices.
You can also find more information in the [blog series about working with Custom Business Objects, Parsers and TypeScript Decorators in PnP JS Core](https://blog.josequinto.com/2017/05/19/why-do-we-should-use-custom-business-objects-models-in-pnp-js-core/)
## Used SharePoint Framework Version
![drop](https://img.shields.io/badge/drop-GA-green.svg)
## Applies to
* [SharePoint Framework](http://dev.office.com/sharepoint/docs/spfx/sharepoint-framework-overview)
* [Office 365 developer tenant](http://dev.office.com/sharepoint/docs/spfx/set-up-your-developer-tenant)
## Solution
Solution|Author(s)
--------|---------
react-sp-pnp-js-property-decorators | Jose Quinto ([@jquintozamora](https://twitter.com/jquintozamora) , [blog.josequinto.com](https://blog.josequinto.com))
## Version history
Version|Date|Comments
-------|----|--------
1.0|July 2, 2017|Initial release
## 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.**
---
## Minimal Path to Awesome
- clone this repo
- `$ npm i`
- `$ gulp trust-dev-cert`
- `$ gulp serve `
### Local Mode
A browser in local mode (localhost) will be opened.
https://localhost:4321/temp/workbench.html
### SharePoint Mode
If you want to try on a real environment, open:
https://your-domain.sharepoint.com/_layouts/15/workbench.aspx
<img src="https://telemetry.sharepointpnp.com/sp-dev-fx-webparts/samples/react-sp-pnp-js-property-decorators" />

View File

@ -0,0 +1,13 @@
{
"entries": [
{
"entry": "./lib/webparts/customBusinessObjectsPnPJs/CustomBusinessObjectsPnPJsWebPart.js",
"manifest": "./src/webparts/customBusinessObjectsPnPJs/CustomBusinessObjectsPnPJsWebPart.manifest.json",
"outputPath": "./dist/custom-business-objects-pn-p-js.bundle.js"
}
],
"externals": {},
"localizedResources": {
"customBusinessObjectsPnPJsStrings": "webparts/customBusinessObjectsPnPJs/loc/{locale}.js"
}
}

View File

@ -0,0 +1,3 @@
{
"deployCdnPath": "temp/deploy"
}

View File

@ -0,0 +1,6 @@
{
"workingDir": "./temp/deploy/",
"account": "<!-- STORAGE ACCOUNT NAME -->",
"container": "react-sp-pnp-js-property-decorators",
"accessKey": "<!-- ACCESS KEY -->"
}

View File

@ -0,0 +1,10 @@
{
"solution": {
"name": "react-sp-pnp-js-property-decorators-client-side-solution",
"id": "a843ff35-51f4-4e36-99f7-f077a93f8d37",
"version": "1.0.0.0"
},
"paths": {
"zippedPackage": "solution/react-sp-pnp-js-property-decorators.sppkg"
}
}

View File

@ -0,0 +1,9 @@
{
"port": 4321,
"initialPage": "https://localhost:5432/workbench",
"https": true,
"api": {
"port": 5432,
"entryPath": "node_modules/@microsoft/sp-webpart-workbench/lib/api/"
}
}

View File

@ -0,0 +1,45 @@
{
// Display errors as warnings
"displayAsWarning": true,
// The TSLint task may have been configured with several custom lint rules
// before this config file is read (for example lint rules from the tslint-microsoft-contrib
// project). If true, this flag will deactivate any of these rules.
"removeExistingRules": true,
// When true, the TSLint task is configured with some default TSLint "rules.":
"useDefaultConfigAsBase": false,
// Since removeExistingRules=true and useDefaultConfigAsBase=false, there will be no lint rules
// which are active, other than the list of rules below.
"lintConfig": {
// Opt-in to Lint rules which help to eliminate bugs in JavaScript
"rules": {
"class-name": false,
"export-name": false,
"forin": false,
"label-position": false,
"member-access": true,
"no-arg": false,
"no-console": false,
"no-construct": false,
"no-duplicate-case": true,
"no-duplicate-variable": true,
"no-eval": false,
"no-function-expression": true,
"no-internal-module": true,
"no-shadowed-variable": true,
"no-switch-case-fall-through": true,
"no-unnecessary-semicolons": true,
"no-unused-expression": true,
"no-unused-imports": true,
"no-use-before-declare": true,
"no-with-statement": true,
"semicolon": true,
"trailing-comma": false,
"typedef": false,
"typedef-whitespace": false,
"use-named-parameter": true,
"valid-typeof": true,
"variable-name": false,
"whitespace": false
}
}
}

View File

@ -0,0 +1,3 @@
{
"cdnBasePath": "<!-- PATH TO CDN -->"
}

View File

@ -0,0 +1,6 @@
'use strict';
const gulp = require('gulp');
const build = require('@microsoft/sp-build-web');
build.initialize(gulp);

View File

@ -0,0 +1,34 @@
{
"name": "react-sp-pnp-js-property-decorators",
"version": "0.0.1",
"private": true,
"engines": {
"node": ">=0.10.0"
},
"dependencies": {
"@microsoft/sp-core-library": "~1.1.0",
"@microsoft/sp-webpart-base": "~1.1.1",
"@types/webpack-env": ">=1.12.1 <1.14.0",
"react": "15.4.2",
"react-dom": "15.4.2",
"@types/react": "0.14.46",
"@types/react-dom": "0.14.18",
"@types/react-addons-shallow-compare": "0.14.17",
"@types/react-addons-update": "0.14.14",
"@types/react-addons-test-utils": "0.14.15",
"sp-pnp-js": "2.0.6"
},
"devDependencies": {
"@microsoft/sp-build-web": "~1.1.0",
"@microsoft/sp-module-interfaces": "~1.1.0",
"@microsoft/sp-webpart-workbench": "~1.1.0",
"gulp": "~3.9.1",
"@types/chai": ">=3.4.34 <3.6.0",
"@types/mocha": ">=2.2.33 <2.6.0"
},
"scripts": {
"build": "gulp bundle",
"clean": "gulp clean",
"test": "gulp test"
}
}

View File

@ -0,0 +1,20 @@
{
"$schema": "../../../node_modules/@microsoft/sp-module-interfaces/lib/manifestSchemas/jsonSchemas/clientSideComponentManifestSchema.json",
"id": "6e2025fd-9c31-4bc4-b217-76019a4fdd02",
"alias": "CustomBusinessObjectsPnPJsWebPart",
"componentType": "WebPart",
"version": "0.0.1",
"manifestVersion": 2,
"preconfiguredEntries": [{
"groupId": "6e2025fd-9c31-4bc4-b217-76019a4fdd02",
"group": { "default": "Under Development" },
"title": { "default": "customBusinessObjectsPnPJs" },
"description": { "default": "customBusinessObjectsPnPJs description" },
"officeFabricIconFontName": "Page",
"properties": {
"description": "customBusinessObjectsPnPJs"
}
}]
}

View File

@ -0,0 +1,74 @@
import * as React from 'react';
import * as ReactDom from 'react-dom';
import { Version } from '@microsoft/sp-core-library';
import {
BaseClientSideWebPart,
IPropertyPaneConfiguration,
PropertyPaneTextField
} from '@microsoft/sp-webpart-base';
import * as strings from 'customBusinessObjectsPnPJsStrings';
import CustomBusinessObjectsPnPJs from './components/CustomBusinessObjectsPnPJs';
import { ICustomBusinessObjectsPnPJsProps } from './components/ICustomBusinessObjectsPnPJsProps';
import { ICustomBusinessObjectsPnPJsWebPartProps } from './ICustomBusinessObjectsPnPJsWebPartProps';
import pnp, {
Logger,
ConsoleListener,
LogLevel
} from "sp-pnp-js";
export default class CustomBusinessObjectsPnPJsWebPart extends BaseClientSideWebPart<ICustomBusinessObjectsPnPJsWebPartProps> {
// // https://github.com/SharePoint/PnP-JS-Core/wiki/Using-sp-pnp-js-in-SharePoint-Framework
public onInit(): Promise<void> {
return super.onInit().then(_ => {
// establish SPFx context
pnp.setup({
spfxContext: this.context
});
// subscribe a listener
Logger.subscribe(new ConsoleListener());
// set the active log level
Logger.activeLogLevel = LogLevel.Warning;
});
}
public render(): void {
const element: React.ReactElement<ICustomBusinessObjectsPnPJsProps> = React.createElement(
CustomBusinessObjectsPnPJs,
{
description: this.properties.description
}
);
ReactDom.render(element, this.domElement);
}
protected get dataVersion(): Version {
return Version.parse('1.0');
}
protected getPropertyPaneConfiguration(): IPropertyPaneConfiguration {
return {
pages: [
{
header: {
description: strings.PropertyPaneDescription
},
groups: [
{
groupName: strings.BasicGroupName,
groupFields: [
PropertyPaneTextField('description', {
label: strings.DescriptionFieldLabel
})
]
}
]
}
]
};
}
}

View File

@ -0,0 +1,3 @@
export interface ICustomBusinessObjectsPnPJsWebPartProps {
description: string;
}

View File

@ -0,0 +1,28 @@
.container {
max-width: 700px;
margin: 0px auto;
box-shadow: 0 2px 4px 0 rgba(0, 0, 0, 0.2), 0 25px 50px 0 rgba(0, 0, 0, 0.1);
}
.header {
border-bottom: 1px solid rgba(255, 255, 255, 0.5);
margin-top: 10px;
}
.row {
padding: 5px;
}
.left {
float: left;
width: 80%;
}
.right {
float: right;
width: 20%;
text-align: center;
}
.clear {
clear: both;
}

View File

@ -0,0 +1,396 @@
import * as React from "react";
import styles from "./CustomBusinessObjectsPnPJs.module.scss";
// import models
import { MyDocument } from "../model/MyDocument";
import { MyDocumentCollection } from "../model/MyDocumentCollection";
// initially we import our custom model which extends from Item class from PnP JS Core
import { MyItem } from "../model/MyItem";
// import custom parsers
import { SelectDecoratorsParser, SelectDecoratorsArrayParser } from "../parser/SelectDecoratorsParsers";
// import pnp and pnp logging system
import pnp from "sp-pnp-js";
import { ICustomBusinessObjectsPnPJsProps } from "./ICustomBusinessObjectsPnPJsProps";
import { ICustomBusinessObjectsPnPJsState } from "./ICustomBusinessObjectsPnPJsState";
export default class CustomBusinessObjectsPnPJs extends React.Component<ICustomBusinessObjectsPnPJsProps, ICustomBusinessObjectsPnPJsState> {
constructor(props: ICustomBusinessObjectsPnPJsProps) {
super(props);
// set initial state
this.state = {
myDocuments: [],
errors: []
};
// normally we don't need to bind the functions as we use arrow functions and do automatically the bing
// http://bit.ly/reactArrowFunction
// but using Async function we can't convert it into arrow function, so we do the binding here
this._loadPnPJsLibrary.bind(this);
}
public render(): React.ReactElement<ICustomBusinessObjectsPnPJsProps> {
return (
<div className={styles.container}>
<div className={"ms-Grid-row ms-bgColor-themeDark ms-fontColor-white " + styles.row}>
<div className="ms-Grid-col ms-u-lg10 ms-u-xl8 ms-u-xlPush2 ms-u-lgPush1">
<span className="ms-font-xl ms-fontColor-white">Welcome to Custom Business Objects, Decorators and Renders Demo!</span>
<div>
{this._gerErrors()}
</div>
<p className="ms-font-l ms-fontColor-white">List of documents:</p>
<div>
<div className={styles.row}>
<div className={styles.left}>Name</div>
<div className={styles.right}>Size (KB)</div>
<div className={styles.clear + " " + styles.header}></div>
</div>
{this.state.myDocuments.map((item) => {
return (
<div className={styles.row}>
<div className={styles.left}>{item.Name}</div>
<div className={styles.right}>{(item.Size / 1024).toFixed(2)}</div>
<div className={styles.clear}></div>
</div>
);
})}
</div>
</div>
</div>
</div >
);
}
public componentDidMount(): void {
const libraryName: string = "Documents";
console.log("libraryName: " + libraryName);
this._loadPnPJsLibrary(libraryName);
}
private async _loadPnPJsLibrary(libraryName: string): Promise<void> {
console.log("loadPnPJsLibrary");
try {
console.log("######################################");
console.log("# PnP JS Core without custom objects #");
console.log("######################################");
const plainItemAsAny: any = await pnp.sp
.web
.lists
.getByTitle("PnPJSSample")
.items
.getById(1)
.select("ID", "Title", "Category", "Quantity")
.get();
console.log(plainItemAsAny);
// plainItemAsAny hasn't intellisense neither type checking using TypeScript
console.log(plainItemAsAny.Title); // compiler: ok (any object), result: Fig
console.log(plainItemAsAny.title); // compiler: ok (any object), result: undefined (posible mistake)
console.log(plainItemAsAny.otherProp); // compiler: ok (any object), result: undefined (posible mistake not having type check)
// from TypeScript 1.6 we can use as operator like the default way to cast inside .tsx file
// (removing any ambiguity between JSX expressions and the TypeScript prefix cast operator)
// https://www.typescriptlang.org/docs/handbook/release-notes/typescript-1-6.html
// a workarround for having intellisense and type checking is using as operator with the specific type
const plainItemAsObject = plainItemAsAny as { ID: string, Title: string, Category: string, Quantity: number };
console.log(plainItemAsObject.Category); // compiler: ok, result: Fruit
// console.log(plainItemAsObject.otherProp); // compiler: error because otherProp isn't on the defined type
console.log(plainItemAsObject);
console.log("######################################");
console.log("# PnP JS Core WITH custom objects #");
console.log("######################################");
const itemCustomObject: MyItem = await pnp.sp
.web
.lists
.getByTitle("PnPJSSample")
.items
.getById(1)
// we don't need the select here as we have already implemented on our custom model
// .select("ID", "Title", "Category", "Quantity")
// as("model") means PnP JS Core will use the returned object from here and we can use it later using method chaining
.as(MyItem)
.get();
console.log(itemCustomObject);
// itemCustomObject has intellisense and type checking using TypeScript
console.log(itemCustomObject.Title); // compiler: ok (any object), result: Fig
// console.log(itemCustomObject.title); // compiler: error
// console.log(itemCustomObject.otherProp); // compiler: error
console.log(itemCustomObject);
console.log("#############################");
console.log("# Query only one document #");
console.log("#############################");
console.log("*************************************************************");
console.log("*** One document selecting all properties");
console.log("*************************************************************");
const myDocument: any = await pnp.sp
.web
.lists
.getByTitle(libraryName)
.items
.getById(1)
.get();
// query all item's properties
console.log(myDocument);
console.log("*************************************************************");
console.log("*** One document with getAs<MyDocument>()");
console.log("*************************************************************");
const myDocumentGetAs: MyDocument = await pnp.sp
.web
.lists
.getByTitle(libraryName)
.items
.getById(1)
.getAs<MyDocument>();
// query all item's properties, exactly the same result as before
console.log(myDocumentGetAs);
console.log("*************************************************************");
console.log("*** One document using select, expand and get()");
console.log("*************************************************************");
const myDocumentWithSelectExpandGet: any = await pnp.sp
.web
.lists
.getByTitle(libraryName)
.items
.getById(1)
.select("Title", "FileLeafRef", "File/Length")
.expand("File/Length")
.get();
// query only selected properties, but ideally should
// get the props from our custom object
console.log(myDocumentWithSelectExpandGet);
console.log("*************************************************************");
console.log("*** One document using select, expand and get() with MyDocument Custom Parser");
console.log("*************************************************************");
const myDocumentWithSelectExpandGetParser: any = await pnp.sp
.web
.lists
.getByTitle(libraryName)
.items
.getById(1)
.select("Title", "FileLeafRef", "File/Length")
.expand("File/Length")
.get(new SelectDecoratorsParser<MyDocument>(MyDocument));
// query only selected properties, but ideally should
// get the props from our custom object
console.log(myDocumentWithSelectExpandGetParser);
console.log("*************************************************************");
console.log("*** One document using select, expand and getAs<MyDocument>()");
console.log("*************************************************************");
const myDocumentWithSelectExpandGetAs: MyDocument = await pnp.sp
.web
.lists
.getByTitle(libraryName)
.items
.getById(1)
.select("Title", "FileLeafRef", "File/Length")
.expand("File/Length")
.getAs<MyDocument>();
// query only selected properties, but ideally should
// get the props from our custom object
console.log(myDocumentWithSelectExpandGetAs);
console.log("*************************************************************");
console.log("*** One document using as(MyDocument) and get() with Default Parser");
console.log("*************************************************************");
const myDocumentWithCustomObjectGet: MyDocument = await pnp.sp
.web
.lists
.getByTitle(libraryName)
.items
.getById(1)
// using as("Model") overrides select and expand queries
.as(MyDocument)
.get();
// query only selected properties, using our Custom Model properties
// but only those that have the proper @select and @expand decorators
console.log(myDocumentWithCustomObjectGet);
console.log("*************************************************************");
console.log("*** One document using as(MyDocument) and getAs<MyDocument>()");
console.log("*************************************************************");
const myDocumentWithCustomObjectGetAs: MyDocument = await pnp.sp
.web
.lists
.getByTitle(libraryName)
.items
.getById(1)
// using as("Model") overrides select and expand queries
.as(MyDocument)
// it's using getAs from MyDocument which has SelectDecoratorsParser
.getAs<MyDocument>();
// query only selected properties, using our Custom Model properties
// but only those that have the proper @select and @expand decorators
console.log(myDocumentWithCustomObjectGetAs);
console.log("###############################");
console.log("# Query document collection #");
console.log("###############################");
console.log("*************************************************************");
console.log("*** Document Collection selecting all properties");
console.log("*************************************************************");
const myDocumentCollection: any = await pnp.sp
.web
.lists
.getByTitle(libraryName)
.items
.get();
console.log(myDocumentCollection);
console.log("*************************************************************");
console.log("*** Document Collection using as(MyDocument) and get()");
console.log("*************************************************************");
const myDocumentsWithCustomObjectAsDocumentGet: MyDocument[] = await pnp.sp
.web
.lists
.getByTitle(libraryName)
.items
// using as("Model") overrides select and expand queries
// that´s where the MAGIC happends as even if we are using
// items (item collection) it will use the proper query
.as(MyDocument)
.get();
console.log(myDocumentsWithCustomObjectAsDocumentGet);
console.log("*************************************************************");
console.log("*** Document Collection using as(MyDocument) and getAs<MyDocument>()");
console.log("*************************************************************");
const myDocumentsWithCustomObjectAsDocument: MyDocument[] = await pnp.sp
.web
.lists
.getByTitle(libraryName)
.items
// *Note that the downside using this approach is after .as(MyDocument)
// we can't use QueryableCollection methods as the type is transformed
// to Item instead of Items
.as(MyDocument)
.getAs<MyDocument[]>();
// query only selected properties, using our Custom Model properties
// but only those that have the proper @select and @expand decorators
console.log(myDocumentsWithCustomObjectAsDocument);
console.log("*************************************************************");
console.log("*** Document Collection using as(MyDocumentCollection) and get()");
console.log("*************************************************************");
const myDocumentsWithCustomObjectAsDocuments: MyDocument[] = await pnp.sp
.web
.lists
.getByTitle(libraryName)
.items
// using as("Model") overrides select and expand queries
.as(MyDocumentCollection)
.get();
// query only selected properties, using our Custom Model properties
// but only those that have the proper @select and @expand decorators
console.log(myDocumentsWithCustomObjectAsDocuments);
console.log("*************************************************************");
console.log("*** Document Collection using as(MyDocumentCollection) and getAs<MyDocumentCollection>()");
console.log("*************************************************************");
const myDocumentsWithCustomObjectAsDocumentsGetAs: any = await pnp.sp
.web
.lists
.getByTitle(libraryName)
.items
// using as("Model") overrides select and expand queries
.as(MyDocumentCollection)
.getAs<MyDocumentCollection>();
// query only selected properties, using our Custom Model properties
// but only those that have the proper @select and @expand decorators
console.log(myDocumentsWithCustomObjectAsDocumentsGetAs);
console.log("*************************************************************");
console.log("*** Document Collection using as(MyDocumentCollection) and getAsMyDocument()");
console.log("*************************************************************");
const myDocumentsWithCustomObjectAsDocumentsGetAsMyDocument: any = await pnp.sp
.web
.lists
.getByTitle(libraryName)
.items
// using as("Model") overrides select and expand queries
.as(MyDocumentCollection)
.getAsMyDocument();
// query only selected properties, using our Custom Model properties
// but only those that have the proper @select and @expand decorators
console.log(myDocumentsWithCustomObjectAsDocumentsGetAsMyDocument);
console.log("*************************************************************");
console.log("*** Document Collection using as(MyDocumentCollection) and get() with Custom Array Parser returning only properties with @select");
console.log("*************************************************************");
const myDocumentsWithCustomObjectAsDocumentsGetParserJustSelect: any[] = await pnp.sp
.web
.lists
.getByTitle(libraryName)
.items
// using as("Model") overrides select and expand queries
.as(MyDocumentCollection)
.get(new SelectDecoratorsArrayParser<MyDocument>(MyDocument, true));
// query only selected properties, using our Custom Model properties
// but only those that have the proper @select and @expand decorators
console.log(myDocumentsWithCustomObjectAsDocumentsGetParserJustSelect);
console.log("*************************************************************");
console.log("*** Document Collection using as(MyDocumentCollection) and get() with Custom Array Parser");
console.log("*************************************************************");
const myDocumentsWithCustomObjectAsDocumentsGetParser: any[] = await pnp.sp
.web
.lists
.getByTitle(libraryName)
.items
// using as("Model") overrides select and expand queries
.as(MyDocumentCollection)
.skip(1)
// this renderer mix the properties and do the match between the props names and the selected if they have /
.get(new SelectDecoratorsArrayParser<MyDocument>(MyDocument));
// query only selected properties, using our Custom Model properties
// but only those that have the proper @select and @expand decorators
console.log(myDocumentsWithCustomObjectAsDocumentsGetParser);
// set our Component´s State
this.setState({ ...this.state, myDocuments: myDocumentsWithCustomObjectAsDocumentsGetParser });
} catch (error) {
// set a new state conserving the previous state + the new error
console.error(error);
this.setState({
...this.state,
errors: [...this.state.errors, "Error in " + libraryName + ". Error: " + error]
});
}
}
private _gerErrors() {
return this.state.errors.length > 0
?
<div style={{ color: "orangered" }} >
<div>Errors:</div>
{
this.state.errors.map((item) => {
return (<div>{JSON.stringify(item)}</div>);
})
}
</div>
: null;
}
}

View File

@ -0,0 +1,3 @@
export interface ICustomBusinessObjectsPnPJsProps {
description: string;
}

View File

@ -0,0 +1,7 @@
// import model
import { MyDocument } from "../model/MyDocument";
export interface ICustomBusinessObjectsPnPJsState {
myDocuments: MyDocument[];
errors: string[];
}

View File

@ -0,0 +1,7 @@
define([], function() {
return {
"PropertyPaneDescription": "Description",
"BasicGroupName": "Group Name",
"DescriptionFieldLabel": "Description Field"
}
});

View File

@ -0,0 +1,10 @@
declare interface ICustomBusinessObjectsPnPJsStrings {
PropertyPaneDescription: string;
BasicGroupName: string;
DescriptionFieldLabel: string;
}
declare module 'customBusinessObjectsPnPJsStrings' {
const strings: ICustomBusinessObjectsPnPJsStrings;
export = strings;
}

View File

@ -0,0 +1,69 @@
import { Item, ODataEntity, ODataParser, FetchOptions, Logger, LogLevel } from "sp-pnp-js";
import { select, expand } from "../utils/decorators";
import { SelectDecoratorsParser } from "../parser/SelectDecoratorsParsers";
// symbol emulation as it's not supported on IE
// consider using polyfill as well
import { getSymbol } from "../utils/symbol";
// sample intheriting single Item
export class MyDocument extends Item {
@select()
public Title: string;
@select("FileLeafRef")
public Name: string;
@select("File/Length")
@expand("File/Length")
public Size: number;
public CustomItemProps: string = "Custom Prop to pass";
// override get to enfore select and expand for our fields to always optimize
public get(parser?: ODataParser<any>, getOptions?: FetchOptions): Promise<any> {
this
._setCustomQueryFromDecorator("select")
._setCustomQueryFromDecorator("expand");
if (parser === undefined) {
parser = ODataEntity(MyDocument);
}
return super.get.call(this, parser, getOptions);
}
// overrise getAs method with custom parser
public getAs<T>(parser?: ODataParser<MyDocument>, getOptions?: FetchOptions): Promise<T> {
this
._setCustomQueryFromDecorator("select")
._setCustomQueryFromDecorator("expand");
if (parser === undefined) {
parser = new SelectDecoratorsParser<MyDocument>(MyDocument);
}
return super.get.call(this, parser, getOptions);
}
private _setCustomQueryFromDecorator(parameter: string): MyDocument {
const sym: string = getSymbol(parameter);
// get pre-saved select and expand props from decorators
const arrayprops: { propName: string, queryName: string }[] = this[sym];
let list: string = "";
if (arrayprops !== undefined && arrayprops !== null) {
list = arrayprops.map(i => i.queryName).join(",");
} else {
Logger.log({
level: LogLevel.Warning,
message: "[_setCustomQueryFromDecorator] - empty property: " + parameter + "."
});
}
// use apply and call to manipulate the request into the form we want
// if another select isn't in place, let's default to only ever getting our fields.
// implement method chain
return this._query.getKeys().indexOf("$" + parameter) > -1
? this
: this[parameter].call(this, list);
}
}

View File

@ -0,0 +1,66 @@
import { Items, ODataEntityArray, ODataParser, FetchOptions, Logger, LogLevel } from "sp-pnp-js";
// symbol emulation as it's not supported on IE
// consider using polyfill as well
import { getSymbol } from "../utils/symbol";
import { SelectDecoratorsArrayParser } from "../parser/SelectDecoratorsParsers";
// import MyDocument to specify the ItemTemplate
import { MyDocument } from "./MyDocument";
export class MyDocumentCollection extends Items {
private ItemTemplate: MyDocument = new MyDocument("");
public CustomCollectionProps: string = "Custom Collection Prop to pass";
// override get to enfore select and expand for our fields to always optimize
public get(parser?: ODataParser<any>, getOptions?: FetchOptions): Promise<any> {
// public get(): Promise<MyDocument> {
this
._setCustomQueryFromDecorator("select")
._setCustomQueryFromDecorator("expand");
if (parser === undefined) {
// default parser
parser = ODataEntityArray(MyDocument);
}
return super.get.call(this, parser, getOptions);
}
// create new method using custom parser
public getAsMyDocument(parser?: ODataParser<MyDocument[]>, getOptions?: FetchOptions): Promise<MyDocument[]> {
this
._setCustomQueryFromDecorator("select")
._setCustomQueryFromDecorator("expand");
if (parser === undefined) {
parser = new SelectDecoratorsArrayParser<MyDocument>(MyDocument);
}
return super.get.call(this, parser, getOptions);
}
private _setCustomQueryFromDecorator(parameter: string): MyDocumentCollection {
const sym: string = getSymbol(parameter);
// get pre-saved select and expand props from decorators
const arrayprops: { propName: string, queryName: string }[] = this.ItemTemplate[sym];
let list: string = "";
if (arrayprops !== undefined && arrayprops !== null) {
list = arrayprops.map(i => i.queryName).join(",");
} else {
Logger.log({
level: LogLevel.Warning,
message: "[_setCustomQueryFromDecorator] - empty property: " + parameter + "."
});
}
// use apply and call to manipulate the request into the form we want
// if another select isn't in place, let's default to only ever getting our fields.
// implement method chain
return this._query.getKeys().indexOf("$" + parameter) > -1
? this
: this[parameter].call(this, list);
}
}

View File

@ -0,0 +1,24 @@
import { Item, ODataEntity, ODataParser, FetchOptions } from "sp-pnp-js";
export class MyItem extends Item {
public static Fields = ["Id", "Title", "Category", "Quantity"];
public Id: number;
public Title: string;
public Category: string;
public Quantity: number;
// override get to enfore select for our fields to always optimize
// but allow it to be overridden by any supplied values
public get(parser?: ODataParser<any>, getOptions?: FetchOptions): Promise<MyItem> {
// use apply and call to manipulate the request into the form we want
// if another select isn't in place, let's default to only ever getting our fields.
const query = this._query.getKeys().indexOf("$select") > -1 ? this : this.select.apply(this, MyItem.Fields);
// call the base get, but in our case pass the appropriate ODataEntity def so we are returning
// a MyItem instance
if (parser === undefined) {
parser = ODataEntity(MyItem);
}
return super.get.call(this, parser, getOptions);
}
}

View File

@ -0,0 +1,133 @@
import { ODataParserBase, QueryableConstructor, Util, Logger, LogLevel } from "sp-pnp-js";
import { getEntityUrl } from "sp-pnp-js/lib/sharepoint/odata";
// symbol emulation as it's not supported on IE
// consider using polyfill as well
import { getSymbol } from "../utils/symbol";
/**
* Custom Response Array Parser to be integrated with @select and @expand decorators
* It can be used on PnP Core JS get() method as a parameter
*/
export class SelectDecoratorsArrayParser<T> extends ODataParserBase<T[]> {
private _returnOnlySelectedWithDecorators = false;
constructor(protected factory: QueryableConstructor<T>, returnOnlySelectedWithDecorators?: boolean) {
super();
this._returnOnlySelectedWithDecorators = returnOnlySelectedWithDecorators;
}
public parse(r: Response): Promise<T[]> {
return super.parse(r).then((d: any[]) => {
if ("length" in d) {
return d.map(v => {
const o = <T>new this.factory(getEntityUrl(v), null);
const combinedWithResults: any = Util.extend(o, v);
const sym: string = getSymbol("select");
if (this._returnOnlySelectedWithDecorators === true) {
return SelectDecoratorsUtils.ProcessSingle(combinedWithResults, sym);
} else {
return Util.extend(combinedWithResults, SelectDecoratorsUtils.ProcessSingle(combinedWithResults, sym));
}
});
} else {
Logger.log({
data: {
d
},
level: LogLevel.Error,
message: "[SelectDecoratorsArrayParser] - response isn't a collection."
});
return null;
}
});
}
}
/**
* Custom Response Parser to be integrated with @select and @expand decorators
* It can be used on PnP Core JS get() method as a parameter
*/
export class SelectDecoratorsParser<T> extends ODataParserBase<T> {
private _returnOnlySelectedWithDecorators = false;
constructor(protected factory: QueryableConstructor<T>, returnOnlySelectedWithDecorators?: boolean) {
super();
this._returnOnlySelectedWithDecorators = returnOnlySelectedWithDecorators;
}
public parse(r: Response): Promise<T> {
// we don't need to handleError inside as we are calling directly
// to super.parse(r) and it's already handled there
return super.parse(r).then(d => {
const classDefaults: T = <T>new this.factory(getEntityUrl(d), null);
const combinedWithResults: any = Util.extend(classDefaults, d);
const sym: string = getSymbol("select");
if ("length" in combinedWithResults) {
Logger.log({
level: LogLevel.Warning,
message: "[SelectDecoratorsParser] - response is a collection. Consider using Array Parser (SelectDecoratorsArrayParser)."
});
// return SelectDecoratorsUtils.ProcessCollection(combinedWithResults, sym);
return combinedWithResults;
} else {
if (this._returnOnlySelectedWithDecorators === true) {
return SelectDecoratorsUtils.ProcessSingle(combinedWithResults, sym);
} else {
return Util.extend(combinedWithResults, SelectDecoratorsUtils.ProcessSingle(combinedWithResults, sym));
}
}
});
}
}
// utils class
class SelectDecoratorsUtils {
// get only custom model properties with @select decorator and return single item
public static ProcessSingle(combinedWithResults: any, symbolKey: string): any {
const arrayprops: { propName: string, queryName: string }[] = combinedWithResults[symbolKey];
let newObj = {};
arrayprops.forEach((item) => {
newObj[item.propName] = SelectDecoratorsUtils.GetDescendantProp(combinedWithResults, item.queryName);
});
return newObj;
}
// get only custom model properties with @select decorator and return item collection
public static ProcessCollection(combinedWithResults: any[], symbolKey: string): any[] {
let newArray: any[] = [];
const arrayprops: { propName: string, queryName: string }[] = combinedWithResults[symbolKey];
for (let i: number = 0; i < combinedWithResults.length; i++) {
const r: any = combinedWithResults[i];
let newObj = {};
arrayprops.forEach((item) => {
newObj[item.propName] = SelectDecoratorsUtils.GetDescendantProp(r, item.queryName);
});
newArray = newArray.concat(newObj);
}
return newArray;
}
private static GetDescendantProp(obj, objectString: string) {
var arr: string[] = objectString.split("/");
if (arr.length > 1 && arr[0] !== "") {
while (arr.length) {
var name: string = arr.shift();
if (name in obj) {
obj = obj[name];
} else {
Logger.log({
data: {
name
},
level: LogLevel.Warning,
message: "[getDescendantProp] - " + name + " property does not exists."
});
return null;
}
}
return obj;
}
if (objectString !== undefined && objectString !== "") {
return obj[objectString];
}
return null;
}
}

View File

@ -0,0 +1,9 @@
/// <reference types="mocha" />
import { assert } from 'chai';
describe('CustomBusinessObjectsPnPJsWebPart', () => {
it('should do something', () => {
assert.ok(true);
});
});

View File

@ -0,0 +1,75 @@
/**
* Property Decorators implementation
*
* Read more about
* Experimental Property decorators: https://github.com/Microsoft/TypeScript-Handbook/blob/master/pages/Decorators.md#property-decorators
* Decorator factories: https://github.com/Microsoft/TypeScript-Handbook/blob/master/pages/Decorators.md#decorator-factories
*
*/
import { Logger, LogLevel } from "sp-pnp-js";
// symbol emulation
import { getSymbol } from "./symbol";
/**
* Decorator factory for select returning Property Decorator
* @param queryName internal name of the SP field or path if means expand. Example: Title, File/Length
*/
export function select(queryName?: string): PropertyDecorator { // this is the decorator factory
return (target: any, propertyKey: string): void => { // this is the decorator
setMetadata(target, "select", propertyKey, queryName);
};
}
/**
* Decorator factory for expand returning Property Decorator
* @param expandName expand path. Example: File/Length
*/
export function expand(expandName: string): PropertyDecorator { // this is the decorator factory
return (target: any, propertyKey: string): void => { // this is the decorator
setMetadata(target, "expand", propertyKey, expandName);
};
}
/**
* Sets metadata on target object using key as an accessor
* Note: I considered to use reflect-metadata API to set metadata, but isn't needed on this scenario
* as we are storing the metadata in the actual object (target).
* @param target object / class from where the decorator is called. It will be used to store metadata on its prototype.
* @param key key or symbol used as accessor for the metadata
* @param propName property name in the class
* @param queryName property name in the query
*/
function setMetadata(target: any, key: string, propName: string, queryName: string): void {
// string.isNullOrUndefinedOrEmpty
if (!(typeof queryName === "string" && queryName.length > 0)) {
queryName = propName;
}
const sym: string = getSymbol(key);
// instead of using Map object, we use an array of objects, as Map is not well supported
// still by all the browsers, consider using Map compiling TypeScript to ES6 and using Babel to transpile to ES5
let currentValues: { propName: string, queryName: string }[] = target[sym];
if (currentValues !== undefined) {
currentValues = [...currentValues, { propName, queryName }];
} else {
currentValues = [].concat({ propName, queryName });
}
// property Decorators will store the metadata in its instance ( as a class property)
// ideally having a symbol as a key, but symbol are not still supported on all the browsers
// and they will require polyfill, as a sample, I will not use symbols, but please, consider it
target[sym] = currentValues;
Logger.log({
data: {
propertyKey: propName,
queryName,
key,
target,
},
level: LogLevel.Verbose,
message: "set metadata for property decorator"
});
}

View File

@ -0,0 +1,5 @@
export function getSymbol(key: string): string {
// symbol not supported on IE, maybe try with polyfill
// const sym: symbol = Symbol.for(key);
return "__" + key + "__";
}

View File

@ -0,0 +1,16 @@
{
"compilerOptions": {
"target": "es5",
"forceConsistentCasingInFileNames": true,
"module": "commonjs",
"jsx": "react",
"declaration": true,
"sourceMap": true,
"experimentalDecorators": true,
"types": [
"es6-promise",
"es6-collections",
"webpack-env"
]
}
}

View File

@ -0,0 +1,8 @@
// Type definitions for Microsoft ODSP projects
// Project: ODSP
/* Global definition for UNIT_TEST builds
Code that is wrapped inside an if(UNIT_TEST) {...}
block will not be included in the final bundle when the
--ship flag is specified */
declare const UNIT_TEST: boolean;

View File

@ -0,0 +1 @@
/// <reference path="@ms/odsp.d.ts" />

View File

@ -6,28 +6,25 @@
"node": ">=0.10.0"
},
"dependencies": {
"@microsoft/sp-client-base": "~1.0.0",
"@microsoft/sp-core-library": "~1.0.0",
"@microsoft/sp-webpart-base": "~1.0.0",
"@types/react": "0.14.46",
"@types/react-addons-shallow-compare": "0.14.17",
"@types/react-addons-test-utils": "0.14.15",
"@types/react-addons-update": "0.14.14",
"@types/react-dom": "0.14.18",
"@microsoft/sp-core-library": "~1.1.0",
"@microsoft/sp-webpart-base": "~1.1.1",
"@types/webpack-env": ">=1.12.1 <1.14.0",
"react": "15.5.4",
"react-dom": "15.5.4",
"react-taxonomypicker": "0.0.30"
"react": "15.4.2",
"react-dom": "15.4.2",
"@types/react": "0.14.46",
"@types/react-dom": "0.14.18",
"@types/react-addons-shallow-compare": "0.14.17",
"@types/react-addons-update": "0.14.14",
"@types/react-addons-test-utils": "0.14.15",
"react-taxonomypicker": "0.0.35"
},
"devDependencies": {
"@microsoft/sp-build-web": "~1.0.1",
"@microsoft/sp-module-interfaces": "~1.0.0",
"@microsoft/sp-webpart-workbench": "~1.0.0",
"@microsoft/sp-build-web": "~1.1.0",
"@microsoft/sp-module-interfaces": "~1.1.0",
"@microsoft/sp-webpart-workbench": "~1.1.0",
"gulp": "~3.9.1",
"@types/chai": ">=3.4.34 <3.6.0",
"@types/microsoft-ajax": "0.0.31",
"@types/mocha": ">=2.2.33 <2.6.0",
"@types/sharepoint": "^2013.1.2",
"gulp": "~3.9.1"
"@types/mocha": ">=2.2.33 <2.6.0"
},
"scripts": {
"build": "gulp bundle",

View File

@ -6,12 +6,11 @@
"jsx": "react",
"declaration": true,
"sourceMap": true,
"experimentalDecorators": true,
"types": [
"es6-promise",
"es6-collections",
"webpack-env",
"microsoft-ajax",
"sharepoint"
"webpack-env"
]
}
}