moleculer
moleculer copied to clipboard
A way to generate client code
Is your feature request related to a problem? Please describe. When service calls another service it needs to use broker.call. Instead, I prefer wrapping those calls inside methods and provide a client to the other services. That way each service provides a client which is descriptive and (using typescript) also typesafe as well as testable.
Describe the solution you'd like I would like to use the service descriptor file to auto-generate a js or ts client automatically. Can be easily implemented with AST. This is similar to how grpc or thrift generate clients from DSL.
Describe alternatives you've considered Manually writing the clients, which is error-prone.
Additional context Just wanted to know if anything like this exists and how the rest of you tackled that problem.
I don't know that something similar lib exists. I think no, but would be useful.
I also use the technique that described @shlomokraus
As an option, I propose to act by analogy with the graphql-code-generator: each service informs another service about which methods it has and the calling service generates code (typescript based on validation schema, javascript).
Hello @shlomokraus, @icebob
We at Jarvify were working on a library, that does exactly what you've requested.
Please, take a look on our moleculer-ts library.
With this library, you simply define a types for your services
import { Action, Even } from 'moleculer-ts';
...
type User = {
id: string;
...
};
export type OwnActions = [
Action<'create', User, { id: string }>,
Action<'get', { email: string }, User>,
Action<'delete', { id: string }, User>,
];
export type OwnEvents = [Event<'nodeChange', User>];
...
then, let the generator do the rest, so you can use your types in actions & event
import { UserServiceTypes } from '../../types';
...
@Action()
async get(
ctx: Context<UserServiceTypes.ActionParams<'get'>>,
): Promise<UserServiceTypes.ActionReturn<'get'>> {
const params = ctx.params;
return {
email: 'a',
id: 'a',
name: 'a',
password: 'a',
};
}
...
@davidfrtala awesome! We were about to embark on our own generator. Will your library work with moleculer 0.14?
Good job @davidfrtala!
We also did something similar: moleculer-service-ts. There is no generator, but defining types for service actions and events is very simple.