ToolJet/plugins/packages/grpc/lib/index.ts

66 lines
1.9 KiB
TypeScript
Raw Normal View History

2023-05-01 23:48:02 +00:00
import { QueryError, QueryResult, QueryService } from '@tooljet-plugins/common';
import { SourceOptions, QueryOptions } from './types';
import * as grpc from '@grpc/grpc-js';
import * as protoLoader from '@grpc/proto-loader';
export default class GRPC implements QueryService {
async run(sourceOptions: SourceOptions, queryOptions: QueryOptions, dataSourceId: string): Promise<QueryResult> {
2023-05-02 09:54:31 +00:00
const { serviceName, rpc } = queryOptions;
2023-05-01 23:48:02 +00:00
2023-05-02 09:54:31 +00:00
if (!sourceOptions.url) {
throw new QueryError('Missing URL', {}, {});
}
2023-05-01 23:48:02 +00:00
const cwd = process.cwd();
const rootDir = cwd.split('/').slice(0, -1).join('/');
2023-05-02 09:54:31 +00:00
const protoFilePath = `${rootDir}/protos/service.proto`;
2023-05-01 23:48:02 +00:00
const options: protoLoader.Options = {
keepCase: true,
longs: String,
enums: String,
defaults: true,
oneofs: true,
};
const authType = sourceOptions.auth_type || 'none';
const grpcObj: any = protoLoader.loadSync(protoFilePath, options);
const Service: any = grpc.loadPackageDefinition(grpcObj)[serviceName];
2023-05-02 09:54:31 +00:00
const clientStub: any = new Service(sourceOptions.url, grpc.credentials.createInsecure());
2023-05-01 23:48:02 +00:00
const metadata = new grpc.Metadata();
if (authType === 'basic') {
metadata.add('username', sourceOptions.username);
metadata.add('password', sourceOptions.password);
}
if (authType === 'bearer') {
metadata.add('Authorization', `Bearer ${sourceOptions.bearer_token}`);
}
if (authType === 'api_key') {
metadata.add(sourceOptions.grpc_apikey_key, sourceOptions.grpc_apikey_value);
}
const result = await new Promise((resolve, reject) => {
2023-05-02 09:54:31 +00:00
clientStub[rpc]({}, metadata, (err: any, response: any) => {
2023-05-01 23:48:02 +00:00
if (err) {
reject(err);
}
resolve(response);
});
}).catch((err) => {
throw new QueryError(err.message, {}, {});
});
return {
status: 'ok',
2023-05-02 09:54:31 +00:00
data: result as any,
2023-05-01 23:48:02 +00:00
};
}
}