
Node js TypeScript Fastify EP 05 Controllers
In this episode, you will learn about controllers. Controllers handle the logic for your routes.
What is a controller?
A controller is a function that handles requests. When someone visits a route, the controller decides what to do and what to return.
Step 1 - Create controllers folder
Create a new folder called controllers inside the src folder.
Step 2 - Create article controller
Create a new file called article.controller.ts inside the src/controllers folder.
export const handleGetArticle = () => {
// This is sample data for testing
const article = {
id: "1",
name: "node.js fastify",
desc: "Fast and easy course for building APIs"
}
return {
articles: [
article
]
}
}
export default {
handleGetArticle
}This controller function returns article data. Later, it will get data from a service.
Step 3 - Create controllers index file
Create a new file called index.ts inside the src/controllers folder.
import articlesController from "./article.controller";
export { articlesController };Step 4 - Update the route to use the controller
Now update your src/routes/article.route.ts file to use the controller.
import { FastifyInstance } from "fastify";
import articleController from './../controllers/article.controller';
const articleRouter = async (app: FastifyInstance) => {
// Use the controller function as the handler
app.get(
"/",
articleController.handleGetArticle
);
};
export default articleRouter;Now your route uses the controller. This separates the route logic from the business logic.
Originally published by me at the dev to - Akkarapon Phikulsri on DEV Community.


