DEV Community

Kevin Jump
Kevin Jump

Posted on

Early Adopter's guide to Umbraco v14 [Trees] - DataSources

A tree is nothing without its data. Previously we have defined the code in the backend (c#) that will get us our tree, now we need to plumb that in to a Data Souce so we can start to represent it on the front end.

Code for these posts is avalible in our TimeDashboard Repository FrontEnd (typescript) & Backend (c#)

DataSource

The Tree datasource is the thing that gets our tree information from teh automatically generated api 'resources' and presents it in a way we can then use in a repository and ultimately the front end.

To save a lot of code - we are extending an Umbraco base tree datasource.

export class TimeTreeServerDataSource extends UmbTreeServerDataSourceBase
    <TimeTreeItemResponseModel, TimeTreeItemModel> {

    constructor(host: UmbControllerHost) {
        super(host, {
            getRootItems,
            getChildrenOf,
            mapper
        });
    }
}
Enter fullscreen mode Exit fullscreen mode

by doing this we have saved ourselves a lot of code, but we do need to define the tree methods we are passing to the constructore.

Get root items

The root items in our tree

const getRootItems = () => TimeResource.getRoot({});
Enter fullscreen mode Exit fullscreen mode

Get Child items

For us we have called that method getChildren in our controllers

const getChildrenOf = (parentUnique: string | null) => {
    if (parentUnique == null){
        return getRootItems();
    }
    else {
        return TimeResource.getChildren({parentId: parentUnique});
    }
};
Enter fullscreen mode Exit fullscreen mode

Map from response to item

Finally we have to map from our response item to the model item that is used in the front end.

const mapper = (item: TimeTreeItemResponseModel) : TimeTreeItemModel => {
    return {
        unique: item.id,
        parentUnique: item.parent?.id || null,
        name: item.name,
        entityType: TIME_TREE_ITEM_TYPE,
        hasChildren: item.hasChildren,
        isFolder: false,
        icon: 'icon-alarm-clock'
    };
};
Enter fullscreen mode Exit fullscreen mode

Top comments (0)