Skip to content
sern

Services

You need some way to use dependencies in your command module. Services to the rescue!

src/dependencies.d.ts
1
import { CoreDependencies, Singleton } from "@sern/handler";
2
import { Client } from "discord.js";
3
4
interface Dependencies extends CoreDependencies {
5
"@sern/client": Singleton<Client>;
6
}

Special Dependencies

Some keys in Dependencies are special and are used by sern internally:

  • @sern/client: Your Discord client. → Emitter
  • @sern/logger: Logging data → Logging
  • @sern/errors: Handling errors and lifetime → ErrorHandling
  • @sern/modules: Managing all command modules → ModuleManager
  • @sern/emitter: The key to emit events and occurences in a project → Emitter

Usage

Lets try to access the client you provided.

src/commands/ping.ts
1
import { Service } from "@sern/handler";
2
3
export default commandModule({
4
// ...
5
execute: (ctx) => {
6
// Type is inferred from the dependencies file.
7
// → Dependencies['@sern/client']
8
const client = Service("@sern/client");
9
},
10
// ...
11
});

Safety

Services cannot be called in other services while makeDependencies is forming.

For example, let’s pass a logger into our database:

Example

index.ts
1
await makeDependencies({
2
build: root => root
3
// Overriding the default logger provided.
4
.upsert({ '@sern/logger': single(() => new Logger()) })
5
6
// Wiring our logger into the database.
7
.add(ctx => {
8
return { database: single(() => new Database(ctx['sern/logger']))) }
9
})
10
})

Another Example

index.ts
1
await makeDependencies(/* ...pass your options here */)
commands/ping.ts
1
// This is guaranteed to be defined if configured correctly
2
import { Service } from "@sern/handler";
3
const client = Service("@sern/client");

Important

  1. Services can only be used after sern has made dependencies.
    → Calling a service before will crash your application.
  2. Services can be safely used outside of a commandModule.
    → Be careful to not cause too many side effects.
  3. You will need to wire dependencies together.
    → This is a good practice to keep your code clean.
  4. Services can only be used after sern has made dependencies.
    → Calling a service before will crash your application.
  5. Services can be safely used outside of a commandModule.
    → Be careful to not cause too many side effects.
  • Use Service for single dependency.
  • Use Services for multiple dependencies.