uSync - ISyncSerializer DeserializeCore & SaveItem - Best practice

I’ve been giving it a go to create a custom uSync serializer for my package uSupport!

I’ve look around, and most packages seems to do it differently. And I am not quite sure what’s the best practice here.

I am currently done this in the DeserializeCore method:

var item = FindItem(node);

...

item = item == null ? _ticketTypeService.Create(schema) :
					  _ticketTypeService.Update(schema);

return SyncAttempt<uSupportTicketType>.Succeed(item.Name, item, ChangeType.Import, Array.Empty<uSyncChange>());

But I am unsure if I should be doing this instead in the DeserializeCore method:

var item = FindItem(node);

...

return SyncAttempt<uSupportTicketType>.Succeed(item.Name, item, ChangeType.Import, Array.Empty<uSyncChange>());

And then do that check in the SaveItem method?

public override void SaveItem(uSupportTicketType item)
{
    var ticketType = _ticketTypeService.Get(item.Id);
    if(ticketType == null)
    {
        _ticketTypeService.Create(item);
    }
    else
    {
        _ticketTypeService.Update(item);
    }

}

Or is this like a, “same same but different kind of thing”. So it doesn’t really matter? :sweat_smile:

Hi,

We’ve been working on making this eaiser - so we have some ‘boilerplate’ code we’ve been developing: uSync/uSync.Extend at v17/main · KevinJump/uSync · GitHub


In terms of what you’re doing.

it depends on how you’re setup works. i suspect both are fine. some of the inbuilt things need you to ‘new up’ the items in a certain way, before you can use them at all, so that’s why they might create the item first before setting values.

but if you don’t need that that just having a ‘new item’ is fine.

so in the extreme this is fine then.

var item = FindItem(node) ?? new(); 

Oh wow, this is golden! Thank you so much for sharing!

Correct me if I am wrong here. But, SaveItem runs after DeserializeCore right? So right now I am running _ticketTypeService.Update twice, if I am using _ticketTypeService.Update in both DeserializeCore and SaveItem, right?

Yes, its actually in the handler after it calls deserialize it will call the save, if and when required***

so yes - i would say you don’t need to call the update/create as part of the deseralize prociess, if you don’t have too. you should just “new” the object if FindItem doesn’t find it, and let the new item be saved by the process deserlizecore.

you only need to call the update/create if you can’t just create a new version of your object with ‘new’ (which sometimes is the case, but mostly, people just do new() right?)


* edge case: for some things the handler can choose to do a bulk save (doesn’t really happen)

* another edge case : you can set the “saved” flag as part of the result, and the handler won’t save it.