@cheep/nestjs
An adapter to use the @cheep/microservices library in the NestJS framework.
Setup
App Level
Import the CheepMicroservicesModule.forRoot
in a top-level module, once per application/microservice. This establishes the primary transport for all feature modules in this process.
import {
CheepTransportModule,
NestTransportUtils,
} from '@cheep/nestjs'
@Module({
imports: [
CheepMicroservicesModule.forRoot({
transport: new MemoryTransport(
{
},
NestTransportUtils,
),
}),
],
})
export class AppModule {}
Feature module
Defines an individual microservice API namespace.
First, create some services which you would like to expose functions from,
then, delcare your API in pure Typescript (this file will disappear after compilation)
import type { UserCommandService } from './user.command.service'
import type { UserQueryService } from './user.query.service'
export type UserApi = ApiWithExecutableKeys<
{
Query: {
User: UserQueryService
}
Command: {
User: UserCommandService
}
Event: {
created: (user: User) => void
}
},
'Query' | 'Command'
>
export type UserRemoteApi =
| import('../groups/group.api.ts').GroupApi
| import('../accounts/account.api.ts').AccountApi
With those types defined, import the CheepMicroservicesModule.forModule
in your module
@Module({
imports: [
CheepMicroservicesModule.forModule<UserApi, UserRemoteApi>({
handlers:{
Query: {
User: UserQueryService
},
Command:{
User: UserCommandService
}
}
listenEventsFrom: {
Event:{
Group: true
}
},
}),
],
providers: [UserQueryService, UserCommandService],
})
export class UserModule {}
Usage
Once the setup is complete, you may consume the exported services from CheepMicroservicesModule.forModule
using CheepApi
in other modules
CheepApi
The CheepApi is for executing queries or commands on remote modules, such as from
a gateway controller which is not in the same module/microservice.
Usage of the API is transparent, and has instant type safety to changes in the
remote module.
@Controller()
export class GatewayService implements OnApplicationBootstrap {
constructor(
private api: CheepApi<ConsumedApis>,
) {}
@Get('users')
async getUsers() {
return this.api.execute.Query.User.getAll()
}
@Get('user/create')
async createUser() {
const id = await this.api.execute.Command.User.create({
user: {
email: faker.internet.email(),
name: faker.name.findName(),
},
})
return this.api.execute.Query.User.getById({ id })
}
@Get('groups')
async getGroups() {
return this.api.execute.Query.Group.getAll()
}
@Get('group/create')
async createGroup() {
const id = await this.api.execute.Command.Group.create({
group: {
name: faker.commerce.department(),
color: faker.random.arrayElement(['red', 'blue']),
},
})
return this.api.execute.Query.Group.getById({ id })
}
@Get('test')
async test() {
return await this.api.execute.Command.User['thisIsPrivate']()
}
}