moleculer icon indicating copy to clipboard operation
moleculer copied to clipboard

A way to generate client code

Open shlomokraus opened this issue 5 years ago • 6 comments

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.

shlomokraus avatar Sep 23 '19 19:09 shlomokraus

I don't know that something similar lib exists. I think no, but would be useful.

icebob avatar Sep 26 '19 19:09 icebob

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).

cloudever avatar Nov 22 '19 07:11 cloudever

Hello @shlomokraus, @icebob

We at Jarvify were working on a library, that does exactly what you've requested.

Moleculer TypeScript

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 avatar Dec 20 '19 14:12 davidfrtala

@davidfrtala awesome! We were about to embark on our own generator. Will your library work with moleculer 0.14?

ujwal-setlur avatar Dec 20 '19 21:12 ujwal-setlur

Good job @davidfrtala!

icebob avatar Dec 31 '19 11:12 icebob

We also did something similar: moleculer-service-ts. There is no generator, but defining types for service actions and events is very simple.

ujwal-setlur avatar Jan 04 '20 09:01 ujwal-setlur