Akshay Sura - Partner
17 Feb 2021
All my career I have worked with programming languages that forced me to use strong types. Strong types give us the means to type check during compile time. Today we will look at how we can use Strongly typed models representing our content types in Kontent.
We will look at how to generate and use Strongly types models in both Next.js and also in .NET Core.
I just love how these API and developer-first technologies are great at documentation. You can find the documentation you need for this blog post using the following links:
Once you have your content types defined in Kentico Kontent you need to generate your Strongly typed models.
Use the following to generate the models based on the programming language you are using. Each of the following commands have additional flags you can explore. The flags specified are the ones I chose to use.
npm i @kentico/kontent-model-generator -g kontent-generate --projectId=xxx --moduleResolution=ES2015 --codeType=TypeScript kontent-generate --projectId=xxx --moduleResolution=ES2015 --codeType=JavaScript
I used the withtypeprovider flag to generate the CustomTypeProvider which registers all the Strongly Typed Models. I also used the structuremodel flag to use IRichTextContent instead of string, this helps while parsing the rich text fields.
dotnet tool install -g Kentico.Kontent.ModelGenerator KontentModelGenerator --projectid "<projectid>" --withtypeprovider True --structuredmodel True
The generator creates two partial class files for each model, one with Modelname.Generated.cs and Modelname.cs. The intent is for you to extend the class in the Modelname.cs file.
Once the code is generated it is time to use these models to pull in the proper values.
In your DeliveryClient configuration, you specify all the typeResolvers.
I am using these models in our Azure Functions and here is an example.
The beauty of the above code is that it brings in the home page item with all of it's references as strongly typed models just because we specified the customTypeProvider. You could also choose to individually map the types to the models but this way its all autogenerated and easy.
That is about it, it is super simple and makes your life easy.
If you have any questions, please get in touch with me. @akshaysura13 on Twitter or on Slack.
Akshay is an nine-time Sitecore MVP who has spent more than a decade working exclusively on Sitecore projects.
In addition to his work as a solution architect, Akshay is also one of the founders of SUGCON North America 2015, SUGCON India 2018 & 2019, Unofficial Sitecore Training, and the Sitecore Slack.
Akshay founded and continues to run the Sitecore Hackathon. As one of the managing partners of Konabos Consulting, Akshay will continue to work with clients to lead projects and mentor their existing teams.
Share on social media