Missing Transactions?

I think the book would be better if updated a bit about fluent transactions.

var userA: User = ...
var userB: User = ...

return req.transaction(on: .<#dbid#>) { conn in
    return userA.save(on: conn).flatMap { _ in
        return userB.save(on: conn)
    }.transform(to: HTTPStatus.ok)

The above example will save User A then User B before completing the transaction. If either user fails to save, neither will save. Once the transaction has completed, the result is transformed to a simple HTTP status response indicating completion.

1 Like

@0xtim Do you have any feedback about this? Thank you - much appreciated! :]

@choioi yeah it would be nice to include, but unfortunately if we added everything Vapor could do we’d never finish the book! :laughing:

The docs are a good place to look for other features, e.g. https://docs.vapor.codes/3.0/fluent/transaction/

1 Like

Hi @choioi. What is the question you have here?

Do you want to perform asynchronous saves of both users at the same time instead of sequentially?

1 Like

My point is sometime you need saving something 1st, then the 2nd must completed too, if transaction 1st comleted but the 2nd error… you must roolback the 1nd too…so i think transaction is a part important but it’s not in the book :slight_smile:

I agree with you about the importance of transactions in relation to the create and update of any CRUD api. I happened to ask something similar here. (Btw, I would have used an array of futures for the user saves and flatten them, so the saves are not sequential).

But there is indeed a lot to cover for server side swift. Perhaps it might be better to have additional supplementary books to the basic one that will cover more depth in specific areas. @0xtim?

@michaeltansg Thank you for your suggestion - much appreciated!

@michaeltansg yeah if there’s demand there could be scope for an advanced book. I’ll also keep a note of it to see if we can add in the third edition when that happens