Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(grpc): GRPCClients.createClient() supports multi services in one .proto file and returns void insted of T #4159

Merged
merged 5 commits into from
Nov 8, 2024
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 20 additions & 3 deletions packages/grpc/src/comsumer/clients.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import * as assert from 'assert';
import {
Config,
Init,
Expand Down Expand Up @@ -40,23 +41,33 @@ export class GRPCClients extends Map {
}
}

async createClient<T>(options: IGRPCClientServiceOptions): Promise<T> {
async createClient<T>(options: IGRPCClientServiceOptions): Promise<void> {
const packageDefinition = await loadProto({
loaderOptions: options.loaderOptions,
protoPath: options.protoPath,
});
const allProto = loadPackageDefinition(packageDefinition);
const packageProto: any = finePackageProto(allProto, options.package);

for (const definition in packageDefinition) {
if (!packageDefinition[definition]['format']) {
const serviceName = definition.replace(`${options.package}.`, '');
const connectionService = new packageProto[serviceName](
const connectionService: T = new packageProto[serviceName](
options.url,
credentials.createInsecure(),
options.clientOptions
);

for (const methodName of Object.keys(packageDefinition[definition])) {
const originMethod = connectionService[methodName];
const msg: string[] = [
`No method found in proto file, path: ${options.protoPath}`,
`method: ${methodName}`,
`definition: ${definition}`,
`serviceName: ${serviceName}`,
];
assert(originMethod, msg.join(', '));

connectionService[methodName] = (
clientOptions: IClientOptions = {}
) => {
Expand All @@ -70,7 +81,6 @@ export class GRPCClients extends Map {
connectionService[methodName];
}
this.set(definition, connectionService);
return connectionService;
}
}
}
Expand Down Expand Up @@ -130,5 +140,12 @@ export const createGRPCConsumer = async <T>(
};

await clients.initService();
if (typeof options.service === 'string' && options.service) {
const pkg = clients.grpcConfig.services[0].package;
const name = options.service.startsWith(`${pkg}.`)
? options.service
: `${pkg}.${options.service}`;
return clients.getService(name);
}
return Array.from(clients.values())[0];
};
4 changes: 4 additions & 0 deletions packages/grpc/src/interface.ts
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,10 @@ export interface IGRPCClientServiceOptions extends IGRPCServiceOptions {
* Client options. Optional.
*/
clientOptions?: ClientOptions;
/**
* Service name. Optional.
*/
service?: string;
}

export interface IMidwayGRPFrameworkOptions extends IConfigurationOptions {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,13 @@ export namespace hero {
id?: number;
name?: string;
}

export interface HeroService2 {
findOne2(data: HeroById, metadata?: Metadata): Promise<Hero>;
}
export interface HeroService2Client {
findOne2(options?: IClientOptions): IClientUnaryService<HeroById, Hero>;
}
}

export namespace helloworld {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
import { GrpcMethod, MSProviderType, Provider, Provide, Inject, Init } from '@midwayjs/core';
import { helloworld, hero } from '../interface';
import { Clients } from '../../../../../src';

@Provide()
@Provider(MSProviderType.GRPC, { package: 'hero' })
export class HeroService2 implements hero.HeroService2 {

@Inject()
grpcClients: Clients;

greeterService: helloworld.GreeterClient;

@Init()
async init() {
this.greeterService = this.grpcClients.getService<helloworld.GreeterClient>('helloworld.Greeter');
}

@GrpcMethod()
async findOne2(data) {
const result = await this.greeterService.sayHello().sendMessage({
name: 'harry'
});
return {
id: 1,
name: 'bbbb-' + result.message,
};
}
}
4 changes: 4 additions & 0 deletions packages/grpc/test/fixtures/proto/hero.proto
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,10 @@ service HeroService {
rpc FindOne (HeroById) returns (Hero) {}
}

service HeroService2 {
rpc FindOne2 (HeroById) returns (Hero) {}
}

message HeroById {
int32 id = 1;
}
Expand Down
23 changes: 15 additions & 8 deletions packages/grpc/test/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,9 @@ export namespace hero {
id?: number;
name?: string;
}
export interface HeroService2Client {
findOne2(options?: IClientOptions): IClientUnaryService<HeroById, Hero>;
}
}

export namespace helloworld {
Expand Down Expand Up @@ -61,7 +64,6 @@ export namespace math {
}
}


describe('/test/index.test.ts', function () {

it('run with empty config', async () => {
Expand Down Expand Up @@ -108,18 +110,23 @@ describe('/test/index.test.ts', function () {

it('should create multiple grpc service in one server', async () => {
const app = await createServer('base-app-multiple-service');

const service = await createGRPCConsumer<hero.HeroServiceClient>({
const opts = {
package: 'hero',
protoPath: join(__dirname, 'fixtures/proto/hero.proto'),
url: 'localhost:6565'
});

const result = await service.findOne().sendMessage({
id: 123
});
}

const service = await createGRPCConsumer<hero.HeroServiceClient>({ ...opts, });
const result = await service.findOne().sendMessage({ id: 123 });
expect(result).toEqual({ id: 1, name: 'bbbb-Hello harry' })

const service2 = await createGRPCConsumer<hero.HeroService2Client>({ service: 'HeroService2', ...opts, });
const result2 = await service2.findOne2().sendMessage({ id: 123 });
expect(result2).toEqual({ id: 1, name: 'bbbb-Hello harry' })

const service3 = await createGRPCConsumer<hero.HeroService2Client>({ ...opts, service: 'hero.HeroService2' });
const result3 = await service3.findOne2().sendMessage({ id: 123 });
expect(result3).toEqual({ id: 1, name: 'bbbb-Hello harry' })
await closeApp(app);
});

Expand Down
Loading