I’m creating an API with ExpressJS with Typescript, and my project architecture is like this ( “->” means “calls”):
Route -> Controller -> Service -> Repository
I’m wondering if making the Controllers, Services & Repositories, static could be a good practice or not for my project, let me give you an example of code.
Route.ts:
import { Router} from 'express';
import MyController from '../Controllers/MyController'
const router = Router();
router.get('/api-route', MyController.getData);
export default router;
MyController.ts:
import { Request, Response } from 'express';
import MyController from '../Controllers/MyController'
export default class MyController {
public static async getData(request: Request, response: Response) {
const body: any = request.body;
// Do request validation... (e.g. Validate JWT)
let data: Data | undefined = await MyService.getData(body["secret-code"]);
if (!data)
return response.status(403).json("Wrong secret code!");
return response.status(200).json(data);
}
}
MyService.ts
export default class MyService {
public static async getData(secretCode: string): Data | undefined {
if (secretCode !== "TheSecret")
return undefined;
return await MyRepository.getData();
}
}
MyRepository.ts
export default class MyRepository {
public static async getData(): Data {
// This is pseudo code to get data from database.
return await Database.Connect(EnvVariableConnectionString).Get("data");
}
}
Considering this code where I don’t “have” to instantiate any object I don’t see the point of non-static methods, am I wrong?
For security and concurrency purposes is that code valid? Why?
If I should not use static methods, where should I instantiate the Controllers, Services & Repositories?
3