
Post Series Index
This is a blog post in the series about working with Custom Business Objects, Parsers and Decorators in PnP JS Core:
- Introduction to Why do we should use Custom Business Objects (Models) in PnP JS Core (this article)
- Creating select and expand TypeScript Property Decorators to be used in PnP JS Core
- Creating MyDocument and MyDocumentCollection models extending Item and Items PnP JS Core classes
- How to consume our decorators, models and parsers from SPFx, the winning combination
- How to consume our decorators, models and parsers from SPFx, the winning combination
- Github project! Please remember to “star” if you liked it!
Introduction
The PnP JS Core library was created to help developers to simplify common operations within SharePoint and the SharePoint Framework by providing a fluent API (wrapper) for SharePoint REST API.
A few months ago I started to put my hands on PnP JS Core and I created a new react sample showing the use of it with async / await. By then I noticed how easy accessing to REST API services is by using this library, which even provides an API to cache data in the browser and do query batching.
Then I decided to give it a go for using in a real world application, and then the fun began ;) and I started to look into more advanced concepts like Extending with Custom Business Objects and create Response Parsers.
I especially DO like TypeScript to develop modern JS Applications and webparts. Moreover, when developing an application we often have defined entities and models representing the data we are manipulating. More in particular in client side development and using TypeScript as a OO Language we like to have our data as a Typed object instead of using any :)
The PnP JS Core library provides a base for us to build our custom objects at different levels:
- Item import { Item } from “sp-pnp-js”;
- Items (ItemCollection) import { Items } from “sp-pnp-js”; For the full list see this PnP JS Core github folder.
Why do we should use custom business objects in PnP JS Core?
Let’s get to the point, quick answer is we don’t strictly need create custom business objects in order to do queries with PnP JS Core library, but if we are using the combination of TypeScript, React and PnP JS Core it will be obvious the benefits it could give to our full development team.
However I would try to show you these benefits by providing two examples solving the same requirement (Get Specific Item from a Custom SharePoint List).
Let’s assume we have the following list with four columns:
We are going to use PnP JS Core to query the first item of that list but we will do in two ways:
- PnP JS Core WITHOUT custom model
- PnP JS Core WITH custom model
PnP JS Core WITHOUT custom model
Let’s assume we already have an environment in which use PnP JS Core, if not you can use this project as a reference to start with PnP JS Core, TypeScript, React and SPFx.
Then let’s use the following code to query do the query: