Skip to content

$service

import { $service } from "dreamkit";

Services are classes that can be exported in the entry and allow you to initialize configurations that remain alive throughout the application’s lifecycle.

If you edit a service in development mode, that service will be safely restarted.

It is common to use services to initialize databases and register them in the IoC context so that other objects can consume them (middleware, api).


Definition

const $service: {
self(value: object): typeof $service;
create(): {
new (): {
onStart(): (() => any) | undefined;
onStop(): any;
};
};
};

self

Consumes dependencies registered in the IoC context so that they can be used internally by the function.

By default there are a number of registered objects available:

create

Create an abstract service class with the configured instance. You must override the method onStart to implement the service logic.

If a function is returned in the onStart method, it will be called when the service stops.

export class MyService extends $service.create() {
override onStart() {
console.log("Starting");
return () => console.log("Stopping");
}
}

Examples

Basic usage

import { $api, $route, $service, AppContext, kind } from "dreamkit";
import { createResource } from "solid-js";
class CounterModel {
static {
// [important] save a kind to not break `instanceof` during development
kind(this, "CounterModel");
}
value = 0;
}
export class CounterService extends $service.self({ AppContext }).create() {
onStart() {
const counter = new CounterModel();
const interval = setInterval(() => {
counter.value += 1;
}, 1000);
this.appContext.register(CounterModel, { value: counter });
return () => {
this.appContext.unregister(CounterModel);
clearInterval(interval);
};
}
}
const fetchCounterValue = $api
.self({
CounterModel,
})
.create(function () {
return this.counterModel.value;
});
export default $route
.path("/")
.api({ fetchCounterValue })
.create(({ api }) => {
const [counterValue, { refetch }] = createResource(api.fetchCounterValue);
return (
<>
<p>value: {counterValue.latest}</p>
<p>
<button onClick={refetch}>refetch</button>
</p>
</>
);
});