Skip to content

ServiceClass

Description

Service class builder.

Services are classes that can be exported in the DreamKit 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.

The service constructor allows you to inject dependencies that will be resolved when the service is started.

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

Import

import { ServiceClass } from "dreamkit";

Definition

declare const ServiceClass: {
(iocParams: object): {
new (): {
onStart(): (() => any) | undefined;
onStop(): any;
};
};
};

Examples

Basic usage

import { $api, $route, IocContext, kind, ServiceClass } 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 ServiceClass({ IocContext }) {
onStart() {
const counter = new CounterModel();
const interval = setInterval(() => {
counter.value += 1;
}, 1000);
this.iocContext.register(CounterModel, { value: counter });
return () => {
this.iocContext.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>
</>
);
});