
Node js TypeScript Fastify EP 06 Services
In this episode, you will learn about services. Services contain the business logic of your application.
What is a service?
A service is where you put your business logic. It handles things like getting data or processing information. Controllers call services.
Step 1 - Create services folder
Create a new folder called services inside the src folder.
Step 2 - Create article service
Create a new file called article.service.ts inside the src/services folder.
export const getArticles = () => {
const data = {
id: "1",
name: "node.js fastify",
desc: "Fast and easy course for building APIs"
}
return { response: data }
}
export default {
getArticles
}This service function returns article data. Later, it will get data from a database.
Step 3 - Create services index file
Create a new file called index.ts inside the src/services folder.
import articleService from "./article.service";
export { articleService };Step 4 - Update the controller to use the service
Now update your src/controllers/article.controller.ts file to use the service.
import { articleService } from "../services";
export const handleGetArticle = () => {
return articleService.getArticles()
}
export default {
handleGetArticle
}Now your controller calls the service. This separates the request handling from the business logic.
Originally published by me at the dev to - Akkarapon Phikulsri on DEV Community.


