[discussion]: improve the ``Controller`` annotation to becomme truly object-oriented
See original GitHub issueHello and a suggestion about Controller
.
Controller
is really useless in the real programming world, especially to handle RESTful routes. For example, a blog application has roughly the following requests:
Request | Method | Url |
---|---|---|
list blogs | GET | /blogs |
create a blog | POST | /blogs |
delete a blog | DELETE | /blogs/:id |
show a blog | GET | /blogs/:id |
update the title of a blog | PUT | /blogs/:id/title |
update the content of a blog | PUT | /blogs/:id/content |
Current solution
Currently, you have to write 4 classes:
@Controller('blogs')
export class BlogsController {
@Get()
list(): string {}
@Post()
create(): void {}
}
@Controller('blogs/:id')
export class BlogController {
@Delete()
delete(): void {}
@Get()
show(): string {}
}
@Controller('/blogs/:id/title')
export class BlogTitleController {
@Put()
updateTitle(): void {}
}
@Controller('/blogs/:id/content')
export class BlogContentController {
@Put()
updateContent(): void {}
}
This makes the code weird. And this has no object-oriented taste. Because the methods of the Controller
class are isolated from each other, there is no side effect between them.
Improved solution
So, can we make the Controller
class looks like more object oriented? A Controller
a route.
Just like:
@Controller('Get', 'blogs')
export class ListBlogsController {
onResponse() {}
}
@Controller('Post', 'blogs')
export class CreateBlogController {
onResponse() {}
}
// ...
Then we can extend these classes to append more hook methods to becomme truly object-oriented:
@Controller('Post', 'blogs')
export class MyCreateBlogController extends CreateBlogController {
private title: string = ""
private content: string = ""
onSessionCheck(): boolean {}
onValidate(): boolean {
// validate req.body.title and req.body.content
// return false if validate failure
...
this.title = req.body.title;
this.content = req.body.content ;
return true;
}
onSave() {
this.mysql.save(this.title, this.content);
}
onResponse() {}
}
This has several advantages:
-
Each
Controller
class represents a route (request - to - response) -
The session check, data validation, storage, and response for each request can be written in separate methods.
-
Each method can be tested separately.
Issue Analytics
- State:
- Created 5 years ago
- Comments:10 (3 by maintainers)
@tulayang They still don’t have to be in the same controller. This is how I’d organize the two routes.
This thread has been automatically locked since there has not been any recent activity after it was closed. Please open a new issue for related bugs.