To process HTTP requests using Deepkit, you can define routes either using the functional API or controller classes. In the functional API, you can use the HttpRouterRegistry
to define routes and their corresponding handlers. Here's an example:
import { App } from '@deepkit/app'; import { FrameworkModule } from '@deepkit/framework'; import { HttpRouterRegistry, HttpBody } from '@deepkit/http'; const app = new App({ imports: [new FrameworkModule()] }); const router = app.get(HttpRouterRegistry); router.get('/user/:id', (id: number, database: Database) => { // Do something with the id and database // Return the result }); router.post('/user', (user: HttpBody<User>) => { // Do something with the user // Return the result });
In the above example, we define two routes: a GET route /user/:id
that takes an id
parameter and a database
dependency, and a POST route /user
that takes a user
object as the request body.
As an alternative to the functional API, you can also use controller classes to define routes. Here's an example:
import { http } from '@deepkit/http'; class UserController { constructor(private database: Database) {} @http.GET('/user/:id') getUser(id: number) { // Route logic } @http.POST('/user') createUser(user: HttpBody<User>) { // Route logic } } const app = new App({ controllers: [UserController], imports: [new FrameworkModule()] });
In both can be seen that you don't handle the HTTP request directly, but instead define a function or method that takes data out of the request automatically by declaring what you expect and need. Deepkit will automatically convert the parameters to the correct types and validate them based on the defined types. This way get API documentation for free either from Deepkit API Console or OpenAPI.