-
Notifications
You must be signed in to change notification settings - Fork 0
Services
Danny SMc edited this page May 13, 2021
·
4 revisions
A service is a class that gets called every defined amount of seconds. You can use services to do background tasks.
1. Create the structure.
The below will create a new folder: ./src/service
and then create a new file inside.
mkdir ./src/service
touch ./src/service/example.ts
2. Create the service code.
The below is a simple example of creating a service, the interface IService
defines the structure of the
service and defines the required function.
// Import our package parts.
import { Service, AbstractService, IService } from 'rewyre';
import { LoggerProvider } from '../provider/logger';
import { PeopleModel } from '../model/people';
@Inject(['logger', 'people'])
@Service('example_service', 10)
export class ExampleService extends AbstractService implements IService {
protected logger!: LoggerProvider;
protected people!: PeopleModel;
public async execute(): Promise<void> {
const people: Array<any> = await this.people.find({});
this.logger.notice('EXAMPLE:SERVICE', `There are ${people.length} people in our database.`);
}
}
3. Register the service.
So we have a service, but we have not registered it, so let's go back to our ./src/application.ts
file and register it.
import { Framework } from 'rewyre';
import { PeopleController } from '../controller/people';
import { PeopleModel } from '../model/people';
import { LoggerProvider } from '../provider/logger';
// Import the service.
import { ExampleService } from '../service/example';
(async () => {
const application: Framework = new Framework({
port: 8080,
database: true,
databases: [
{
unique: 'main',
host: 'localhost',
port: 27017,
name: 'demo-rewyre-app',
driver: Drivers.MONGO,
default: true,
},
],
});
// Register the class.
application.register([ PeopleController, PeopleModel, LoggerProvider, ExampleService ]);
await application.start();
});