Make Nodejs API S Great With TypeScript Dmytro Zharkov
Make Nodejs API S Great With TypeScript Dmytro Zharkov
ABOUT ME
http://bit.ly/2FAm3Lr
http://bit.ly/2FAm3Lr
NODEJS REPUTATION
FRONT-END DEVELOPERS
NodeJS
What’s wrong with NodeJS APIs?
4
TYPESCRIPT FOR A RESQUE
TYPE ALIASES
public port: number;
INTERFACES
protected server: http.Server;
CLASSES
public article: Article;
LET’S COMPARE
CLASSES
● Reference types only
● Can be extended
● Signature and implementation
INTERFACES
interface BaseArticle {
SKU: string, interface FashionArticle extends BaseArticle {
name: string, size: Sizes,
type: string, color: Colors
price: Price }
}
export default FashionArticle;
export default BaseArticle;
export {ArticleModel};
MORE INTERFACES
}
ACCESS MODIFIERS
PUBLIC
Default modifier and can be omitted
(better not).
PRIVATE
Restics members visibility to current
class only.
PROTECTED
Visible in derived classes.
IN PRACTICE
class Server {
import * as io from "socket.io";
protected app: express.Application;
protected server: http.Server;
class SocketServer extends Server {
public port: number;
private socketServer: io.Server;
constructor(port: number = 3000) {
constructor(public port: number) {
this.app = express();
super(port);
this.port = port;
this.socketServer = io(this.server);
this.app.set("port", port);
….
this.app.listen(this.port);
}
}
}
}
DECORATORS
CLASSES METHODS
PARAMETERS FIELDS
EXAMPLE: TRY-CATCH WRAPPER
class TestClass {
@safe
public doSomething(str: string): boolean {
return str.length > 0;
}
return descriptor;
}
EXAMPLE: DECLARATIVE ROUTES
@Get()
public resources(req: Request, res: Response) {
res.json([]);
}
@Get("/:id")
public resources(req: Request, res: Response) {
res.json({});
}
}
EXAMPLE: REQUEST VALIDATION
@Validate({
param: "name",
validate: "required"
})
public createArticle(request: Request, response: Response): void {
// create an article
}
EXAMPLE: REQUEST VALIDATION
descriptor.value = function () {
const body = arguments[0].body;
const response = arguments[1];
// do some work
};
return descriptor;
};
}
EXAMPLE: HATEOAS
DEMO
DOCUMENTATION
TSOA
AUTO SWAGGER DOCUMENTATION WITH DECORATORS
TSOA
@Route("Users")
class ArticlesService {
@Post()
public createArticle(@Body() requestBody: FashionArticle): Promise<FashionArticle> {
// create an article
}
}
SUPERTEST
DEBUG DIRECTLY IN TS
DRAWBACKS
Additional build step.
Slides
NodeJS TypeScript starter http://bit.ly/2FW64qn
TSOA auto swagger documentation http://bit.ly/2FW64qn