# Services

Services in FhyTS act as a layer between the Controller and the Model, responsible for handling business logic, data processing, and managing the application's internal dependencies.

# Basic Structure

All services are derived from the Service base class available in the framework:

```javascript
import { Service } from 'fhyts';
```

## Model Sharing

A service can access one or more models explicitly in its constructor.

```javascript
import { UserModel, User } from '../models/UserModel';

export class UserService extends Service {
  private userModel: UserModel;

  constructor(userModel?: UserModel) {
    super();
    this.userModel = userModel || new UserModel();
  }

  async getUsers(): Promise<User[]> {
    return await this.userModel.findAll();
  }

  async getUser(id: number): Promise<User | null> {
    return await this.userModel.findById(id);
  }

  async execute(): Promise<void> {
    // Optional override, used when the service is called as a task
  }
}
```

## General Contract

The Service class in FhyTS supports the single-responsibility principle and can be extended to meet various needs, such as:

| Method | Description |
| --------------- | ------------------------------------------------------------------------- |
| `constructor()` | Initialization location for dependencies such as models, utilities, or other helpers. |
| `execute()` | Optional lifecycle method (can be overridden) for custom execution. |

## Best Practices

* Each service should focus on a single domain/entity (e.g., UserService, AuthService).
* Avoid performing validation or rendering within the service — focus solely on business logic.

## Example Usage in Controller

```
import { UserService } from './services/UserService';

const userService = new UserService();
const userList = await userService.getUsers();
```

## Integrations and Extensions

* Services can be used to access multiple models simultaneously.
* They can also consume external APIs, run asynchronous processes, caching, or queue.
* The **execute()** method can be used if the service is running as a task or background job.

## Next

Once you understand how to use Services, you can move on to the [Middlewares](#middlewares) section to manage the intermediate logic layer in your application's request flow.