Closed nightwill closed 4 years ago
@nightwill The optional id is a feature of Fluent itself. But you can return an optional in your Public
struct like this:
extension Key: CRUDModel {
var `public`: Public {
Public.init(id: id, title: title)
}
struct Public: Content {
var id: UUID?
var title: String
}
}
If I misunderstood something and there is an issue with crud-kit
please don't hesitate to correct me!
In my case, optional "id" is not acceptable, so usually, I use
import Vapor
struct KeyResponse: Content {
let id: UUID
let title: String
}
extension KeyResponse {
init(_ key: Key) throws {
self.id = try key.requireID()
self.title = key.title
}
}
So I would like to have somthing like:
func `public`() throws -> Public {
try Public(id: try requireID(), title: title)
}
@nightwill Please apologize, I still don't understand how this is related to crud-kit.
If your Public
struct is equal to your base model except for the non-optional id, you don't need a Public
struct at all. Crud-Kit always returns model instances from the database, so they will always have an id. (This behavior is verified by tests.)
If you want to provide a Public
struct, you can make the id optional and still be sure it will be there. But if you insist in a non-optional id, you will need to force unwrap the id or use requireID()
.
Thank you for your response. I'm rewriting a large project using microservices architecture, and I will use many CRUD models. In most cases "public" model a little bit different than a corresponding model in DB. Now I have the choice: write each time force unwrapping "!", or using optional id in a model. It's just my preference but I hate to write "!". It's unsafe, and I don't use it anywhere in my project. Or I should use optional id
in my model - it isn't a perfect way too. I think many developers will face the same problem using your great library. So it's just my thoughts and maybe just my private preferences.
It wasn't a real problem, but just a wish. You can close the issue.
PS. I love this lib and still using it)) Thank you for your job.
Thanks! Now I do understand. Unfortunately the optional id is not related to this package but part of the protocol Model
defined in vapor/fluent-kit. I am not touching this in my code.
I was exploring custom autogenerated responses in the beginning but due to Swifts limitations with reflection I am afraid what you ask for is currently not possible in a generic way. Still I might be wrong and if you have an idea, I would be glad to see!
Hi Simon. I'm starting a new project and trying to use your library. My English is not very well, sorry.
I need "id" in many cases, so I will always have to use "!" to force unwrap optional "id".