Skip to content

Commit 23efe5b

Browse files
committed
feat: ✨ update documentation with new features and translations
1 parent 1c31b40 commit 23efe5b

File tree

24 files changed

+617
-59
lines changed

24 files changed

+617
-59
lines changed

docs/.vitepress/config.mts

Lines changed: 5 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -141,24 +141,14 @@ export default defineConfig({
141141
{
142142
text: "Advanced Concepts",
143143
items: [
144+
{ text: "Watch Mode and Hot Reload", link: "/en/advanced-concepts/hot-reload" },
144145
{ text: "Cookies", link: "/en/advanced-concepts/cookies" },
145146
{
146147
text: "Multipart/Form Data Handling",
147148
link: "/en/advanced-concepts/multipart-form-data",
148149
},
149150
{ text: "Security", link: "/en/advanced-concepts/security" },
150151
{ text: "Testing", link: "/en/advanced-concepts/testing" },
151-
{ text: "Hot Reload", link: "/en/advanced-concepts/hot-reload" },
152-
],
153-
},
154-
{
155-
text: "Examples",
156-
items: [
157-
{ text: "Basic Examples", link: "/en/examples/basic-examples" },
158-
{
159-
text: "Advanced Examples",
160-
link: "/en/examples/advanced-examples",
161-
},
162152
],
163153
},
164154
{ text: "Changelog and Roadmap", link: "/en/changelog-roadmap/" },
@@ -296,27 +286,17 @@ export default defineConfig({
296286
{
297287
text: "Conceptos avanzados",
298288
items: [
289+
{
290+
text: "Watch Mode y Hot Reload",
291+
link: "/es/advanced-concepts/hot-reload",
292+
},
299293
{ text: "Cookies", link: "/es/advanced-concepts/cookies" },
300294
{
301295
text: "Manejo de Multipart/Form Data",
302296
link: "/es/advanced-concepts/multipart-form-data",
303297
},
304298
{ text: "Seguridad", link: "/es/advanced-concepts/security" },
305299
{ text: "Testing", link: "/es/advanced-concepts/testing" },
306-
{
307-
text: "Hot Reload",
308-
link: "/es/advanced-concepts/hot-reload",
309-
},
310-
],
311-
},
312-
{
313-
text: "Ejemplos",
314-
items: [
315-
{ text: "Ejemplos Básicos", link: "/es/examples/basic-examples" },
316-
{
317-
text: "Ejemplos Avanzados",
318-
link: "/es/examples/advanced-examples",
319-
},
320300
],
321301
},
322302
{ text: "Changelog y Roadmap", link: "/es/changelog-roadmap/" },

docs/en/advanced-concepts/cookies.md

Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,3 +5,62 @@ keywords: ["cookies", "http cookies", "session management", "sword framework", "
55
---
66

77
# Cookies
8+
9+
To use cookies in Sword, you can enable the `cookies` feature flag. This will allow you to manage cookies using the [Tower Cookies](https://docs.rs/tower-cookies/latest/tower_cookies/) layer.
10+
11+
Sword re-exports the necessary types and functions for working with cookies, making them easy to use in your applications.
12+
13+
## Using Cookies
14+
15+
To access cookies, methods are provided on the `Request` structure. You can use the following method:
16+
17+
```rust
18+
pub fn cookies(&self) -> Result<&Cookies, HttpResponse>;
19+
```
20+
21+
Returns an internal server error (500) if no cookie container is found (which is only possible if the cookie middleware is not enabled).
22+
23+
### Example
24+
25+
```rust
26+
use sword::prelude::*;
27+
28+
#[controller("/cookies")]
29+
struct CookieController {}
30+
31+
#[routes]
32+
impl CookieController {
33+
#[get("/set")]
34+
async fn set_cookie(&self, req: Request) -> HttpResult {
35+
let cookies = req.cookies()?;
36+
37+
let cookie = CookieBuilder::new("username", "sword_user")
38+
.path("/")
39+
.http_only(true)
40+
.same_site(SameSite::Lax)
41+
.build();
42+
43+
cookies.add(cookie);
44+
45+
Ok(HttpResponse::Ok())
46+
}
47+
}
48+
```
49+
50+
## `Signed` and `Private` Cookies
51+
52+
As mentioned earlier, Sword uses the [Tower Cookies](https://docs.rs/tower-cookies/latest/tower_cookies/) layer to manage cookies. Tower Cookies offers two additional types of cookies: `Signed` and `Private`.
53+
54+
- [Private Cookies Documentation](https://docs.rs/tower-cookies/latest/tower_cookies/struct.PrivateCookies.html)
55+
56+
- [Signed Cookies Documentation](https://docs.rs/tower-cookies/latest/tower_cookies/struct.SignedCookies.html)
57+
58+
To use these types of cookies, you'll need to configure a secret key. You can register it as `#[config]` and inject it into middlewares or controllers. [See dependency injection](../key-concepts/dependency-injection/using-dependencies.md)
59+
60+
### Accessing `Signed` and `Private` Cookies
61+
62+
```rust
63+
req.cookies()?.signed(key);
64+
65+
req.cookies()?.private(key);
66+
```
Lines changed: 41 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,44 @@
11
---
2-
title: Hot Reload - Sword Framework
3-
description: Enable hot reload in Sword for faster development. Learn to automatically restart your server when code changes are detected.
4-
keywords: ["hot reload", "development", "auto restart", "sword framework", "development workflow"]
2+
title: Watch Mode and Hot Reload - Sword Framework
3+
description: Enable watch mode and hot reload in Sword for faster development. Learn to automatically restart your server when code changes are detected.
4+
keywords: ["hot reload", "watch mode", "development", "auto restart", "sword framework", "development workflow"]
55
---
66

7-
# Hot Reload
7+
# Watch Mode and Hot Reload
8+
9+
Hot reload is a development tool commonly seen in Node.js environments and other languages. In Rust, there are two options:
10+
11+
## Cargo Watch
12+
13+
Over time, `cargo-watch` has been the most popular tool for watching changes in source code and automatically recompiling the project. You can install it using `cargo`:
14+
15+
```bash
16+
cargo install cargo-watch
17+
```
18+
19+
However, `cargo-watch` only recompiles and restarts the application; it doesn't provide a complete hot reload experience.
20+
21+
## Hot Reload with `subsecond` and `dioxus-cli`
22+
23+
The `Dioxus` team has developed a crate called `subsecond`, which enables a smoother hot reload experience compatible with `axum` and other crates.
24+
25+
To use `subsecond` in your Sword project, follow these steps:
26+
27+
1. Enable the `hot-reload` feature flag in your `Cargo.toml`:
28+
29+
```toml
30+
[dependencies]
31+
sword = { version = "x.y.z", features = ["hot-reload"] }
32+
```
33+
34+
2. Install `dioxus-cli` to run the server with hot reload:
35+
36+
```bash
37+
cargo install dioxus-cli
38+
```
39+
40+
3. Run your Sword application with `dioxus-cli`:
41+
42+
```bash
43+
dx serve # equivalent to `cargo run`
44+
```

docs/en/advanced-concepts/security.md

Lines changed: 42 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,4 +4,45 @@ description: Implement security best practices in Sword applications. Learn abou
44
keywords: ["security", "authentication", "authorization", "cors", "csrf", "sword framework", "web security"]
55
---
66

7-
# Seguridad
7+
# Security
8+
9+
One of Sword's goals is to facilitate the implementation of tools and libraries commonly used in the `axum` ecosystem.
10+
11+
## Helmet
12+
13+
Helmet is a collection of HTTP headers that help protect web applications from some well-known vulnerabilities. To use Helmet in Sword, you can enable the `helmet` feature flag.
14+
15+
This feature uses the [axum-helmet](https://docs.rs/axum-helmet/latest/axum_helmet/) crate.
16+
17+
### Using Helmet
18+
19+
```rust
20+
use sword::prelude::*;
21+
use sword::web::helmet::*;
22+
23+
#[controller("/")]
24+
struct MyController;
25+
26+
#[routes]
27+
impl MyController {
28+
#[get("/")]
29+
async fn index(&self) -> HttpResult {
30+
Ok(HttpResponse::Ok().message("Hello, Helmet!"))
31+
}
32+
}
33+
34+
#[sword::main]
35+
async fn main() {
36+
let helmet = Helmet::builder()
37+
.with_header(XContentTypeOptions::nosniff())
38+
.with_header(XXSSProtection::on())
39+
.build();
40+
41+
let app = Application::builder()
42+
.with_controller::<MyController>()
43+
.with_layer(helmet)
44+
.build();
45+
46+
app.run().await;
47+
}
48+
```

docs/en/advanced-concepts/testing.md

Lines changed: 76 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,3 +5,79 @@ keywords: ["testing", "unit tests", "integration tests", "sword framework", "tes
55
---
66

77
# Testing
8+
9+
Since Sword is built on top of `axum`, you can leverage the testing tools provided by the `axum` ecosystem to test your Sword applications.
10+
11+
## `axum_test`
12+
13+
The [`axum_test`](https://docs.rs/axum-test/latest/axum_test/) crate offers utilities for testing `axum` applications, and therefore, Sword applications.
14+
15+
However, remember that Sword provides a standardized HTTP response system, so you'll need to adapt `axum` responses to Sword responses in your tests.
16+
17+
### Example
18+
19+
First, make sure to add `axum_test` as a dependency:
20+
21+
```toml
22+
[dependencies]
23+
axum-test = "17.3.0"
24+
```
25+
26+
Then, you can write tests for your Sword controllers as follows:
27+
28+
```rust
29+
use serde_json::json;
30+
use sword::prelude::*;
31+
32+
#[controller("/users")]
33+
pub struct UsersController {}
34+
35+
#[routes]
36+
impl UsersController {
37+
#[get("/")]
38+
async fn list_users(&self) -> HttpResponse {
39+
let data = json!({
40+
"users": [
41+
{"id": 1, "name": "Alice"},
42+
{"id": 2, "name": "Bob"}
43+
]
44+
});
45+
46+
HttpResponse::Ok().data(data)
47+
}
48+
}
49+
```
50+
51+
Now, you can write a test for the `/users` endpoint:
52+
53+
```rust
54+
#[tokio::test]
55+
async fn test_list_users() {
56+
use axum_test::TestServer;
57+
58+
let app = Application::builder()
59+
.with_controller::<UsersController>()
60+
.build();
61+
62+
let server = TestServer::new(app.router()).unwrap();
63+
let response = server.get("/users").await;
64+
let json = response.json::<ResponseBody>();
65+
66+
assert_eq!(response.status_code(), 200);
67+
assert!(json.data.is_some());
68+
69+
let data = json.data.unwrap();
70+
71+
assert_eq!(
72+
data,
73+
json!({
74+
"users": [
75+
{"id": 1, "name": "Alice"},
76+
{"id": 2, "name": "Bob"}
77+
]
78+
})
79+
);
80+
}
81+
```
82+
83+
The `ResponseBody` structure corresponds to the standard HTTP response structure in Sword.

docs/en/changelog-roadmap/index.md

Lines changed: 86 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,4 +4,89 @@ description: View Sword framework's changelog and future roadmap. Stay updated w
44
keywords: ["changelog", "roadmap", "updates", "sword framework", "release notes", "future features"]
55
---
66

7-
# Changelog y Roadmap
7+
# Changelog and Roadmap
8+
9+
## [Unreleased]
10+
11+
### Added
12+
13+
- New `next()` method on `Request` struct. See `Changed` section for more details.
14+
15+
### Changed
16+
17+
- The `next!` macro has been removed. Instead, use the `req.next().await` method to pass control to the next middleware or handler in the chain. This change removes the need for a macro to do "magic" and makes the code more explicit and easier to understand.
18+
19+
- Middleware structs marked with `#[middleware]` macro now can omit the `next` parameter in their methods. Instead, they can call `req.next().await` to pass control to the next middleware or handler.
20+
21+
22+
## [0.2.0]
23+
24+
### Added
25+
26+
- Added `Non static handlers for controllers` support. Now, controllers must have `&self` as the first parameter in their methods. This allows to use struct fields that are extracted from the application state.
27+
28+
- Added schema validation with feature flags. Now the `validator` crate is included only under `validator` feature flag. This allows users to choose if they want to use `validator` crate or not. If not, you can implement your own trait for validation to the `Request` struct. e.g. with `garde`, `validify`.
29+
30+
- Added `global prefix` support. Now, you can set a global prefix for all routes in the application. This is useful for versioning or grouping routes under a common path.
31+
32+
- Added versioning support on controllers with `version` attribute.
33+
34+
- Added `hot-reload` feature flag to `sword`. This enables hot-reloading of the application during development. It uses the `subsecond` and `dioxus-devtools` crates for hot-reloading functionality. See the examples for usage.
35+
36+
- Non static middlewares support. Now, middlewares can also have `&self` as the first parameter in their methods. This allows to use struct fields that are extracted from the dependency injection system.
37+
38+
- `OnRequest` and `OnRequestWithConfig` traits for creating custom middlewares.
39+
40+
- `#[uses]` macro attribute to apply middlewares to controllers.
41+
42+
- Added injection support for middlewares. Now, middlewares can have dependencies injected from the DI system.
43+
44+
- Added injection support for custom configuration types marked with `#[config]` macro.
45+
46+
- Added `DependencyContainer` struct that allows to register components and providers. This struct is used internally by the DI system to manage dependencies.
47+
48+
### Fixed
49+
50+
- Fixed an issue where the middleware macro was not working correctly with some configuration types.
51+
52+
- Fixed the error messages when some macros failed to compile. Now, the error messages are more descriptive and helpful.
53+
54+
### Changed
55+
56+
- With the latest `axum_responses` release, the `data` field in error responses has been removed and replaced with either `error` or `errors`, depending on your configuration. By default, validation errors will be returned under `errors` fields.
57+
58+
- Changed global state scope. Now its necessary to use DI pattern.
59+
60+
- Changed `Context` by `Request`. This change was made because at the first time `Context` was used to handle request, state, and config together. But now, with the new features added, it was more appropriate to use `Request`.
61+
62+
- Change the purpose of `#[middleware]`. Now, it's used to declare a middleware struct instead of applying middlewares to controllers. To apply middlewares to controllers, use the new `#[uses]` attribute.
63+
64+
- Change `HttpResult` from `Result<T, HttpResponse>` to `Result<HttpResponse, HttpResponse>`. This change was made because the main usage of `HttpResult` is to return HTTP responses, not arbitrary types.
65+
66+
## [0.1.8]
67+
68+
### Added
69+
70+
- Added `helmet` feature to `sword`. This allows users to enable security-related HTTP headers for their applications. It's built on top of the `rust-helmet` and `axum-helmet` crates.
71+
72+
- Added built-in `Timeout` middleware based on `tower_http` TimeoutLayer. This middleware allows users to set a timeout duration for requests, enhancing the robustness of their applications. The number of seconds can be configured on the config .toml file at the `application` key. See the examples for usage.
73+
74+
- Added documentation comments to all public functions and structs in the `sword` crate. This improves code readability and helps users understand the functionality of the framework better.
75+
76+
- Added `cookies` feature flag to `sword`. This enables cookie parsing and management. It uses the `tower-cookies` crate for cookie handling. This feature allows users to use Cookies, PrivateCookies, and SignedCookies in their handlers. See the examples for usage.
77+
78+
- Added `multipart` feature flag to `sword`. This enables multipart form data handling using the `multipart` feature flag of `axum` crate. Basically it provides `Multipart` extractor for handling file uploads and form data.
79+
80+
- Added support for axum run with graceful shutdown. This allows the application to handle shutdown signals gracefully, ensuring that ongoing requests are completed before the server stops.
81+
82+
- Added `tower_http` layers support to `middleware macro`. This allows users to easily add middleware layers from the `tower_http` to controllers using the `#[middleware]` attribute.
83+
84+
### Changed
85+
86+
- Move `hot-reload` functionality to another branch due to its constantly changing development state.
87+
88+
- Changed the `serde_qs` dependency to native `axum` query extraction. This simplifies the codebase and reduces dependencies.
89+
90+
- Changed the `#[controller_impl]` macro to `#[routes]`. This change improves clarity and consistency in the codebase.
91+
92+
- Changed the builder pattern for `Application` struct. Now, all the build methods start with `with_` prefix. For example, `with_layer`, `with_controller`, etc. This change enhances code readability and consistency.

docs/en/examples/advanced-examples.md

Lines changed: 0 additions & 7 deletions
This file was deleted.

0 commit comments

Comments
 (0)