Facades
Introduction
A facade is a short, global-looking handle to a service in the container. Instead of passing a cache object through your code, you import Cache and call Cache.get('key'). Behind the scenes, the call is forwarded to whatever object the container currently holds for that service.
Facades are built on a JavaScript Proxy. They are optional: dependency injection through the container is the recommended way to wire most code, and facades exist for the places where a terse, importable name reads better, such as in a route file or a small script. Plinth does not ship ready-made facades. You define the ones you want in a line each.
Setting up
Facades need to know which container to resolve from. Point them at your application once, during bootstrap, with Facade.setContainer:
import { Application, Facade } from '@plinthjs/core'
const app = new Application()
Facade.setContainer(app)In the generated app you would add this line in src/bootstrap/app.ts, after the application is created. Until a container is set, using any facade throws:
A facade root has not been set. Call Facade.setContainer(app) first.Defining a facade
createFacade takes the token the service is bound under and returns a proxy with the service's type. Give it the interface or class you want your editor to know about:
import { createFacade } from '@plinthjs/core'
import type { Repository } from '@plinthjs/cache'
export const Cache = createFacade<Repository>('cache')Put each facade in its own module (for example src/facades/cache.ts) and import it where you need it. The token can be a string, a symbol, or a class, exactly as with container.make:
export const Clock = createFacade<ClockService>(ClockService)
export const Db = createFacade<Connection>(DB)Bind the real service as usual, in a service provider:
import { arrayCache } from '@plinthjs/cache'
class CacheServiceProvider extends ServiceProvider {
register(): void {
this.app.singleton('cache', () => arrayCache())
}
}Now the facade works:
await Cache.put('framework', 'Plinth', 60)
await Cache.get('framework') // => 'Plinth'
await Cache.remember('answer', 60, () => 42) // => 42How a facade resolves
A facade holds no service of its own. Every property read, method call, and in check asks the container for the service at that moment and applies the operation to it. Two consequences follow:
- Rebinding a token takes effect immediately, even for code that imported the facade long before. This is what makes faking easy.
- Methods are bound to the resolved instance, so
thisworks inside them. You can even destructure a method:const { describe } = Settingskeeps working.
WARNING
Because the service is resolved on each access, bind it with singleton (or instance) if it holds state. A facade over a plain bind factory gets a fresh object every time, so a property you set, as in Settings.theme = 'dark', would be lost on the next access. A facade passes assignments through to the resolved object, which is only meaningful when that object is shared.
Facades and injected services refer to the same object when the binding is a singleton:
Facade.getContainer() === app // => true
app.make<Repository>('cache') === app.make<Repository>('cache') // => trueFaking a facade in tests
The way to fake a facade is to rebind its token on the container. Facade.swap(token, fake) does exactly that: it registers the fake as the instance for the token and returns it. Every facade pointing at that token now talks to the fake:
import { Facade } from '@plinthjs/core'
const calls: string[] = []
const fake = {
get: async (key: string) => {
calls.push(key)
return 'faked'
},
} as unknown as Repository
Facade.swap('cache', fake)
await Cache.get('anything') // => 'faked'
calls // => ['anything']The fake only needs the methods your test exercises. Cast it to the service's type, as above, or write a small class that implements the interface.
swap replaces the binding until you undo it. Facade.swapWithToken(token, fake) returns { fake, token }, and Facade.restore(token) puts the original service back (or unbinds the token if there was none); Facade.restoreAll() undoes every outstanding swap, most recent first. A reliable test pattern:
let swapped: SwapToken
beforeEach(() => {
swapped = Facade.swapWithToken('cache', fakeCache).token
})
afterEach(() => {
Facade.restore(swapped) // or Facade.restoreAll()
})Or give each test its own application, so there is nothing to undo:
import { Application, Facade } from '@plinthjs/core'
import { beforeEach, afterEach, expect, it } from 'vitest'
beforeEach(() => {
const app = new Application()
app.singleton('cache', () => arrayCache())
Facade.setContainer(app)
})
afterEach(() => {
Facade.clearContainer()
})
it('reads through the cache', async () => {
await Cache.put('k', 'v')
expect(await Cache.get('k')).toBe('v')
})
it('can be faked', async () => {
Facade.swap('cache', { get: async () => 'faked' } as unknown as Repository)
expect(await Cache.get('anything')).toBe('faked')
})If you share one application across tests instead, restore the originals with Facade.restoreAll() after each test. Facade.clearContainer() detaches the facades from any container, after which they throw the "facade root has not been set" error again; call it after each test so a leaked container cannot affect the next one.
See Testing for more on structuring tests.
Facades or injection?
Both reach the same container, so you can mix them. Prefer injection when a class has dependencies it should declare openly, because the constructor then documents what the class needs and a test can pass in a fake directly:
class ReportService {
private readonly cache: Repository
constructor(cache: Repository) {
this.cache = cache
}
summary(): Promise<string> {
return this.cache.remember('summary', 300, () => 'built')
}
}Reach for a facade where a global reads better and the dependency is not worth threading through, such as a route handler or a one-off script. Whichever you choose, the services themselves are still registered once, in a provider.
Working with other facade operations
Facade.getContainer() returns the container facades currently use, which is useful in test helpers. Facade.setContainer can be called again to point facades at a different application, for example one per test file. A facade also forwards property writes and in checks (shown here with Reflect.has, which is the in operator as a function):
const Settings = createFacade<{ theme: string }>('settings')
Settings.theme = 'dark' // writes to the shared settings object
Reflect.has(Settings, 'theme') // => true