Inquiry regarding the implementation of DTO within a service layer parameter

I have a query regarding the choice of service layer to use.

// 1
export class SomeService{
  async create(dto:CreateSomeDto) {}
}

or

// 2 
export class SomeService{
  async create(title: string, content: string) {}
}

It appears that most individuals opt for option 1.

Nevertheless, I came across an article suggesting that this approach leads to increased interdependence between the controller and the service layer.

The argument is that the controller layer should rely on the service layer in a unidirectional manner.

There may not be a definitive answer, but could you help elucidate the advantages and disadvantages of each approach?

Answer №1

Using method 1 may save a small amount of time by not having to redefine DTO type definitions for service methods, but ultimately it is not worth the trade-off. It is recommended to use method 2 instead.

As your application grows, there may be instances where service methods are called from other services or controllers. This can lead to situations where callers of a service must provide unnecessary extra parameters in order to call the method.

For example, consider a scenario where you have a UsersService and UsersController for handling user registration:

class UsersController() {
  @Post('register')
  register(@Body() dto: RegisterUserDto) {
    const isVerified = this.verificationService.verify(dto.code);
    if (isVerified) {
      return this.usersService.create(dto);
    }
  }
}

class UsersService() {
  create(dto: RegisterUserDto) {
    // create user... 
  }
}

Everything works fine until a few months later when a client requests the ability to manually add users from their dashboard. Even though you already have an implemented create method in UsersService, you cannot directly use it in

AdminController</code because the method requires a <code>code
parameter. The compiler will not allow you to call the method without providing the required parameter, even if it is not actually used in the create method.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The createReadStream function cannot be found in the uploaded image

I am currently using node v14.17.0, "apollo-server-express": "^2.25.0", "graphql-upload": "^12.0.0" I'm facing an issue with uploading an image as I don't receive the createReadStream from the image that I upload via graphiql. Specifically, I am ...

Utilizing Express routes in Node.js to rewrite URLs for proxying to Etherpad

Welcome to my first question on stackoverflow ;). What I am attempting to accomplish: My goal is to create an express route "/pad/*" that will display etherpads (etherpad lite) and allow manipulation of the pad that the user will see. For example, if the ...

Is it possible to view the frames/packets being transmitted from an EJS or HTML form to the Express backend using Express Js?

My current computer science assignment involves visually representing the data transfer process between a frontend and backend. I don't need to show the full data, just the flow of chunks and how it navigates through protocols. Could someone please g ...

Adding API endpoints to a Nuxt and Express application created with create-nuxt-app

After using the create-nuxt-app npm command, I ended up with a server/index.js file for my app. const express = require('express') const consola = require('consola') const { Nuxt, Builder } = require('nuxt') const app = expre ...

An error was encountered in compiler.js at line 1021, stating that an unexpected value 'UserService' was imported by the module 'UserModule'. It is recommended to add a @NgModule annotation to resolve this issue

As a PHP programmer new to Angular, I am facing an issue while trying to retrieve user properties from a Laravel API. When attempting this, I encountered the following error: compiler.js:1021 Uncaught Error: Unexpected value 'UserService' importe ...

Generating a random number to be input into the angular 2 form group index can be done by following these

One interesting feature of my form is the dynamic input field where users can easily add more fields by simply clicking on a button. These input fields are then linked to the template using ngFor, as shown below: *ngFor="let data of getTasks(myFormdata); ...

The values of variables persist even after refreshing the page

let quote; let author; // Establishing the Get Method for the Root Route in ExpressJS app.get('/', (req, res)=>{ res.render('home', { quote: quote, writer: author }); }); // Configuring the Post Method for t ...

I'm trying to figure out how to incorporate types for utilizing Intl.ListFormat in node v12. Can

I am currently working with nodeJS version 12.10.0, which now includes support for Intl.ListFormat. I am also using Typescript version 3.6.3. However, when compiling my code with Typescript, I encounter the following error: Property 'ListFormat' ...

What steps should I follow to deploy both my backend and frontend applications using Nginx?

server{ listen 80 ; listen [::]:80; server_name test.demo.io; root /home/ubuntu/SuperApp/build; location / { try_files $uri /index.html; } } This nginx configuration file is specifically for my frontend application develop ...

Exploring Node.js: Deciphering the meaning behind this notation

Recently, I inherited a project from another developer which utilizes the common MEAN stack with server.js as the main entry point. Within server.js, there is a module that includes: var express = require('express'); var app = express(); v ...

Angular 8 HTTP Interceptor causing issues with subscriptions

I'm currently in the process of setting up an Angular 8 project that will allow me to mock API calls using HTTP INTERCEPTORS. My approach involves adding a --configuration=mock flag to my ng serve script so that the interceptor is injected into my app ...

Adding HTML content to routes in ExpressOrEnhancing routes

Recently, I've been working with a basic index.html file. My goal is to have the routes file append an HTML button when requested by the browser without actually modifying the original file. This may seem like a peculiar idea, but my intention is to c ...

Error encountered when trying to access the new route

I'm facing an issue while attempting to create a new route (/profile) for my NodeJS Express web application. In order to implement this, I made adjustments to my app.js file as shown below: var routes = require('./routes/index'); var profil ...

Managing Cookie Expiration in Node.js with Express and Passport

Incorporating Passport for authentication in my application, alongside the usage of Express, I have encountered a perplexing issue: the login process functions correctly initially, but subsequent to any user session expiration, no users are able to log bac ...

Route user based on login status using router

I want to set up automatic routing to a login page for users who are not logged in. app.module.ts import { RouterModule, Routes } from '@angular/router'; import { AppComponent } from './app.component'; import { LoginComponent } from &ap ...

After clicking on the "Delete Rows" button in the table, a white color suddenly fills the background in Angular Material

When the dialog box pops up, you'll see a white background color: https://i.stack.imgur.com/EflOx.png The TypeScript code for this action can be found in config-referrals.component.ts openDialog(action, obj) { this.globalService.configA ...

Using Node.js and Express 3 to set asynchronous app.locals values

Exploring the differences between app.locals and res.locals in Node.js and Express 3.0, I have a specific scenario at hand... I aim to define two app.locals variables ('newest' and 'popular') that should be accessible globally across a ...

When I specify the type for the function parameter, an error occurs when I attempt to execute the function

When I assign a generic type to the function parameter and try to call the function, an error message pops up stating "This expression is not callable. Type unknown has no call signature." function a() { return 'abc' } function fun<T>(x: T ...

Search for words in a given string that begin with the symbol $ using Angular 2

I am trying to locate words that begin with $. var str = "$hello, this is a $test $john #doe"; var re = /(?:^|\W)\$(\w+)(?!\w)/g, match, results = []; while (match = re.exec(str)) { results.push(match[1]); } The regular expression a ...

Passing an object from @CanActivate() to a component in Angular 2 leads to Typescript Error

Within Angular 2, I am using a MyObjectComponent to display an array of myObjects. These myObjects are retrieved from a MyObjectService, which is called by @CanActivate. @CanActivate((next: ComponentInstruction, previous: ComponentInstruction) => { ...