What's the best way to organize code in an actix-web application?

Some of my web backend experience so far is working on a decently large C# ASP.Net Core app. In the C# app, DI and classic OOP were heavily used to make the code clean, with a separation of the data layer and routes. In Rust with actix-web, however, this is less practical since DI doesn't seem to exist in the same way. I can do something similar by having my route functions "inject" an API via Data<MyApi>, but this seems to not support that API itself injecting things (e.g. to access the database, or to access another API).

As such, I ask, what are the design patterns that make a large Actix-web project clean?

Personally I used a module for DB accessors that internally use Diesel, a module for routes, and the main file.
However, for a really large actix app I don't think it's unrealistic for each of those modules to be split up into sub-modules.

What sort of things are in this module. E.g. is your database connection pool some global/static data in the module? Are there some structs there, or just functions? If so, what do they do? Do you have any FOSS examples that I could study to see it in more detail?

The DB module contains types that work with Diesel's Insertable and Queryable derive macros (what they're for should be obvious from their respective names), and prepared statements and other queries that operate on those types. Most of the stuff in there is crate-public for easy access.

No in general globals are a red flag and that goes double for async code bases.
I think globals are mostly supported in Rust to accommodate legacy C code bases that do use globals.

Instead, what happens is that you register the conn pool with your HttpServer instance, and then add the connection as a Data<T> argument to your handlers that need DB access. Since Data<T> derefs to the T value contained inside (technically it derefs to &T), you can then feed the &T to the queries you've defined in your DB module. Check here for more detailed information.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.