Example: overloaded controller

Here is some code that demonstrates what not to do. It's an example of a RESTful API controller class. In it, only the createUser method is shown, but given the class name AppController, it's rightful to assume that this controller would contain all of the methods for the app's REST api.

// AppController.ts

export class AppController {
  ...
  createUser (req: express.Request, res: express.Response): Promise<void> {
    // Get values from request
    const { username, email, password } = req.body;

    // Validate request values
    const isUsernameValid = TextUtils.isAtLeast(3, username) 
      && TextUtils.isAtMost(30, username);
    const isEmailValid = TextUtils.isValidEmail(email)
    const isPasswordValid = TextUtils.isAtLeast(3, password) 
      && TextUtils.isAtMost(25, password);

    // Check if username has already been taken
    const existingUserByUserName = await this.userRepo
      .getUserByUserName(username);

    if (existingUserByUserName) {
      return res.status(409).json({ 
        message: "Username already taken" 
      });
    }

    // Check if email already exists
    const existingUserByEmail = await this.userRepo
      .getUserByEmail(email);
    
    if (existingUserByEmail) {
      return res.status(409).json({ 
        message: "User already exists. Try logging in." 
      });
    }

    // Otherwise, create the user
    const user = await this.userRepo.create({
      username,
      email,
      password
    })

    // Send email verification email
    await this.emailService.sendVerificationEmaill(user.email);

    // Add email to mailing list
    await this.mailingList.add(user.email);
    
    // Do more stuff...
    ...
  }
}

Without going on a tangent, this file has the potential to become very large.

In a request, there are…

Howdy 👋

This is an online wiki and book about the basics of software design and architecture with TypeScript by Khalil Stemmler, Developer Advocate @ Apollo GraphQL .

This book’s mission is to teach developers the essential skills and practices to write testable, flexible, and maintainable code.

You can read more about the learning journey in the "Software Design and Architecture Roadmap 🖼️".

Already bought it?

If you’ve already purchased the book, click here to re-send your link. You can read the online wiki or download a copy of the book in PDF, EPUB, and Kindle versions.

Want access?

You can read the intro to the book for free and visit solidbook.io to buy the book/wiki (it's currently on pre-sale for 33% off)! For recent updates, click here. To get an idea of my writing, read some of my best free content here and here.

Need help?

Something not working? Have a question? You can reach me on Twitter or khalil@khalilstemmler.com.