Adonis, microservices, nats
Need microservices in your Adonis5 application? Just use it.
This package provide wrapper for NATs broker (based on moleculer). For better experience you must implement two classes called ${AnyService}Server
and ${AnyService}client
who extends ${AnyService}Server
(for better autocomplete)
npm i adonis5-nats
node ace configure adonis5-nats
import { ServiceSchema } from 'moleculer'
const sleep = (ms: number = 3000) => new Promise((res) => setTimeout(() => res(true), ms))
export class UserServiceClassServer {
public static serviceName = 'UserServiceClassServer' //required field
public static serviceOptions: ServiceSchema = {} //any optins like metadata and other
/** Your any logic: */
public users: [1, 2, 3]
public async getUsersIDs() {
await sleep()
return this.users
}
public async getTestVars<T>(data: T): Promise<T> {
await sleep()
return data
}
}
import { UserServiceClassServer } from 'App/Services/UserServiceServer'
import Broker from '@ioc:Adonis/Addons/NATS'
class UserServiceClassClient extends UserServiceClassServer {
public static serviceName = 'UserServiceClassServer'
constructor() {
super()
}
}
export const UserServiceClient = Broker.addClient<UserServiceClassClient>(
UserServiceClassClient,
UserServiceClassServer
)
import { BaseCommand } from '@adonisjs/core/build/standalone'
import { UserServiceClassServer } from 'App/Services/UserServiceServer'
import Broker from '@ioc:Adonis/Addons/NATS'
export default class UsersService extends BaseCommand {
public static commandName = 'users:service'
public static description = ''
public static settings = {
loadApp: true,
stayAlive: true,
}
public async run() {
await Broker.addServer<UserServiceClassServer>(UserServiceClassServer)
this.logger.info('users service run')
}
}
import Route from '@ioc:Adonis/Core/Route'
import { UserServiceClient } from 'App/Services/UserServiceClient'
Route.get('/get-users-ids', async () => {
return await UserServiceClient.getUsersIDs()
})
version: '3.7'
services:
nats:
image: 'nats'
ports:
- '4222:4222'
docker-compose up nats
node ace generate:manifest
node ace users:service
node ace serve --watch