Skip to content

Services

Josh Wright edited this page Jan 14, 2021 · 4 revisions

Services

Provides easy access to some commonly used services in Alchemy. These services are Injected from the global Container. You can add your own services in extensions if you'd like.

public enum Services
Services.db
// equivalant to
Container.global.resolve(Database.self)
// equivalent to
@Inject
var db: Database

Properties

db

The main database of your app. By default, this isn't registered, so don't forget to do so in your Application.setup!

var db: Database
struct MyServer: Application {
    func setup() {
        Services.db = PostgresDatabase(
            DatabaseConfig(
                socket: .ip(host: "localhost", port: 5432),
                database: "alchemy",
                username: "admin",
                password: "password"
            )
        )
    }
}

// Now, `Services.db` is usable elsewhere.
Services.db // `PostgresDatabase(...)` registered above
    .runRawQuery("select * from users;")
    .whenSuccess { rows in
        print("Got \(rows.count) results!")
    }

router

The router to which all incoming requests in your application are routed.

var router: Router

scheduler

A scheduler for scheduling recurring tasks.

var scheduler: Scheduler

client

An HTTPClient for making HTTP requests.

var client: HTTPClient

Usage:

Services.client
    .get(url: "https://swift.org")
    .whenComplete { result in
        switch result {
        case .failure(let error):
            ...
        case .success(let response):
            ...
        }
    }

eventLoop

The current EventLoop.

var eventLoop: EventLoop

eventLoopGroup

The EventLoopGroup of this application.

var eventLoopGroup: EventLoopGroup

threadPool

A NIOThreadPool for running expensive/blocking work on.

var threadPool: NIOThreadPool

By default, this pool has a number of threads equal to the number of logical cores on this machine. This pool is created and started when first accessed.

lifecycle

A ServiceLifecycle hooking into this application's lifecycle.

var lifecycle: ServiceLifecycle

Methods

mock()

Mocks many common services. Can be called in the setUp() function of test cases.

public static func mock()
Alchemy
Types
Protocols
Global Typealiases
Global Variables
Global Functions
Fusion
Types
Protocols
Papyrus
Types
Protocols
Clone this wiki locally