nestforge 1.9.0

NestJS-inspired modular backend framework for Rust
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
/**
* This is the crate users will import.
* It re-exports the internal pieces
* use nestforge::{NestForgeFactory, ModuleDefinition, Container};
*/
pub use nestforge_core::{
    collect_module_graph, collect_module_route_docs, framework_log, framework_log_event,
    initialize_module_graph, openapi_array_schema_for, openapi_nullable_schema_for,
    openapi_schema_components_for, openapi_schema_for, register_injectable, register_provider,
    ApiEnvelopeResult, ApiResult, ApiSerializedResult, AuthIdentity, AuthUser, BearerToken, Body,
    Container, ContainerError, ControllerBasePath, ControllerDefinition, Cookies, Decorated,
    DocumentedController, DynamicModuleBuilder, ExceptionFilter, Guard, Headers, HttpException,
    Identifiable, InMemoryStore, InitializedModule, Inject, Injectable, Interceptor,
    IntoInjectableResult, LifecycleHook, List, ModuleDefinition, ModuleGraphEntry,
    ModuleGraphReport, ModuleRef, NextFn, NextFuture, OpenApiSchema, OpenApiSchemaComponent,
    OptionHttpExt, OptionalAuthUser, Param, Pipe, PipedBody, PipedParam, PipedQuery, Provider,
    Query, RegisterProvider, RequestContext, RequestDecorator, RequestId,
    RequireAuthenticationGuard, ResourceError, ResourceService, ResponseEnvelope,
    ResponseSerializer, ResultHttpExt, RoleRequirementsGuard, RouteBuilder, RouteDocumentation,
    RouteResponseDocumentation, Serialized, Validate, ValidatedBody, ValidationErrors,
    ValidationIssue,
};
pub use serde_json;

#[cfg(feature = "cache")]
pub use nestforge_cache::{
    cached_response_interceptor, CacheInterceptor, CachePolicy, DefaultCachePolicy,
};
#[cfg(feature = "config")]
pub use nestforge_config::{
    load_config, Config, ConfigError, ConfigModule, ConfigOptions, ConfigService, EnvSchema,
    EnvStore, EnvValidationIssue, FromEnv,
};
#[cfg(feature = "data")]
pub use nestforge_data::{CacheStore, DataError, DataFuture, DocumentRepo};
#[cfg(feature = "db")]
pub use nestforge_db::{Db, DbConfig, DbError, DbTransaction};
pub use nestforge_http::NestForgeFactory;
pub use nestforge_http::{MiddlewareConsumer, MiddlewareRoute, NestMiddleware};
pub use nestforge_macros::{
    authenticated, controller, delete, description, dto, entity, entity_dto, get, id, identifiable,
    injectable, module, post, put, response, response_dto, roles, routes, summary, tag,
    use_exception_filter, use_guard, use_interceptor, version, Identifiable, Validate,
};
#[cfg(feature = "microservices")]
pub use nestforge_microservices::{
    EventEnvelope, InProcessMicroserviceClient, MessageEnvelope, MicroserviceClient,
    MicroserviceContext, MicroserviceRegistry, MicroserviceRegistryBuilder, TransportMetadata,
};

#[macro_export]
macro_rules! impl_identifiable {
    ($type:ty, $field:ident) => {
        impl $crate::Identifiable for $type {
            fn id(&self) -> u64 {
                self.$field
            }

            fn set_id(&mut self, id: u64) {
                self.$field = id;
            }
        }
    };
}

#[macro_export]
macro_rules! guard {
    ($name:ident) => {
        #[derive(Default)]
        pub struct $name;

        impl $crate::Guard for $name {
            fn can_activate(
                &self,
                _ctx: &$crate::RequestContext,
            ) -> Result<(), $crate::HttpException> {
                Ok(())
            }
        }
    };
    ($name:ident, |$ctx:ident| $body:block) => {
        #[derive(Default)]
        pub struct $name;

        impl $crate::Guard for $name {
            fn can_activate(
                &self,
                $ctx: &$crate::RequestContext,
            ) -> Result<(), $crate::HttpException> {
                $body
            }
        }
    };
}

#[macro_export]
macro_rules! auth_guard {
    ($name:ident) => {
        #[derive(Default)]
        pub struct $name;

        impl $crate::Guard for $name {
            fn can_activate(
                &self,
                ctx: &$crate::RequestContext,
            ) -> Result<(), $crate::HttpException> {
                if ctx.is_authenticated() {
                    Ok(())
                } else {
                    Err($crate::HttpException::unauthorized(
                        "Authentication required",
                    ))
                }
            }
        }
    };
}

#[macro_export]
macro_rules! role_guard {
    ($name:ident, $role:expr) => {
        #[derive(Default)]
        pub struct $name;

        impl $crate::Guard for $name {
            fn can_activate(
                &self,
                ctx: &$crate::RequestContext,
            ) -> Result<(), $crate::HttpException> {
                if !ctx.is_authenticated() {
                    return Err($crate::HttpException::unauthorized(
                        "Authentication required",
                    ));
                }

                if ctx.has_role($role) {
                    Ok(())
                } else {
                    Err($crate::HttpException::forbidden(format!(
                        "Missing required role `{}`",
                        $role
                    )))
                }
            }
        }
    };
}

#[macro_export]
macro_rules! interceptor {
    ($name:ident) => {
        #[derive(Default)]
        pub struct $name;

        impl $crate::Interceptor for $name {
            fn around(
                &self,
                _ctx: $crate::RequestContext,
                req: axum::extract::Request,
                next: $crate::NextFn,
            ) -> $crate::NextFuture {
                Box::pin(async move { (next)(req).await })
            }
        }
    };
    ($name:ident, |$ctx:ident, $req:ident, $next:ident| $body:block) => {
        #[derive(Default)]
        pub struct $name;

        impl $crate::Interceptor for $name {
            fn around(
                &self,
                $ctx: $crate::RequestContext,
                $req: axum::extract::Request,
                $next: $crate::NextFn,
            ) -> $crate::NextFuture {
                Box::pin(async move $body)
            }
        }
    };
}

#[macro_export]
macro_rules! middleware {
    ($name:ident) => {
        #[derive(Default)]
        pub struct $name;

        impl $crate::NestMiddleware for $name {
            fn handle(
                &self,
                req: axum::extract::Request<axum::body::Body>,
                next: $crate::NextFn,
            ) -> $crate::NextFuture {
                Box::pin(async move { (next)(req).await })
            }
        }
    };
    ($name:ident, |$req:ident, $next:ident| $body:block) => {
        #[derive(Default)]
        pub struct $name;

        impl $crate::NestMiddleware for $name {
            fn handle(
                &self,
                $req: axum::extract::Request<axum::body::Body>,
                $next: $crate::NextFn,
            ) -> $crate::NextFuture {
                Box::pin(async move $body)
            }
        }
    };
}

#[macro_export]
macro_rules! request_decorator {
    ($name:ident => $output:ty, |$ctx:ident, $parts:ident| $body:block) => {
        pub struct $name;

        impl $crate::RequestDecorator for $name {
            type Output = $output;

            fn extract(
                $ctx: &$crate::RequestContext,
                $parts: &axum::http::request::Parts,
            ) -> Result<Self::Output, $crate::HttpException> {
                $body
            }
        }
    };
}
#[cfg(feature = "graphql")]
pub use nestforge_graphql::{
    async_graphql, graphql_auth_identity, graphql_container, graphql_request_id, graphql_router,
    graphql_router_with_config, resolve_graphql, GraphQlConfig, GraphQlSchema,
};
#[cfg(all(feature = "grpc", feature = "microservices"))]
pub use nestforge_grpc::{dispatch_grpc_event, dispatch_grpc_message};
#[cfg(feature = "grpc")]
pub use nestforge_grpc::{prost, tonic, GrpcContext, GrpcServerConfig, NestForgeGrpcFactory};
#[cfg(feature = "mongo")]
pub use nestforge_mongo::{InMemoryMongoRepo, MongoConfig};
#[cfg(feature = "openapi")]
pub use nestforge_openapi::{
    docs_router, docs_router_with_config, OpenApiConfig, OpenApiDoc, OpenApiRoute, OpenApiUi,
};
#[cfg(feature = "orm")]
pub use nestforge_orm::{EntityMeta, OrmError, Repo, RepoFuture, SqlRepo, SqlRepoBuilder};
#[cfg(feature = "redis")]
pub use nestforge_redis::{InMemoryRedisStore, RedisConfig};
#[cfg(feature = "schedule")]
pub use nestforge_schedule::{
    shutdown_schedules, start_schedules, ScheduleRegistry, ScheduleRegistryBuilder, ScheduledJob,
    ScheduledJobKind,
};
#[cfg(feature = "testing")]
pub use nestforge_testing::{TestFactory, TestingModule};
#[cfg(all(feature = "websockets", feature = "microservices"))]
pub use nestforge_websockets::{
    handle_websocket_microservice_message, WebSocketMicroserviceFrame, WebSocketMicroserviceKind,
    WebSocketMicroserviceResponse,
};
#[cfg(feature = "websockets")]
pub use nestforge_websockets::{
    websocket_gateway_router, websocket_gateway_router_with_config, websocket_router,
    websocket_router_with_config, CloseFrame, Message, Utf8Bytes, WebSocket, WebSocketConfig,
    WebSocketContext, WebSocketGateway,
};

pub mod prelude {
    pub use crate::{
        authenticated, controller, delete, dto, entity, entity_dto, get, identifiable, injectable,
        module, post, put, response, response_dto, routes, summary, tag, use_exception_filter,
        use_guard, use_interceptor, version, ApiSerializedResult, HttpException, Inject,
        NestForgeFactory, Param, Query, Serialized, Validate,
    };

    #[cfg(feature = "openapi")]
    pub use crate::NestForgeFactoryOpenApiExt;
    #[cfg(feature = "websockets")]
    pub use crate::NestForgeFactoryWebSocketExt;
    #[cfg(feature = "grpc")]
    pub use crate::NestForgeGrpcFactory;
    #[cfg(all(feature = "microservices", feature = "testing"))]
    pub use crate::TestFactory;
    #[cfg(feature = "config")]
    pub use crate::{ConfigModule, ConfigOptions, FromEnv};
    #[cfg(feature = "graphql")]
    pub use crate::{GraphQlConfig, NestForgeFactoryGraphQlExt};
    #[cfg(feature = "microservices")]
    pub use crate::{MicroserviceClient, TransportMetadata};
}

#[cfg(feature = "openapi")]
pub fn openapi_doc_for_module<M: ModuleDefinition>(
    title: impl Into<String>,
    version: impl Into<String>,
) -> anyhow::Result<OpenApiDoc> {
    let routes = collect_module_route_docs::<M>()?;
    Ok(OpenApiDoc::from_routes(title, version, routes))
}

#[cfg(feature = "openapi")]
pub fn openapi_docs_router_for_module<M: ModuleDefinition>(
    title: impl Into<String>,
    version: impl Into<String>,
) -> anyhow::Result<axum::Router<Container>> {
    let doc = openapi_doc_for_module::<M>(title, version)?;
    Ok(docs_router(doc))
}

#[cfg(feature = "openapi")]
pub fn openapi_docs_router_for_module_with_config<M: ModuleDefinition>(
    title: impl Into<String>,
    version: impl Into<String>,
    config: OpenApiConfig,
) -> anyhow::Result<axum::Router<Container>> {
    let doc = openapi_doc_for_module::<M>(title, version)?;
    Ok(docs_router_with_config(doc, config))
}

#[cfg(feature = "openapi")]
pub trait NestForgeFactoryOpenApiExt<M: ModuleDefinition> {
    fn with_openapi_docs(
        self,
        title: impl Into<String>,
        version: impl Into<String>,
    ) -> anyhow::Result<Self>
    where
        Self: Sized;

    fn with_openapi_docs_config(
        self,
        title: impl Into<String>,
        version: impl Into<String>,
        config: OpenApiConfig,
    ) -> anyhow::Result<Self>
    where
        Self: Sized;
}

#[cfg(feature = "openapi")]
impl<M: ModuleDefinition> NestForgeFactoryOpenApiExt<M> for NestForgeFactory<M> {
    fn with_openapi_docs(
        self,
        title: impl Into<String>,
        version: impl Into<String>,
    ) -> anyhow::Result<Self> {
        let router = openapi_docs_router_for_module::<M>(title, version)?;
        Ok(self.merge_router(router))
    }

    fn with_openapi_docs_config(
        self,
        title: impl Into<String>,
        version: impl Into<String>,
        config: OpenApiConfig,
    ) -> anyhow::Result<Self> {
        let router = openapi_docs_router_for_module_with_config::<M>(title, version, config)?;
        Ok(self.merge_router(router))
    }
}

#[cfg(feature = "graphql")]
pub trait NestForgeFactoryGraphQlExt<M: ModuleDefinition> {
    fn with_graphql<Query, Mutation, Subscription>(
        self,
        schema: GraphQlSchema<Query, Mutation, Subscription>,
    ) -> Self
    where
        Query: async_graphql::ObjectType + Send + Sync + 'static,
        Mutation: async_graphql::ObjectType + Send + Sync + 'static,
        Subscription: async_graphql::SubscriptionType + Send + Sync + 'static,
        Self: Sized;

    fn with_graphql_config<Query, Mutation, Subscription>(
        self,
        schema: GraphQlSchema<Query, Mutation, Subscription>,
        config: GraphQlConfig,
    ) -> Self
    where
        Query: async_graphql::ObjectType + Send + Sync + 'static,
        Mutation: async_graphql::ObjectType + Send + Sync + 'static,
        Subscription: async_graphql::SubscriptionType + Send + Sync + 'static,
        Self: Sized;
}

#[cfg(feature = "graphql")]
impl<M: ModuleDefinition> NestForgeFactoryGraphQlExt<M> for NestForgeFactory<M> {
    fn with_graphql<Query, Mutation, Subscription>(
        self,
        schema: GraphQlSchema<Query, Mutation, Subscription>,
    ) -> Self
    where
        Query: async_graphql::ObjectType + Send + Sync + 'static,
        Mutation: async_graphql::ObjectType + Send + Sync + 'static,
        Subscription: async_graphql::SubscriptionType + Send + Sync + 'static,
    {
        self.merge_router(graphql_router(schema))
    }

    fn with_graphql_config<Query, Mutation, Subscription>(
        self,
        schema: GraphQlSchema<Query, Mutation, Subscription>,
        config: GraphQlConfig,
    ) -> Self
    where
        Query: async_graphql::ObjectType + Send + Sync + 'static,
        Mutation: async_graphql::ObjectType + Send + Sync + 'static,
        Subscription: async_graphql::SubscriptionType + Send + Sync + 'static,
    {
        self.merge_router(graphql_router_with_config(schema, config))
    }
}

#[cfg(feature = "websockets")]
pub trait NestForgeFactoryWebSocketExt<M: ModuleDefinition> {
    fn with_websocket_gateway<G>(self, gateway: G) -> Self
    where
        G: WebSocketGateway,
        Self: Sized;

    fn with_websocket_gateway_config<G>(self, gateway: G, config: WebSocketConfig) -> Self
    where
        G: WebSocketGateway,
        Self: Sized;
}

#[cfg(feature = "websockets")]
impl<M: ModuleDefinition> NestForgeFactoryWebSocketExt<M> for NestForgeFactory<M> {
    fn with_websocket_gateway<G>(self, gateway: G) -> Self
    where
        G: WebSocketGateway,
    {
        self.merge_router(websocket_gateway_router(gateway))
    }

    fn with_websocket_gateway_config<G>(self, gateway: G, config: WebSocketConfig) -> Self
    where
        G: WebSocketGateway,
    {
        self.merge_router(websocket_gateway_router_with_config(gateway, config))
    }
}