Skip to content

Services

Danny SMc edited this page Nov 2, 2021 · 2 revisions

Services are the core functionality of the application, they provide the actual services (http server, websocket server, discord bot, etc) that actually calls the controllers, services do a lot of the hard work in terms of generating the right contexts, and passing them over to the controller, and managing their returns.

You can implement a service in two ways, either by creating a services/service folder and creating your logic there, or by creating a plugin folder, and registering the plugin in your entry point using the engine.use() method. We would always suggest using a plugin as this allows you to encapsulate all of your code under the same roof, see the src/plugin folder in the repository for two available examples (HttpPlugin and WsPlugin).


Example

A service has a fairly simple structure, I have defined below the most basic example of a service, which simply calls a controller at random intervals.

@Service('timer')
export class HttpService extends AbstractService implements IService {
	private controllers: Array<any> = [];
	private interval?: NodeJS.Timer;
	private running = false;

	public constructor(options: Record<string, any>) {
		super(options);

		// We do this so we can inject this anywhere, for custom functionality.
		Injector.register('engine.plugin.timer', this);
		Injector.register('engine.plugin.timer.options', this.options);
	}

	public async initialise(): Promise<void> {
		this.interval = setInterval(() => {
			if (this.running) {
				this.execute();
			}
		}, 1000 * 60); // Every minute.
	}

	public async start(): Promise<void> {
		this.running = true;
	}

	public async stop(): Promise<void> {
		this.running = false;
	}

	public async execute(): Promise<void> {
		// Do logic to call controllers here.
	}
}

As you can see the service, simply setups the timers, hooking into the events, and the from there we can call the controllers, the logic to call controllers can be complex and differ for each service, for more information see the examples from the HttpPlugin and WsPlugin for more examples.

Features

Plugins

Future Plans

Resources

Clone this wiki locally