FFCoreData icon indicating copy to clipboard operation
FFCoreData copied to clipboard

Decodable Object prevent duplicates

Open darnat opened this issue 7 years ago • 2 comments

The code works perfectly fine, but something is missing. What if when I'm tryin to decode a JSON with my NSManagedObject Codable Model, but this object already exist. I mean to say for exemple that I already have in my Database an Object with the same primaryKey. And I don't want to have a duplicate, just update the existing one.

Since I don't really have the control when init(from decoder: Decoder) is called. How can I perform an NSRequest and return the object if it exist or create a new One. Exactly like the Person and its dogs but at the root level ?

darnat avatar Apr 18 '18 08:04 darnat

That's exactly what findOrCreate(for:in:) is for. While the default implementation fetches a "singleton-like" object and updates it, you can always implement it in your entities and fetch an object with the id of the DTO.

Of course if this happens a the root level, you'd need to manually decode the DTO and then pass it to findOrCreate(for:in:). I might add some convenience extensions / functions for that. Meanwhile you can use something like this:

extension JSONDecoder {
    final func decode<Entity: CoreDataDecodable>(_: Entity.Type, from data: Data) throws -> Entity {
        return try .findOrCreate(for: decode(Entity.DTO.self, from: data), in: .decodingContext())
    }
}

ffried avatar Apr 18 '18 09:04 ffried

I've just released v4.1.0 which adds the above convenience extension. However, this still does not deal with decoding say an array of entities. There you still need to manually loop over the decoded DTOs. I want to add a more generic solution to this, but haven't had time in this release.

ffried avatar Jun 01 '18 13:06 ffried