Extracting Reusable Code with Services

In this lesson, we'll learn about services and how we can use them to extract reusable code in a way that makes it super simple to use throughout your project.

Published
Jan 27
Duration
7m 4s

Developer, dog lover, and burrito eater. Currently teaching AdonisJS, a fully featured NodeJS framework, and running Adocasts where I post new lessons weekly. Professionally, I work with JavaScript, .Net C#, and SQL Server.

Adocasts

Burlington, KY

Join The Discussion! (2 Comments)

Please sign in or sign up for free to join in on the dicussion.

  1. Commented 1 month ago

    Is a service just a controller?

    0

    Please sign in or sign up for free to reply

    1. Commented 1 month ago

      Hi Luiz! Though they look similar and are traditionally both classes, they aren't the same as one another from a logical standpoint as they're in charge of different things.

      Controllers are used to handle routes. AdonisJS will directly instantiate a new instance of a controller and call the appropriate method bound to the requested route.

      Services generally aid controllers and events to help them complete their objectives. This could be something as simple as a helper, like normalizing text, or as complex as the main action of an operation, like storing a new blog post.

      To put it in a real-world example, let's say you go to a dine-in restaurant. You sit at a table and the server comes over to take your order (determining which of the app's routes you need). They take your order (request) to the chef (our controller). The chef then is in charge of completing your order which may consist of:

      1. Making a burger

      2. Fetching fries

      3. Grabbing that pickle slice

      4. etc

      Any one of those little things could come from a service, but the controller (the chef) coordinates and puts it all together to complete the request (order).

      export default class DinerController {
        async order({ request, view }: HttpContext) {
          const data = await request.validateUsing(orderValidator)
      
          const burger = await BurgerService.getCheeseBurger()
          const fries = await FriesService.getMediumFry()
          const pickle = await CondimentService.getPickleSlice()
      
          return view.render('plate', {
            burger,
            fries,
            pickle
          })
        }
      }
      Copied!
      1

      Please sign in or sign up for free to reply