Skip to content

Restful Controllers

For those familiar with backend development, especially those who know Spring/Nest.js, the concept of controllers should not be unfamiliar.

In unioc, controllers are used to create routes and can contain multiple routes.

Creating Controllers

ts
import { 
Get
,
RestController
} from 'unioc/web'
@
RestController
()
export class
AppController
{
@
Get
('/')
async
index
() {
return 'Hello World' } }

Then, import this controller in your application's main entry point:

ts
import { 
ExpressApp
} from 'unioc/web-express'
// Import the controller import './app.controller' async function
bootstrap
():
Promise
<void> {
// Below is your App startup logic, for example, if you want to create an Express application const
app
= new
ExpressApp
()
// Start the application await
app
.
run
(3000)
}
bootstrap
()

Above is an example of creating an Express application. You can also create a Koa application, and with just a simple import statement in the main entry point, it can be automatically discovered by unioc and routes will be created automatically based on your controllers.

Using with Vite

When using unioc with Vite, import.meta.glob is very convenient, effectively implementing features similar to Spring's automatic package scanning @ComponentScan.

This is a feature only available in Vite. You can pass a glob path, and you won't need to manually import controllers anymore.

ts
/// <reference types="vite/client" />
import { 
ExpressApp
} from 'unioc/web-express'
// This means automatically importing all ts files in the ./controllers directory, // so you don't need to import them one by one, very very convenient ✨ import.meta.
glob
('./controllers/*.ts', {
eager
: true })
async function
bootstrap
():
Promise
<void> {
// Below is your App startup logic, for example, if you want to create an Express application const
app
= new
ExpressApp
()
// Start the application await
app
.
run
(3000)
}
bootstrap
()

NOTE

For import.meta.glob documentation, please refer to the Vite Official Documentation.

Contributors

Changelog