React sample showing the use of sp-pnp-js with Async functions and Logging enabled (#187)

* update react-taxonomypicker styles

* react async await PnP JS Core with Logging first release

* update react

* update license

* Establish SPFx Context
This commit is contained in:
José Quinto 2017-05-06 12:27:17 +01:00 committed by Vesa Juvonen
parent 04ea81e196
commit ccb54125d6
36 changed files with 611 additions and 4 deletions

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-async-await-sp-pnp-js",
"framework": "react",
"version": "1.0.2",
"libraryId": "c3bd0bfa-1bee-4af0-ad3d-a72d02b4dc7c"
}
}

View File

@ -0,0 +1,61 @@
# React sample showing the use of sp-pnp-js with Async / Await
## Summary
This webpart demonstrates how to use [PnP JS Core](https://github.com/SharePoint/PnP-JS-Core) with Async functions into the SharePoint Framework as well as integrating [PnP JS and SPFx Logging systems](https://blog.josequinto.com/2017/04/30/how-to-integrate-pnp-js-core-and-sharepoint-framework-logging-systems/). Real example querying SharePoint library to show document sizes.
![React-sp-pnp-js-async-await](./assets/async-await-sp-pnp-js.png)
## 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-async-await-sp-pnp-js | Jose Quinto ([@jquintozamora](https://twitter.com/jquintozamora) , [blog.josequinto.com](https://blog.josequinto.com))
## Version history
Version|Date|Comments
-------|----|--------
1.0|May 1, 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
## Usage
![React-sp-pnp-js-async-await-code](./assets/async-await-sp-pnp-js-2.png)
## Features
- [Async / Await functionality working with PnP JS sample](https://github.com/jquintozamora/spfx-react-async-await-sp-pnp-js/blob/master/src/webparts/asyncAwaitPnPJs/components/AsyncAwaitPnPJs.tsx#L93)
- React Container for the initial load. [Smart Component](https://github.com/jquintozamora/spfx-react-async-await-sp-pnp-js/blob/master/src/webparts/asyncAwaitPnPJs/components/IAsyncAwaitPnPJsState.ts)
- [Interface best practices](https://github.com/jquintozamora/spfx-react-async-await-sp-pnp-js/tree/master/src/webparts/asyncAwaitPnPJs/interfaces)
- [PnP JS and SPFx Logging systems integration](https://blog.josequinto.com/2017/04/30/how-to-integrate-pnp-js-core-and-sharepoint-framework-logging-systems)
![React-sp-pnp-js-async-await-code](./assets/pnp-js-logging-spfx.png)
<img src="https://telemetry.sharepointpnp.com/sp-dev-fx-webparts/samples/react-async-await-sp-pnp-js" />

Binary file not shown.

After

Width:  |  Height:  |  Size: 47 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 39 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 30 KiB

View File

@ -0,0 +1,13 @@
{
"entries": [
{
"entry": "./lib/webparts/asyncAwaitPnPJs/AsyncAwaitPnPJsWebPart.js",
"manifest": "./src/webparts/asyncAwaitPnPJs/AsyncAwaitPnPJsWebPart.manifest.json",
"outputPath": "./dist/async-await-pn-p-js.bundle.js"
}
],
"externals": {},
"localizedResources": {
"asyncAwaitPnPJsStrings": "webparts/asyncAwaitPnPJs/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-async-await-sp-pnp-js",
"accessKey": "<!-- ACCESS KEY -->"
}

View File

@ -0,0 +1,10 @@
{
"solution": {
"name": "react-async-await-sp-pnp-js-client-side-solution",
"id": "c3bd0bfa-1bee-4af0-ad3d-a72d02b4dc7c",
"version": "1.0.0.0"
},
"paths": {
"zippedPackage": "solution/react-async-await-sp-pnp-js.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,35 @@
{
"name": "react-async-await-sp-pnp-js",
"version": "0.0.1",
"private": true,
"engines": {
"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",
"@types/webpack-env": ">=1.12.1 <1.14.0",
"react": "15.5.4",
"react-dom": "15.5.4",
"sp-pnp-js": "^2.0.4"
},
"devDependencies": {
"@microsoft/sp-build-web": "~1.0.1",
"@microsoft/sp-module-interfaces": "~1.0.0",
"@microsoft/sp-webpart-workbench": "~1.0.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": "c81d0661-6ead-4c3c-a3a0-261e2a7edd44",
"alias": "AsyncAwaitPnPJsWebPart",
"componentType": "WebPart",
"version": "0.0.1",
"manifestVersion": 2,
"preconfiguredEntries": [{
"groupId": "c81d0661-6ead-4c3c-a3a0-261e2a7edd44",
"group": { "default": "Under Development" },
"title": { "default": "AsyncAwaitPnPJs" },
"description": { "default": "AsyncAwaitPnPJs description" },
"officeFabricIconFontName": "Page",
"properties": {
"description": "AsyncAwaitPnPJs"
}
}]
}

View File

@ -0,0 +1,54 @@
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 'asyncAwaitPnPJsStrings';
import AsyncAwaitPnPJs from './components/AsyncAwaitPnPJs';
import { IAsyncAwaitPnPJsProps } from './components/IAsyncAwaitPnPJsProps';
import { IAsyncAwaitPnPJsWebPartProps } from './IAsyncAwaitPnPJsWebPartProps';
export default class AsyncAwaitPnPJsWebPart extends BaseClientSideWebPart<IAsyncAwaitPnPJsWebPartProps> {
public render(): void {
const element: React.ReactElement<IAsyncAwaitPnPJsProps > = React.createElement(
AsyncAwaitPnPJs,
{
description: this.properties.description,
pageContext: this.context.pageContext
}
);
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 IAsyncAwaitPnPJsWebPartProps {
description: string;
}

View File

@ -0,0 +1,29 @@
.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,150 @@
import * as React from "react";
import styles from "./AsyncAwaitPnPJs.module.scss";
// import interfaces
import { IFile, IResponseFile, IResponseItem } from "../interfaces"
// import pnp and pnp logging system
import { Logger, FunctionListener, LogEntry, LogLevel, Web } from "sp-pnp-js";
// import SPFx Logging system
import { Log } from "@microsoft/sp-core-library";
// import React props and state
import { IAsyncAwaitPnPJsProps } from "./IAsyncAwaitPnPJsProps";
import { IAsyncAwaitPnPJsState } from "./IAsyncAwaitPnPJsState";
export default class AsyncAwaitPnPJs extends React.Component<IAsyncAwaitPnPJsProps, IAsyncAwaitPnPJsState> {
constructor(props: IAsyncAwaitPnPJsProps) {
super(props);
// set initial state
this.state = {
items: [],
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._readAllFilesSize.bind(this);
// enable PnP JS Logging integrated with SPFx Logging
this._enableLogging();
}
public componentDidMount(): void {
// read all file sizes from Documents library
this._readAllFilesSize("Documents");
}
public render(): React.ReactElement<IAsyncAwaitPnPJsProps> {
// calculate total of file sizes
const totalDocs: number = this.state.items.length > 0
? this.state.items.reduce<number>((acc: number, item: IFile) => {
return (acc + Number(item.Size));
}, 0)
: 0;
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 SharePoint Async Await SP PnP JS Demo!</span>
<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.items.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 className={styles.row}>
<div className={styles.clear + " " + styles.header}></div>
<div className={styles.left}>Total: </div>
<div className={styles.right}>{(totalDocs / 1024).toFixed(2)}</div>
<div className={styles.clear + " " + styles.header}></div>
</div>
</div>
</div>
</div>
</div>
);
}
// Async functions were introduced with ES3/ES5 native support in TypeScript 2.1
// https://blogs.msdn.microsoft.com/typescript/2016/12/07/announcing-typescript-2-1/
// Async function always return a Promise, on this scenario we return void Promise
// because we will not need it as we are directly setting the Component´s state
private async _readAllFilesSize(libraryName: string): Promise<void> {
try {
// do PnP JS query, some notes:
// - .expand() method will retrive Item.File item but only Length property
// - .usingCaching() will be using SessionStorage by default to cache the results
// - .get() always returns a promise
// - await converts Promise<IResponseItem[]> into IResponse[]
const web: Web = new Web(this.props.pageContext.web.absoluteUrl);
const response: IResponseItem[] = await web.lists
.getByTitle(libraryName)
.items
.select("Title", "FileLeafRef")
.expand("File/Length")
.usingCaching()
.get();
// use map to convert IResponseItem[] into our internal object IFile[]
const items: IFile[] = response.map((item: IResponseItem) => {
return {
Title: item.Title,
Size: item.File.Length,
Name: item.FileLeafRef
};
});
// Set our Component´s State
this.setState({ ...this.state, items });
} catch (error) {
// set a new state conserving the previous state + the new error
this.setState({ ...this.state, errors: [...this.state.errors, error] });
}
}
private _enableLogging() {
////////////////////////////////////////////////////////////////////////
// enable Logging system
////////////////////////////////////////////////////////////////////////
// we will integrate PnP JS Logging System with SPFx Logging system
// 1. Logger object => PnP JS Logger
// https://github.com/SharePoint/PnP-JS-Core/wiki/Working-With:-Logging
// 2. Log object => SPFx Logger
// https://github.com/SharePoint/sp-dev-docs/wiki/Working-with-the-Logging-API
////////////////////////////////////////////////////////////////////////
// [PnP JS Logging] activate Info level
Logger.activeLogLevel = LogLevel.Info;
// [PnP JS Logging] create a custom FunctionListener to integrate PnP JS and SPFx Logging systems
let listener = new FunctionListener((entry: LogEntry) => {
// get React component name
const componentName: string = (this as any)._reactInternalInstance._currentElement.type.name;
// mapping betwween PnP JS Log types and SPFx logging methods
// instead of using switch we use object easy syntax
const logLevelConversion = { Verbose: "verbose", Info: "info", Warning: "warn", Error: "error" };
// create Message. Two importante notes here:
// 1. Use JSON.stringify to output everything. It´s helpful when some internal exception comes thru.
// 2. Use JavaScript´s Error constructor allows us to output more than 100 characters using SPFx logging
const formatedMessage: Error = new Error(`Message: ${entry.message} Data: ${JSON.stringify(entry.data)}`);
// [SPFx Logging] Calculate method to invoke verbose, info, warn or error
const method = logLevelConversion[LogLevel[entry.level]];
// [SPFx Logging] Call SPFx Logging system with the message received from PnP JS Logging
Log[method](componentName, formatedMessage);
});
// [PnP JS Logging] Once create the custom listerner we should subscribe to it
Logger.subscribe(listener);
}
}

View File

@ -0,0 +1,5 @@
import { PageContext } from "@microsoft/sp-page-context";
export interface IAsyncAwaitPnPJsProps {
description: string;
pageContext: PageContext;
}

View File

@ -0,0 +1,5 @@
import {IFile} from "../interfaces";
export interface IAsyncAwaitPnPJsState {
items: IFile[];
errors: string[];
}

View File

@ -0,0 +1,6 @@
// create File item to work with it internally
export interface IFile {
Title: string;
Name: string;
Size: number;
}

View File

@ -0,0 +1,4 @@
// create PnP JS response interface for File
export interface IResponseFile {
Length: number;
}

View File

@ -0,0 +1,7 @@
import { IResponseFile } from "./IResponseFile";
// create PnP JS response interface for Item
export interface IResponseItem {
File: IResponseFile;
FileLeafRef: string;
Title: string;
}

View File

@ -0,0 +1,3 @@
export { IFile } from "./IFile";
export { IResponseFile } from "./IResponseFile";
export { IResponseItem } from "./IResponseItem";

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 IAsyncAwaitPnPJsStrings {
PropertyPaneDescription: string;
BasicGroupName: string;
DescriptionFieldLabel: string;
}
declare module 'asyncAwaitPnPJsStrings' {
const strings: IAsyncAwaitPnPJsStrings;
export = strings;
}

View File

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

View File

@ -0,0 +1,15 @@
{
"compilerOptions": {
"target": "es5",
"forceConsistentCasingInFileNames": true,
"module": "commonjs",
"jsx": "react",
"declaration": true,
"sourceMap": 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

@ -15,12 +15,12 @@
"@types/react-addons-update": "0.14.14",
"@types/react-dom": "0.14.18",
"@types/webpack-env": ">=1.12.1 <1.14.0",
"react": "15.4.2",
"react-dom": "15.4.2",
"react-taxonomypicker": "0.0.26"
"react": "15.5.4",
"react-dom": "15.5.4",
"react-taxonomypicker": "0.0.30"
},
"devDependencies": {
"@microsoft/sp-build-web": "~1.0.0",
"@microsoft/sp-build-web": "~1.0.1",
"@microsoft/sp-module-interfaces": "~1.0.0",
"@microsoft/sp-webpart-workbench": "~1.0.0",
"@types/chai": ">=3.4.34 <3.6.0",