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
- 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 (this article)
- 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
In the previous posts of this series we explained why we should use Custom Business Objects in PnP JS Core and we implemented TypeScript decorators to help us to have more generic and maintainable code. In this article, we will see how to implement Custom Business Objects inheriting from Item and Items PnP JS Core generic classes and using the previously created TypeScript decorators internally.
What is the difference between Item and Items PnP JS Core classes?
Let’s do the comparison with Client Object Model, Item is ListItem and Items is ListItemCollection. PnP Core JS expose these two different classes Item and Items with different methods within them. For example, you can see different Item Methods and Items methods.
Imagine we are trying to get specific Item or Document from SharePoint using PnP Core JS then we will use this code (with no custom objects):
And similarly, to get Items or Document Collection we will use:
Here the result:
Now, we already know the difference between Item and Items from PnP JS Core. Let’s implement our two custom classes inheriting both of them and combining TypeScript decorators.
Custom classes implementation inheriting from Item and Items
We are going to create two new classes called “MyDocument“ and “MyDocumentCollection“.
MyDocument
MyDocumentCollection
Note you can see the full code in this github project.
Ideally we will create a folder in our solution to create all our models:
How to use MyDocument Custom Business Object from our PnP JS Core code
We can easily use the class with the following code:
How to consume MyDocument:
How to use MyDocumentCollection:
Conclusion
We can notice how both custom objects and decorators work well because queries to SP only brings the right data “Title, FileLeafRef and File/Length“, but still we need a parser in order to correctly do the mapping between the query properties into our TypeScript objects “Title, Name and Size“ properties.
In the next post we are going to implement a custom Parser and Array Parser to solve this specific issue.