Simple questions about modularity

Hi, I am re-structuring my code and I wanted to ask if it makes sense to put al lot off common prisma queries within function, e.g. in a simple getBalance function where I need the account data, I could make an accountService and make the code a bit cleaner in my eyes. Does this makes sense, it's my first big project, and I want to do some best practices cause the code needs to be adaptable with the future in mind. I would appreciate any quick feedback on this from someone more experienced!
No description
No description
No description
2 Replies
RaphaelEtim
RaphaelEtim2w ago
Hi @Jeroen_v_g It's a good idea to group common Prisma queries in service functions. Since you're using Nestjs, you can also inject services into controllers instead of using static methods like you're doing. For example:
@Injectable()
export class AccountService {
constructor(private prisma: PrismaService) {}

async findAccountById(accountId: number): Promise<Account | null> {
return this.prisma.account.findUnique({
where: { accountId },
});
}
}
@Injectable()
export class AccountService {
constructor(private prisma: PrismaService) {}

async findAccountById(accountId: number): Promise<Account | null> {
return this.prisma.account.findUnique({
where: { accountId },
});
}
}
In the controller, you can then do something like:
@Controller('account')
export class AccountController {
constructor(private accountService: AccountService) {}

@Get('balance')
async getBalance(@Req() req: Request, @Res() res: Response) {
const accountId = req.user.accountId;
try {
const account = await this.accountService.findAccountById(accountId);
if (!account) {
return res.status(404).json({ error: 'Account not found' });
}
const balance = await getAccountBalance(accountId);
return res.status(200).json(balance);
} catch (error) {
return res.status(500).json({ error: error.message });
}
}
}
@Controller('account')
export class AccountController {
constructor(private accountService: AccountService) {}

@Get('balance')
async getBalance(@Req() req: Request, @Res() res: Response) {
const accountId = req.user.accountId;
try {
const account = await this.accountService.findAccountById(accountId);
if (!account) {
return res.status(404).json({ error: 'Account not found' });
}
const balance = await getAccountBalance(accountId);
return res.status(200).json(balance);
} catch (error) {
return res.status(500).json({ error: error.message });
}
}
}
Jeroen_v_g
Jeroen_v_gOP2w ago
Thank you! I have builded a whole game, without using classes x) was only possible by using prisme though I think
Want results from more Discord servers?
Add your server