@opengis/fastify-table
Version:
core-plugins
104 lines (103 loc) • 3.37 kB
JavaScript
/* eslint-disable no-promise-executor-return */
/* eslint-disable no-console */
import path from "node:path";
import { fileURLToPath } from "url";
import grpc from "@grpc/grpc-js";
import protoLoader from "@grpc/proto-loader";
import config from "../../../config.js";
import logger from "../logger/getLogger.js";
const filename = fileURLToPath(import.meta.url);
const dirname = path.dirname(filename);
config.ready = config.ready || {};
// external ip not-accessible from internal network
const defaultConvertServerAddress = config.pg?.host?.startsWith?.("192.168.3")
? "192.168.1.96:4003"
: "193.239.152.181:44003";
const convertServerAddress = config.convertServerAddress === true
? defaultConvertServerAddress
: config.convertServerAddress;
if (config.local || config.debug)
console.log("convertServerAddress: ", convertServerAddress, !!config.convertServerAddress);
// const relpath = 'server/plugins/grpc/utils/convertp.proto';
// const protoLocation = process.cwd().includes('fastify-table') ? relpath : `node_modules/@opengis/fastify-table/${relpath}`;
const proto = grpc.loadPackageDefinition(protoLoader.loadSync(`${dirname}/utils/convertp.proto`, {
keepCase: true,
longs: String,
enums: String,
defaults: true,
oneofs: true,
}));
const Convert = proto.Convert;
const methodNames = [
"pdfMerge",
"htmlToPdf",
"csvToXls",
"jsonToXls",
"excelToJson",
"xmlToJson",
"htmlToDoc",
"htmlToImage",
"shpToGeojson",
"geojsonToShp",
"geojsonToGpkg",
"docToPDF",
"mergeImages",
"resizeImage",
"jsonToYaml",
"yamlToJson",
"log",
];
const convertClient = convertServerAddress
? new Convert(convertServerAddress, grpc.credentials.createInsecure(), {
"grpc.max_send_message_length": 512 * 1024 * 1024,
"grpc.max_receive_message_length": 512 * 1024 * 1024,
})
: {};
if (convertServerAddress) {
convertClient.waitForReady(Date.now() + 5000, (err) => {
if (err) {
config.ready.convert = false;
console.error("Client connection timeout or failure:", err);
}
else {
config.ready.convert = true;
console.log("Client connected successfully.");
// You can now make RPC calls safely
}
});
}
const wrapGrpcCall = (methodName) => async (data) => new Promise((res, rej) => {
if (!convertServerAddress) {
logger.file("grpc/convert", {
method: methodName,
error: "grpc convert not set",
stack: new Error().stack,
});
return rej(new Error("grpc convert not set"));
}
convertClient[methodName](data, (err, response) => {
if (err) {
logger.file("grpc/convert", {
method: methodName,
error: err.toString(),
stack: err.stack,
ready: config.ready.convert,
});
if (!config.ready.convert) {
return rej(new Error("no grpc convert connection"));
}
return rej(err);
}
return res(response);
});
return null;
});
const grpcMethods = methodNames.reduce((acc, name) => {
acc[name] = wrapGrpcCall(name);
return acc;
}, {});
const getGRPC = () => ({
...grpcMethods,
convertServerAddress,
});
export default getGRPC;