Skip to content

Commit d0677c3

Browse files
feat: add method for find registered microservices
1 parent 7cb8aa0 commit d0677c3

File tree

3 files changed

+39
-1
lines changed

3 files changed

+39
-1
lines changed

__tests__/services/abstract-microservice-test.ts

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
/* eslint-disable camelcase */
12
import dns from 'dns';
23
import axios from 'axios';
34
import { expect } from 'chai';
@@ -412,4 +413,18 @@ describe('services/abstract-microservice', () => {
412413
it('should correctly return channel prefix', () => {
413414
expect(ms).to.have.property('channelPrefix').to.equal(ms.getChannelPrefix());
414415
});
416+
417+
it('should correctly return list of registered microservices', async () => {
418+
const channels = {
419+
$info: {},
420+
'ms/demo': { worker_ids: [] },
421+
'ms/example': { worker_ids: ['worker-id'] },
422+
};
423+
const stubbed = sinon.stub(axios, 'request').resolves({ data: channels });
424+
425+
expect(await ms.lookup()).to.deep.equal(['demo', 'example']);
426+
expect(await ms.lookup(true)).to.deep.equal(['example']);
427+
428+
stubbed.restore();
429+
});
415430
});

package.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
{
22
"name": "@lomray/microservice-nodejs-lib",
3-
"version": "2.4.5",
3+
"version": "1.0.0",
44
"description": "Package for create microservice architecture based on NodeJS & inverted json.",
55
"main": "lib/index.js",
66
"types": "lib/index.d.ts",

src/services/abstract-microservice.ts

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -242,6 +242,29 @@ abstract class AbstractMicroservice {
242242
return handledParams;
243243
}
244244

245+
/**
246+
* Get list of registered microservices
247+
*/
248+
public async lookup(isOnlyAvailable = false): Promise<string[]> {
249+
const ijsonConnection = await this.getConnection();
250+
const { data } = await axios.request({ url: `${ijsonConnection}/rpc/details` });
251+
const prefix = `${this.getChannelPrefix()}/`;
252+
253+
return Object.entries(data ?? {}).reduce(
254+
(res: string[], [channel, params]: [string, Record<string, any>]) => {
255+
if (
256+
channel.startsWith(prefix) &&
257+
(!isOnlyAvailable || (params?.worker_ids?.length ?? 0) > 0)
258+
) {
259+
res.push(channel.replace(prefix, ''));
260+
}
261+
262+
return res;
263+
},
264+
[],
265+
);
266+
}
267+
245268
/**
246269
* Get task from queue
247270
* @protected

0 commit comments

Comments
 (0)