Create record only if parent exists in Vapor using Fluent
You can do something like
LastName.query(on: req.db).filter(\.$name == "Smith")
.first()
.unwrap(or: Abort(.notFound))
.flatMap { lastName in
let middlenameQuery = MiddleName.query(on: req.db).filter(\.$name == "Jane").first().flatMap { middlenameFound in
if let middleName = middlenameFound {
return req.eventLoop.future(middleName)
} else {
let newMiddlename = Middlename(name: "Jane")
return newMiddlename.create(on: req.db).transform(to: newMiddlename)
}
}
return middlenameQuery.flatMap { middlename in
// Use last name and middle name here
}
}
Vapor 4 Unable to Update Optional Parent with Put HTPP Request
With Fluent and relations if you're trying to set properties you need to do it via the property wrapper rather than the property itself. So in your case it should be
$0.$jurisdiction.id = jurisdiction.id
This allows you to update the relation with only the parent ID rather than requiring the whole parent, in the same way as the initialiser.
Vapor 4 parent child relationship
In this case ID
should be set as String
@ID(key: .id, generatedBy: .user) var id: String?
Vapor 4 fluent. Complex query, filter and create if doesn't exist
0xTim helped me out on Discord. And I managed to make it work after reading This doc
Here's working solution:
func create(req: Request) throws -> EventLoopFuture<Chat> {
let currentUser = try req.auth.require(User.self)
guard
let userID = req.parameters.get("userID"),
let userUUID = UUID(userID)
else { throw Abort(.badRequest) }
return User
.query(on: req.db)
.filter(\.$id == userUUID)
.with(\.$chats, { chats in
chats.with(\.$users)
})
.first()
.unwrap(or: Abort(.internalServerError))
.flatMap({ chatUser -> EventLoopFuture<Chat> in
let chat = chatUser
.chats
.filter({
$0.users.contains(where: { $0.id! == currentUser.id! })
})
.first
if let chat = chat {
return req.eventLoop.makeSucceededFuture(chat)
} else {
let newChat = Chat()
return newChat
.save(on: req.db)
.flatMap({
newChat
.$users
.attach([chatUser, currentUser], on: req.db)
.flatMap({
return req.eventLoop.makeSucceededFuture(newChat)
})
})
}
})
}
Parent Child Relation with Vapor 4
This is failing because of the way property wrappers override the JSON decoding for models. You have two options. You can either send the JSON Fluent expects:
{
"name": "Chicago Bulls",
"league": {
"id": "C21827C2-8FAD-4A89-B8D3-A3E62E421258"
}
}
Or you can create a new type, CreateTeamData
that matches the JSON you would expect to send, and manually create a Team
out of it. I much prefer the second route:
struct CreateTeamData: Content {
let name: String
let leagueID: UUID
}
func createTeam(req: Request) throws -> EventLoopFuture<Team> {
let data = try req.content.decode(CreateTeamData.self)
let team = Team(name: data.name, leagueID: data.leagueID)
return team.save(on: req.db).map { team }
}
Complex query using Fluent in Vapor 4
If I have understood your requirement correctly, you should be starting with the sibling relationship from the User
end, not Chat
. Your query then simplifies to:
func fetch(req: Request) throws -> EventLoopFuture<[Chat]> {
let user = try req.auth.require(User.self)
return User
.query(on: req.db)
.filter(\.$id == user.id!)
.with(\.$chats)
.first()
.unwrap(or:Abort(.internalServerError))
.map
{
chattyUser in
return chattyUser.chats
}
}
Using Fluent in a Vapor Command
This was a simple one...
Just missing the
import Fluent
Thanks to @0xTim at Discord :)
Vapor 4 Fluent create Model doesn't save it to the database
Try saving the product instead of the input:
return product.create(on: req.db).map { print("Product saved") }
.transform(to: .ok)
Creating CRUD Functions Using Async-Await with Vapor-Fluent - Swift 5.6
You probably need to give the compiler a hand and force it to use the async version of .first()
:
guard let row: Token = try await Token.query(on: req.db)
.filter(\.$token == token)
.first()
Because the functions have the same signature it can occasionally pick the future version, especially if there are errors elsewhere
Related Topics
How to Convert String to Date Without Time in Swift 3
Swift - Nsdate - Remove Part of Date
How to Get The Nearest Int Floored from a Sqrt of an Int
Xcode9/Scenekit - .Dae File Not Loading into Scnscene - Returns Nil
Swift Auto Completion Not Working in Xcode 6 Beta
Implement an Equatable Void (None) Type
Continuous Rotation of Nsimageview (So It Appears to Be Animated)
Adding Items to The Dock Menu from My View Controller in My Cocoa App
Merging Two Arrays of Dictionaries Based on a Shared Value
Cannot Convert Value of Type 'Foo!' to Expected Argument Type 'Foo!'
Implementing Undo and Redo in a UItextview with Attributedtext
Change Color of Row Programmatically in Watchkit
Rxswift + Mvvm + Coordinator Pattern, How to Wait for Coordinator Result Sequentially
How to Change an Inout Parameter from Within a Escaping Closure
Querying Geohashes in Firestore Returns Nothing
Comma Automatically Being Added to Textfield in Swift