Services - Definition
Services are the main components of your Eicrud application. They host a CRUD entity as well as CMDs for non-crud operations.
Generate a new service
You can use the CLI to quickly generate a new service.
An Eicrud service (CrudService) has 3 main components:
An Entity:
services/profile/profile.entity.ts
It is the database schema as well as the DTO for CRUD operations. In that case, a @Entity()
export class Profile implements CrudEntity {
@PrimaryKey({ name: '_id' })
@IsString()
@IsOptional()
id: string;
@Property()
createdAt: Date;
@Property()
updatedAt: Date;
}
profile
table is created.
A Security:
services/profile/profile.security.ts
This is where you define the access rules for your entity. By default, nothing is allowed unless specified in the security.
export function getSecurity(PROFILE: string): CrudSecurity {
return {
rolesRights: {
guest: {
async defineCRUDAbility(can, cannot, ctx) {
//rules for guests
}
}
},
}
}
A Service:
services/profile/profile.service.ts
The actual service implementation, it's a NestJS provider that you can use everywhere in your app. This is where the service's configuration is specified.
@Injectable()
export class ProfileService extends CrudService<Profile> {
constructor(protected modRef: ModuleRef) {
const serviceName = CrudService.getName(Profile);
super(modRef, Profile, getSecurity(serviceName));
}
}
Info
In a CrudService any function starting with $
may be replaced by an HTTP call, depending on your microservice configuration.
You should always:
await
the result of$
functions- pass parameters that can be serialized
- return values that can be serialized
Check out this guide to ensure your application can smoothly transition from monolithic to microservices.
Operations
A CrudService handles all CRUD operations out of the box :
- Create: $create, $createBatch
- Read: $findOne, $find, $findIn
- Update: $patchOne, $patch, $patchIn, $patchBatch
- Delete: $deleteOne, $delete, $deleteIn
You can extend it with CMDs for everything else.
Import your service
Since services are NestJS providers, you can inject them anywhere in your app:
@Injectable()
export class UserService extends CrudUserService<User> {
constructor(
protected modRef: ModuleRef,
protected profileService: ProfileService
) {
super(modRef, User, userSecurity(CrudService.getName(User)));
}
async findProfile(query){
return await this.profileService.$find(query);
}
}