UNPKG

nats-micro

Version:

NATS micro compatible extra-lightweight microservice library

77 lines 3.76 kB
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; import { ZodError } from 'zod'; // eslint-disable-next-line import/no-cycle import { callHandler } from './callHandler.js'; import { errorToString } from './misc.js'; import { addContextHeadersToThreadContext, threadContext } from './threadContext.js'; import { debug } from '../debug.js'; export function wrapMethodSafe(broker, callback, handlerInfo) { return (msg, subject) => __awaiter(this, void 0, void 0, function* () { var _a; try { const store = new Map(); threadContext.enterWith(store); let input = msg.data; if (handlerInfo.methodConfig.request) { // eslint-disable-next-line @typescript-eslint/no-explicit-any if (handlerInfo.methodConfig.request._def.typeName === 'ZodVoid') // eslint-disable-next-line @typescript-eslint/no-explicit-any input = undefined; else try { input = handlerInfo.methodConfig.request.parse(input); } catch (err) { if (err instanceof ZodError) { throw new Error(`Error parsing request fields: ${err.issues.map((i) => `${i.path.join('.')} (${i.message})`).join(', ')}`); } throw err; } } addContextHeadersToThreadContext(msg.headers); debug.ms.thread.debug(`Executing safe ${handlerInfo.method}(${JSON.stringify(msg.data)})`); const output = yield callHandler(callback, input, subject, (_a = msg.headers) !== null && _a !== void 0 ? _a : [], handlerInfo); if ((typeof (output.data) !== 'symbol') && 'replyTo' in msg && msg.replyTo) { if (handlerInfo.methodConfig.response) { try { output.data = handlerInfo.methodConfig.response.parse(output.data); } catch (err) { if (err instanceof ZodError) throw new Error(`Invalid response type: ${err.issues.map((i) => i.message).join(',')}`); else throw err; } } broker.send(msg.replyTo, output.data, { headers: output.headers, }); } } catch (err) { const error = errorToString(err); debug.error(error); if ('replyTo' in msg && msg.replyTo) { const headers = [ ...((typeof (err) === 'object') && err && ('status' in err) ? [['X-Error-Status', String(err.status)]] : []), ['X-Error-Message', error], ]; broker.send(msg.replyTo, 'ERROR', { headers, }); } // throw err; } }); } //# sourceMappingURL=wrapMethodSafe.js.map