- How to Start with Backend TypeScript and use it’s full potential.
- Original author: IdchLife
- The Nuggets translation Project
- Permanent link to this article: github.com/xitu/gold-m…
- Translator: xilihuasi
- Proofread by: tvChan, Noahziheng
How to play the back end in TypeScript?
I’m going to introduce a couple of great libraries from a developer’s perspective. They can satisfy most of the features of your back-end application. Decorator and metadata capabilities are fully utilized in these libraries, making them very powerful and easy to use.
I hope this article will help people like me who love TypeScript and want to write back-end code with it enjoy discovering these libraries as much as I do.
TL; DR — Stack makes your back-end applications as powerful as many enterprise static solutions in other languages:
-
Libraries that use decorators, parameters, body-injected routes, and controllers
-
Libraries for dependency injection and services that use decorators
-
ORM using decorators is as convenient for manipulating entities as Doctrine/Hibernate
-
Tips for those unfamiliar with TypeScript writing backends
Routing-controllers: Controllers, requests, etc
pleerock/routing-controllersRouting-controllers – Create structured, declarative, and well-organized class-based controllers
Although the library is written as a TypeScript helper for Express/Koa, it will also help you write controllers that you use in Java/PHP/C# enterprise frameworks.
Here is a small example of a controller:
import {JsonController, Param, Body, Get, Post, Put, Delete} from "routing-controllers";
@JsonController()
export class UserController {
@Get("/users")
getAll() {
return userRepository.findAll();
}
@Get("/users/:id")
getOne(@Param("id") id: number) {
return userRepository.findById(id);
}
@Post("/users")
post(@Body() user: User) {
returnuserRepository.insert(user); }}Copy the code
This is like getting out of a nightmare for some people: no more routing components, full of nested middleware, and middleware implementations with injection, validation, and request parameters (yes, you can even define parameter types and must-pass! Such as @body ({required: true, validate: true}) will work fine and throw an exception if arguments are missing or the request is incorrect.
Decorators have many useful features, such as @Controller for the base Controller, the ability to define the type of content in actions, and the ability to use the @JsonController service and receive JSON.
I’m using it in Express, Now that we have async/await (even though TS Node.js has been in development for months I can’t help but praise it) we don’t seem to need Koa anymore (now routing-Controllers support Express better). And Express has a much larger set of types, @types.
Here is an example of my project using routing-controllers and other @pleerock libraries (VSCode, if interested, from TypeLens plug-in) :
As you can see, routing-Controllers even provide undefined return codes (as well as empty and NULL decorators) and many other features. About this.playerService — This is another fascinating library that I’ll talk about later.
Overall, the library has a powerful documentation that helps you understand and build applications that work with custom middleware for operations and even the entire controller (this was a great moment for me). The link address as you can see is right there, very handy.
Of course, you can also use a lot of Express/Koa middleware to isolate your application, as well as view configuration (the library also has decorators for views), authentication (which can be applied to the entire control layer through middleware), error handling, and so on.
Usually I put them in the /controllers folder.
TypeDI: Dependency injection, services
Github.com/pleerock/ty…
This library helped me structure my project so it was easy to code and not have to think, “Ok, where does a service exist, this is a service? HMM maybe another one, but how does it depend on another service? How does it reference other services?”
Going back to my PlayerService, here’s where you can see what it depends on:
Inject is the best decorator for me for services and logically complete back-end applications.
(If you want to know about @OrmentityManager — another library from @pleerock, which I’ll explain later)
Yes, you can have many services that depend on other services. And if you have a service loop dependency, you can solve this problem by explicitly defining the type (the library documentation covers most of the problems and scenarios)
For those unfamiliar with Services, service containers, Services dependency injection, etc. Brief description:
You have some functionality, you want to put it in a class, and then you want an instance of that class and you want that class to depend on another one, another one, etc. Dependency injection of the Service container can help you do this. You can get services from the container and it will handle all of the dependencies of services itself, automatically injecting your working instances with other instances.
My description of the library doesn’t cover all of its potential (you can check its documentation for yourself — there are more features you can use) : you can name it when you define services, you can define constructor injection, etc.
Usually I store my services in the /services folder.
TypeORM: Use ORM to define relational entities, convenient for different column types and different data storage schemes (relational, non-relational)
typeorm/typeorm_typeORm — A data-mapper ORM available in TypeScript and JavaScript (ES7, ES6, ES5) environments. Support MySQL, PostgreSQL, MariaDB, SQLite
This gives me the feeling that writing Node.js in TypeScript is finally competitive with other languages and ORMS.
Powerful ORM makes it easy to write entities in an understandable way. I’m not a fan of many other Node.js ORMS like this:
Module. Exports = {id: someorm. Integer, name: someorm. String({... })}Copy the code
I always want entities to be classes. Classes that are assigned attributes of type are discovered by ORMs with simple decorators. It doesn’t even have a type.
TypeORM gives you this ability. Another example from my project:
As you can see, I didn’t even write the type of the attribute in the decorator (you can do that, don’t worry, explicitly define the type, default, nullable, etc.)! TypeORM does all this work for me, learning what types (thanks to TypeScript reflection: Metadata extensions) and applying them to my database.
It is very powerful and you will have everything you have/see in other ORMs such as (Doctrine, Hibernate).
When using routing-Controllers and TypeDI, it provides very useful decorators for you to inject entity managers (as you can see in my PlayerService screenshot) or to connect your controllers to services (which is very handy).
The ORM has an official documentation that covers a lot of features, so you can look at it and learn everything you need to know to get started.
I usually put my database configuration in the /config folder and entities in the /entities folder.
- Why does one article cover all these libraries?
That’s the interesting part.
Routing-controllers are like the foundation of your application. It gives you the possibility to easily connect the two libraries (covered in the library documentation). Of course, you don’t have to if you want to. It can be used with any ORM.
However, when you use all three libraries, you make the framework look too powerful compared to other solutions (at least to me). You have controllers, parameter injection, body injection, parameter validation, dependency injection, and with that you can forget about manually providing dependencies and defining types, entities that decorate properties, query Builders. It’s all in TypeScript! So there will be compile-time type checking on the back end too!
- Yes, thanks to the libraries that cover those features. But again, how do you use TypeScript in Node?
Well, it couldn’t be easier. You can write typescript as usual, configure it to compile to ES2015 (Node now has a lot of features and doesn’t need to compile to pre-ES2015 versions), and implement modules using the CommonJS standard.
And use PM2 or something else to launch index/server/app.js after compilation. Basically the production code is in place. No TS-Node or anything else.
If you like these libraries, don’t forget to express your love
As you can see, not many people know about routing-Controllers and TypeDI, which are the most powerful and useful libraries I use in my TypeScript Node.js project. If you like them, please take a second to star them and advertise them. They’ve helped me a lot, so I hope they help you and other TypeScript users!
These libraries also have gitter communities, and you can easily find them by googling “Gitter library name.”
Thanks for reading and being happy with TypeScript. Feel free to comment or ask questions
The Nuggets Translation Project is a community that translates quality Internet technical articles from English sharing articles on nuggets. The content covers Android, iOS, front-end, back-end, blockchain, products, design, artificial intelligence and other fields. If you want to see more high-quality translation, please continue to pay attention to the Translation plan of Digging Gold, the official Weibo, Zhihu column.