Using the service

Services

Now that you've created a service, let's use it in a command.

To use a service within middleware use the manager property on the Context like so:

const myService = context.manager.getService(MyService)

Note that we pass the MyService class, not a string. This is important because it makes it possible to be typesafe with TypeScript.

Now, we can get the count from the service:

const command = new Command()
  .match(matchPrefixes("count"))
  .use((context) => {
    const myService = context.manager.getService(MyService)

    console.log(`The count is ${myService.count}`)
  })

// Input: "count"
// Output: "The count is 0"

Adding a method

Let's add a method to the service to increment the count.

class MyService extends Service {
  serviceDidInitialize() {
    this.count = 0
  }

  increment() {
    this.count += 1
  }
}

And now we can use this to increment the count in our command:

const command = new Command()
  .match(matchPrefixes("count"))
  .use((context) => {
    const myService = context.manager.getService(MyService)

    myService.increment()
    console.log(`The count is ${myService.count}`)
  })

// Input: "count"
// Output: "The count is 1"

// Input: "count"
// Output: "The count is 2"

// Input: "count"
// Output: "The count is 3"
Creating a service