UNPKG

@grpc.ts/fastify-client

Version:
57 lines (53 loc) 1.7 kB
import fp from 'fastify-plugin'; import { createClient } from '@grpc.ts/core'; export { ChannelCredentials, GrpcTimestamp, createClient, createMetadata, createSecureContext, dateToGrpcTimestamp, grpcTimestampToDate } from '@grpc.ts/core'; async function createClients(options) { if (!Array.isArray(options)) { options = [options]; } const clients = await Promise.allSettled(options.map(async ({ clientName = '', ...opts }) => { const client = await createClient(opts); return { client, clientName, }; })); return clients.reduce((result, settledServer) => { if (settledServer.status === 'fulfilled') { const { client, clientName } = settledServer.value; result[clientName] = client; } return result; }, {}); } let grpcClientList = {}; const getService = (serviceName, options = {}) => { const { clientName = '', packageName = '' } = options; const client = grpcClientList[clientName]; return client.getService(serviceName, { packageName, }); }; const grpcClient = async (fastify, options) => { if (!fastify.hasDecorator('grpcClient')) { fastify.decorate('grpcClient', { getService, }); } const list = await createClients(options); grpcClientList = { ...grpcClientList, ...list, }; fastify.addHook('onClose', onClose); function onClose() { Object.values(grpcClientList).forEach((wrapper) => { wrapper.close(); }); } }; var index = fp(grpcClient, { fastify: '>=3', name: '@grpc.ts/fastify-client', }); export { index as default };