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
- Create Custom Parser and Array Parser to unify select and property names (this article)
- How to consume our decorators, models and parsers from SPFx, the winning combination
- Github project! Please remember to “star” if you liked it!
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 and Custom Business Object inheriting from Item and Items PnP JS Core classes to help us to have more generic and maintainable code . In this article, we will see how to solve some specific issue to unify query and business object properties by creating custom Parser and Array Parser in PnP JS Core.
PnP JS Core makes use of parser classes to handle converting the response object returned by fetch into the result. The default parser implemented, ODataDefaultParser is used for all requests by default (except a few special cases). But, we can create a custom parser by extending ODataParserBase
Parsers process returned single item. Array Parsers process returned Item Collections as an array.
Here we have both implementations for SelectDecoratorArrayParser and SelectDecoratorParser which is using the decorator metadata in order to combine the results and provide our real business object. For example, in the previous post, we did map @select(“File/Length”) with the property called Size, then the parser will be actually provide the information in the proper Size property.
Here is an example of consuming information from a SP library by using custom objects and custom parsers.
Sample 1. Query one single document using MyDocument custom object and SelectDecoratorParsers (single)
Sample 2. Query multiple documents using MyDocument and MyDocumentCollection custom object classes and SelectDecoratorsArrayParser (returning just the Custom Object properties):
Sample 3. Query multiple documents using MyDocument and MyDocumentCollection custom object classes and SelectDecoratorsArrayParser (returning the full PnP JS Core object):
The ideal scenario is using the sample 3 because will allows us continue with the pnp js core method chain if needed.