Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

@silenteer/natsu

Package Overview
Dependencies
Maintainers
2
Versions
37
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@silenteer/natsu - npm Package Compare versions

Comparing version 1.0.15 to 1.0.16

3

dist/index.d.ts
import NatsClient from './nats-client';
export type { NatsRequest, NatsResponse, NatsInjection, NatsValidationResult, NatsAuthorizationResult, NatsHandleResult, NatsMiddlewareValidationResult, NatsMiddlewareAuthorizationResult, NatsMiddlewareHandleResult, NatsValidate, NatsAfterValidate, NatsBeforeAuthorize, NatsAuthorize, NatsAfterAuthorize, NatsBeforeHandle, NatsHandle, NatsAfterHandle, NatsHandler, NatsBeforeValidateMiddleware, NatsAfterValidateMiddleware, NatsBeforeAuthorizeMiddleware, NatsAfterAuthorizeMiddleware, NatsBeforeHandleMiddleware, NatsAfterHandleMiddleware, } from './type';
export { NatsValidationResultUtil, NatsAuthorizationResultUtil, NatsHandleResultUtil, NatsMiddlewareValidationResultUtil, NatsMiddlewareAuthorizationResultUtil, NatsMiddlewareHandleResultUtil, } from './utility';
export type { NatsInjection, NatsValidationInjection, NatsAuthorizationInjection, NatsHandleInjection, NatsMiddlewareBeforeInjection, NatsMiddlewareAfterInjection, NatsValidationResult, NatsAuthorizationResult, NatsHandleResult, NatsMiddlewareBeforeResult, NatsMiddlewareAfterResult, NatsBefore, NatsAfter, NatsValidate, NatsAuthorize, NatsHandle, NatsMiddleware, NatsHandler, } from './type';
export default NatsClient;
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.NatsMiddlewareHandleResultUtil = exports.NatsMiddlewareAuthorizationResultUtil = exports.NatsMiddlewareValidationResultUtil = exports.NatsHandleResultUtil = exports.NatsAuthorizationResultUtil = exports.NatsValidationResultUtil = void 0;
const tslib_1 = require("tslib");
const nats_client_1 = (0, tslib_1.__importDefault)(require("./nats-client"));
var utility_1 = require("./utility");
Object.defineProperty(exports, "NatsValidationResultUtil", { enumerable: true, get: function () { return utility_1.NatsValidationResultUtil; } });
Object.defineProperty(exports, "NatsAuthorizationResultUtil", { enumerable: true, get: function () { return utility_1.NatsAuthorizationResultUtil; } });
Object.defineProperty(exports, "NatsHandleResultUtil", { enumerable: true, get: function () { return utility_1.NatsHandleResultUtil; } });
Object.defineProperty(exports, "NatsMiddlewareValidationResultUtil", { enumerable: true, get: function () { return utility_1.NatsMiddlewareValidationResultUtil; } });
Object.defineProperty(exports, "NatsMiddlewareAuthorizationResultUtil", { enumerable: true, get: function () { return utility_1.NatsMiddlewareAuthorizationResultUtil; } });
Object.defineProperty(exports, "NatsMiddlewareHandleResultUtil", { enumerable: true, get: function () { return utility_1.NatsMiddlewareHandleResultUtil; } });
exports.default = nats_client_1.default;
//# sourceMappingURL=index.js.map

@@ -1,4 +0,5 @@

import type { NatsService, NatsHandler } from './type';
import type { NatsService } from '@silenteer/natsu-type';
import type { NatsInjection, NatsHandler } from './type';
declare const _default: {
setup: <TInjection extends Record<string, unknown>>(params: {
setup: <TInjection extends Partial<Pick<NatsInjection<NatsService<string, unknown, unknown>, Record<string, unknown>>, "logService"> & Record<string, unknown>>>(params: {
urls: string[];

@@ -9,12 +10,9 @@ injections?: TInjection;

verbose?: boolean;
namespace?: {
getNamespaceSubject: string;
namespaceSubjects: string[];
};
logLevels?: Array<'log' | 'info' | 'warn' | 'error'> | 'all' | 'none';
}) => {
start: () => Promise<void>;
stop: () => Promise<void>;
register: (handlers: NatsHandler<NatsService<string, unknown, unknown>, TInjection>[]) => void;
register: (handlers: NatsHandler<NatsService<string, unknown, unknown>, TInjection>[]) => Promise<void>;
};
};
export default _default;

@@ -5,218 +5,169 @@ "use strict";

const nats_1 = require("nats");
class UnhandledMiddlewareError extends Error {
}
class UnhandledHandleError extends Error {
}
const requestCodec = (0, nats_1.JSONCodec)();
const responseCodec = (0, nats_1.JSONCodec)();
const clients = {};
function start(params) {
var _a;
return (0, tslib_1.__awaiter)(this, void 0, void 0, function* () {
if (params.namespace &&
(!params.namespace.getNamespaceSubject ||
((_a = params.namespace.namespaceSubjects) === null || _a === void 0 ? void 0 : _a.length) === 0)) {
throw new Error(`Wrong config for 'namespace' `);
}
const { urls, user, pass, verbose } = params;
const key = getClientKey(urls);
if (!clients[key]) {
const { urls, handlers = {}, user, pass, verbose } = params;
if (Object.keys(handlers).length === 0) {
throw new Error(`Must register handlers before starting client`);
}
if (!clients[key].natsService) {
const client = yield (0, nats_1.connect)({
servers: urls,
user,
pass,
pingInterval: 30 * 1000,
maxPingOut: 10,
verbose,
});
clients[key] = Object.assign(Object.assign({}, clients[key]), { natsService: createNatsService({ client, namespace: params.namespace }) });
Object.entries(clients[key].handlers).forEach(([subject, handler]) => {
const natsService = clients[key].natsService;
const subcription = natsService.subscribe(subject);
(() => (0, tslib_1.__awaiter)(this, void 0, void 0, function* () {
var e_1, _a;
try {
for (var subcription_1 = (0, tslib_1.__asyncValues)(subcription), subcription_1_1; subcription_1_1 = yield subcription_1.next(), !subcription_1_1.done;) {
const message = subcription_1_1.value;
let data = message.data
? requestCodec.decode(message.data)
: undefined;
let injection;
try {
if (!data) {
respond({
message,
data: responseCodec.encode(Object.assign(Object.assign({}, data), { body: undefined, code: 400 })),
});
continue;
}
if (data.body) {
data = Object.assign(Object.assign({}, data), { body: data.body });
}
injection = Object.assign(Object.assign({}, params.injections), { subject,
const client = yield (0, nats_1.connect)({
servers: urls,
user,
pass,
pingInterval: 30 * 1000,
maxPingOut: 10,
verbose,
});
const natsService = createNatsService(client);
Object.entries(handlers).forEach(([subject, { handler, injection: registeredInjection, middlewares }]) => {
const subcription = natsService.subscribe(subject);
(() => (0, tslib_1.__awaiter)(this, void 0, void 0, function* () {
var e_1, _a;
try {
for (var subcription_1 = (0, tslib_1.__asyncValues)(subcription), subcription_1_1; subcription_1_1 = yield subcription_1.next(), !subcription_1_1.done;) {
const message = subcription_1_1.value;
let data = message.data
? requestCodec.decode(message.data)
: undefined;
const handlerLogService = registeredInjection.logService;
let injection;
try {
injection = Object.assign(Object.assign({}, registeredInjection), { message,
natsService });
handlerLogService.info('Begin');
if (!data) {
handlerLogService.error('Incoming message has no data');
respond({
message,
natsService });
//#region Validate
const beforeValidateResult = yield beforeValidate({
message,
data,
injection,
handler,
data: responseCodec.encode(Object.assign(Object.assign({}, data), { body: undefined, code: 400 })),
});
if (beforeValidateResult && beforeValidateResult.code !== 'OK') {
continue;
}
else if (beforeValidateResult) {
data = beforeValidateResult.data;
}
const validateResult = yield validate({
message,
data,
injection,
handler,
});
if (validateResult && validateResult.code !== 'OK') {
continue;
}
const afterValidateResult = yield afterValidate({
message,
data,
injection,
handler,
});
if (afterValidateResult && afterValidateResult.code !== 'OK') {
continue;
}
else if (afterValidateResult) {
data = afterValidateResult.data;
}
//#endregion
//#region Authorize
const beforeAuthorizeResult = yield beforeAuthorize({
message,
data,
injection,
handler,
});
if (beforeAuthorizeResult && beforeAuthorizeResult.code !== 'OK') {
continue;
}
else if (beforeAuthorizeResult) {
data = beforeAuthorizeResult.data;
}
const authorizeResult = yield authorize({
message,
data,
injection,
handler,
});
if (authorizeResult && authorizeResult.code !== 'OK') {
continue;
}
const afterAuthorizeResult = yield afterAuthorize({
message,
data,
injection,
handler,
});
if (afterAuthorizeResult && afterAuthorizeResult.code !== 'OK') {
continue;
}
else if (afterAuthorizeResult) {
data = afterAuthorizeResult.data;
}
//#endregion
//#region Handle
const beforeHandleResult = yield beforeHandle({
message,
data,
injection,
handler,
});
if (beforeHandleResult && beforeHandleResult.code !== 'OK') {
continue;
}
else if (beforeHandleResult) {
data = beforeHandleResult.data;
}
const handleResult = yield handle({
message,
data,
injection,
handler,
});
if (handleResult) {
if (handleResult.code === 200) {
yield afterHandle({
message,
data,
result: handleResult,
injection,
handler,
});
}
continue;
}
//#endregion
respond({ message });
handlerLogService.info('End');
continue;
}
catch (error) {
console.error(error);
yield respondUnhandledError({
message,
data,
error,
injection,
handler,
});
if (data.body) {
data = Object.assign(Object.assign({}, data), { body: data.body });
}
//#region Before
const beforeResult = yield before({
message,
data,
injection,
middlewares: middlewares.before,
});
if (beforeResult && beforeResult.code !== 'OK') {
handlerLogService.info('End');
continue;
}
else if (beforeResult) {
data = beforeResult.data;
injection = beforeResult.injection;
}
//#endregion
//#region Handle
let handleResult = yield handle({
message,
data,
injection,
handler,
});
if (handleResult && handleResult.code !== 'OK') {
handlerLogService.info('End');
continue;
}
//#endregion
//#region After
const afterResult = yield after({
message,
data,
result: handleResult,
injection,
middlewares: middlewares.after,
});
if (afterResult && afterResult.code !== 'OK') {
handlerLogService.info('End');
continue;
}
else if (afterResult) {
data = afterResult.data;
handleResult = afterResult.result;
injection = afterResult.injection;
}
//#endregion
respond({
message,
data: responseCodec.encode(Object.assign(Object.assign({}, data), { headers: (handleResult === null || handleResult === void 0 ? void 0 : handleResult.headers)
? Object.assign(Object.assign({}, data === null || data === void 0 ? void 0 : data.headers), handleResult === null || handleResult === void 0 ? void 0 : handleResult.headers) : data === null || data === void 0 ? void 0 : data.headers, code: (handleResult === null || handleResult === void 0 ? void 0 : handleResult.code) === 'OK' ? 200 : handleResult === null || handleResult === void 0 ? void 0 : handleResult.code, body: handleResult === null || handleResult === void 0 ? void 0 : handleResult.body })),
});
handlerLogService.info('End');
}
}
catch (e_1_1) { e_1 = { error: e_1_1 }; }
finally {
try {
if (subcription_1_1 && !subcription_1_1.done && (_a = subcription_1.return)) yield _a.call(subcription_1);
catch (error) {
yield respondUnhandledError({
message,
data,
error,
injection,
handler,
});
handlerLogService.info('End');
}
finally { if (e_1) throw e_1.error; }
}
}))();
});
}
}
catch (e_1_1) { e_1 = { error: e_1_1 }; }
finally {
try {
if (subcription_1_1 && !subcription_1_1.done && (_a = subcription_1.return)) yield _a.call(subcription_1);
}
finally { if (e_1) throw e_1.error; }
}
}))();
});
return natsService;
});
}
function stop(urls) {
function stop(natsService) {
return (0, tslib_1.__awaiter)(this, void 0, void 0, function* () {
const key = getClientKey(urls);
if (clients[key]) {
yield clients[key].natsService.drain();
delete clients[key];
}
yield (natsService === null || natsService === void 0 ? void 0 : natsService.drain());
});
}
function register(params) {
var _a;
const { urls, handlers } = params;
const key = getClientKey(urls);
const isStarted = !!((_a = clients[key]) === null || _a === void 0 ? void 0 : _a.natsService);
if (isStarted) {
throw new Error(`Can't register more handler after nats client started`);
}
if (!clients[key]) {
clients[key] = {
natsService: undefined,
handlers: {},
};
}
handlers.forEach((handler) => {
const { subject } = handler;
if (!clients[key].handlers[subject]) {
clients[key].handlers[subject] = handler;
return (0, tslib_1.__awaiter)(this, void 0, void 0, function* () {
const { logService, handlers, logLevels } = params;
const result = {};
for (const handler of handlers) {
const { subject } = handler;
if (!result[subject]) {
const handlerLogService = createLogService({
prefix: `[${subject}]`,
logService,
logLevels,
});
const injection = {
subject,
handler: {
validate: handler.validate,
authorize: handler.authorize,
handle: handler.handle,
},
logService: handlerLogService,
};
const middlewares = yield loadMiddlewares({
handler,
injection,
});
result[subject] = {
handler,
middlewares,
injection,
};
}
}
return result;
});
}
function getClientKey(urls) {
return urls.sort().join('|');
}
function createNatsService(params) {
const { client } = params;
const { getNamespaceSubject, namespaceSubjects } = params.namespace || {};
function createNatsService(client) {
return {

@@ -227,28 +178,3 @@ request: (subject, data, opts) => (0, tslib_1.__awaiter)(this, void 0, void 0, function* () {

publish: (subject, data, opts) => (0, tslib_1.__awaiter)(this, void 0, void 0, function* () {
const shouldSetNamespace = getNamespaceSubject && (namespaceSubjects === null || namespaceSubjects === void 0 ? void 0 : namespaceSubjects.includes(subject));
let _subject = subject;
if (shouldSetNamespace) {
try {
const { headers } = data || {};
const natsRequest = {
headers,
body: { subject },
};
const message = yield client.request(getNamespaceSubject, (0, nats_1.JSONCodec)().encode(natsRequest));
const natsResponse = (0, nats_1.JSONCodec)().decode(message.data);
const { namespace } = (natsResponse.body ||
{});
if (namespace) {
_subject = `${subject}.${namespace}`;
}
else {
throw new Error(`Namespace is required for subject: ${subject}`);
}
}
catch (error) {
console.error(`Get namespace failed for subject: ${subject}`);
throw error;
}
}
return client.publish(_subject, (0, nats_1.JSONCodec)().encode(data), opts);
return client.publish(subject, (0, nats_1.JSONCodec)().encode(data), opts);
}),

@@ -263,160 +189,182 @@ subscribe: (subject, opts) => {

}
function beforeValidate(params) {
var _a;
return (0, tslib_1.__awaiter)(this, void 0, void 0, function* () {
const { message, data, injection, handler } = params;
let validationResult;
if (((_a = handler.beforeValidateMiddlewares) === null || _a === void 0 ? void 0 : _a.length) > 0) {
for (const validateMiddleware of handler.beforeValidateMiddlewares) {
validationResult = yield validateMiddleware.handle(validationResult ? validationResult.data : data, injection);
if (validationResult.code !== 'OK') {
yield handleErrorResponse({
data: validationResult.data,
error: {
code: validationResult.code,
errors: validationResult.errors,
},
injection,
handler,
});
respond({
message,
data: responseCodec.encode(Object.assign(Object.assign({}, validationResult.data), { code: validationResult.code, body: validationResult.errors })),
});
break;
}
function createLogService(params) {
const { prefix, logService = console, logLevels = 'all' } = params;
let levels = [];
if (Array.isArray(logLevels)) {
levels = [...logLevels];
}
else if (logLevels === 'all') {
levels = ['log', 'info', 'warn', 'error'];
}
return {
log: (message, ...optionalParams) => {
if (levels.includes('log')) {
logService.log(prefix, message, ...optionalParams);
}
}
return validationResult;
});
}
function validate(params) {
return (0, tslib_1.__awaiter)(this, void 0, void 0, function* () {
const { message, data, injection, handler } = params;
let validationResult;
if (handler.validate) {
validationResult = yield handler.validate(data, injection);
if (validationResult.code !== 'OK') {
yield handleErrorResponse({
data,
error: {
code: validationResult.code,
errors: validationResult.errors,
},
injection,
handler,
});
respond({
message,
data: responseCodec.encode(Object.assign(Object.assign({}, data), { code: validationResult.code, body: validationResult.errors })),
});
},
info: (message, ...optionalParams) => {
if (levels.includes('info')) {
logService.info(prefix, message, ...optionalParams);
}
}
return validationResult;
});
},
warn: (message, ...optionalParams) => {
if (levels.includes('warn')) {
logService.warn(prefix, message, ...optionalParams);
}
},
error: (message, ...optionalParams) => {
if (levels.includes('error')) {
logService.error(prefix, message, ...optionalParams);
}
},
};
}
function afterValidate(params) {
function createHandleInjection(injection) {
const handleInjection = Object.assign(Object.assign({}, injection), { ok: (params) => {
const { headers, body } = params;
return {
code: 'OK',
headers,
body,
};
}, error: (params) => {
const { data, code = 500, errors } = params;
return {
code,
data,
errors,
};
} });
return handleInjection;
}
function createMiddlewareBeforeInjection(injection) {
const beforeInjection = Object.assign(Object.assign({}, injection), { ok: (params) => {
const { data, injection } = params;
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const { ok, error } = injection, rest = (0, tslib_1.__rest)(injection, ["ok", "error"]);
return {
code: 'OK',
data,
injection: rest,
};
}, error: (params) => {
const { data, injection, code = 400, errors } = params;
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const { ok, error } = injection, rest = (0, tslib_1.__rest)(injection, ["ok", "error"]);
return {
code,
data,
errors,
injection: rest,
};
} });
return beforeInjection;
}
function createMiddlewareAfterInjection(injection) {
const afterInjection = Object.assign(Object.assign({}, injection), { ok: (params) => {
const { data, result, injection } = params;
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const { ok, error } = injection, rest = (0, tslib_1.__rest)(injection, ["ok", "error"]);
return {
code: 'OK',
data,
result,
injection: rest,
};
}, error: (params) => {
const { data, result, injection, code = 500, errors } = params;
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const { ok, error } = injection, rest = (0, tslib_1.__rest)(injection, ["ok", "error"]);
return {
code,
data,
result,
errors,
injection: rest,
};
} });
return afterInjection;
}
function loadMiddlewares(params) {
var _a;
return (0, tslib_1.__awaiter)(this, void 0, void 0, function* () {
const { message, data, injection, handler } = params;
let validationResult;
if (((_a = handler.afterValidateMiddlewares) === null || _a === void 0 ? void 0 : _a.length) > 0) {
for (const validateMiddleware of handler.afterValidateMiddlewares) {
validationResult = yield validateMiddleware.handle(validationResult ? validationResult.data : data, injection);
if (validationResult.code !== 'OK') {
yield handleErrorResponse({
data: validationResult.data,
error: {
code: validationResult.code,
errors: validationResult.errors,
},
injection,
handler,
const { injection, handler } = params;
const before = [];
const after = [];
if (((_a = handler.middlewares) === null || _a === void 0 ? void 0 : _a.length) > 0) {
for (const middleware of handler.middlewares) {
const middlewareId = middleware.id;
const instance = yield middleware.init({ injection });
if (instance.before) {
before.push({
middlewareId,
handle: (params) => (0, tslib_1.__awaiter)(this, void 0, void 0, function* () {
const { injection } = params, rest = (0, tslib_1.__rest)(params, ["injection"]);
const middlewareLogService = createLogService({
prefix: `[${middleware.id}][before]`,
logService: injection.logService,
});
const middlewareInjection = createMiddlewareBeforeInjection(Object.assign(Object.assign({}, injection), { logService: middlewareLogService }));
middlewareLogService.info('Handling');
try {
const result = yield instance.before(Object.assign({ injection: middlewareInjection }, rest));
if (result.code !== 'OK') {
middlewareLogService.error(result);
}
return Object.assign(Object.assign({}, result), { injection: Object.assign(Object.assign({}, result.injection), { logService: injection.logService }) });
}
catch (error) {
middlewareLogService.error(error);
throw new UnhandledMiddlewareError();
}
}),
});
respond({
message,
data: responseCodec.encode(Object.assign(Object.assign({}, validationResult.data), { code: validationResult.code, body: validationResult.errors })),
});
break;
}
}
}
return validationResult;
});
}
function beforeAuthorize(params) {
var _a;
return (0, tslib_1.__awaiter)(this, void 0, void 0, function* () {
const { message, data, injection, handler } = params;
let authorizationResult;
if (((_a = handler.beforeAuthorizeMiddlewares) === null || _a === void 0 ? void 0 : _a.length) > 0) {
for (const authorizeMiddleware of handler.beforeAuthorizeMiddlewares) {
authorizationResult = yield authorizeMiddleware.handle(authorizationResult ? authorizationResult.data : data, injection);
if (authorizationResult.code !== 'OK') {
yield handleErrorResponse({
data: authorizationResult.data,
error: {
code: authorizationResult.code,
errors: authorizationResult.errors,
},
injection,
handler,
if (instance.after) {
after.unshift({
middlewareId,
handle: (params) => (0, tslib_1.__awaiter)(this, void 0, void 0, function* () {
const { injection } = params, rest = (0, tslib_1.__rest)(params, ["injection"]);
const middlewareLogService = createLogService({
prefix: `[${middleware.id}][after]`,
logService: injection.logService,
});
const middlewareInjection = createMiddlewareAfterInjection(Object.assign(Object.assign({}, injection), { logService: middlewareLogService }));
middlewareLogService.info('Handling');
try {
const result = yield instance.after(Object.assign({ injection: middlewareInjection }, rest));
if (result.code !== 'OK') {
middlewareLogService.error(result);
}
return Object.assign(Object.assign({}, result), { injection: Object.assign(Object.assign({}, result.injection), { logService: injection.logService }) });
}
catch (error) {
middlewareLogService.error(error);
throw new UnhandledMiddlewareError();
}
}),
});
respond({
message,
data: responseCodec.encode(Object.assign(Object.assign({}, authorizationResult.data), { code: authorizationResult.code, body: authorizationResult.errors })),
});
break;
}
}
}
return authorizationResult;
return {
before,
after,
};
});
}
function authorize(params) {
function before(params) {
return (0, tslib_1.__awaiter)(this, void 0, void 0, function* () {
const { message, data, injection, handler } = params;
let authorizationResult;
if (handler.authorize) {
authorizationResult = yield handler.authorize(data, injection);
if (authorizationResult.code !== 'OK') {
yield handleErrorResponse({
data,
error: {
code: authorizationResult.code,
errors: authorizationResult.errors,
},
const { message, data, injection, middlewares } = params;
let beforeResult;
if (middlewares.length > 0) {
for (const middleware of middlewares) {
beforeResult = yield middleware.handle({
data: beforeResult ? beforeResult.data : data,
injection,
handler,
});
respond({
message,
data: responseCodec.encode(Object.assign(Object.assign({}, data), { code: authorizationResult.code, body: authorizationResult.errors })),
});
}
}
return authorizationResult;
});
}
function afterAuthorize(params) {
var _a;
return (0, tslib_1.__awaiter)(this, void 0, void 0, function* () {
const { message, data, injection, handler } = params;
let authorizationResult;
if (((_a = handler.afterAuthorizeMiddlewares) === null || _a === void 0 ? void 0 : _a.length) > 0) {
for (const authorizeMiddleware of handler.afterAuthorizeMiddlewares) {
authorizationResult = yield authorizeMiddleware.handle(authorizationResult ? authorizationResult.data : data, injection);
if (authorizationResult.code !== 'OK') {
yield handleErrorResponse({
data: authorizationResult.data,
error: {
code: authorizationResult.code,
errors: authorizationResult.errors,
},
injection,
handler,
});
if (beforeResult.code !== 'OK') {
respond({
message,
data: responseCodec.encode(Object.assign(Object.assign({}, authorizationResult.data), { code: authorizationResult.code, body: authorizationResult.errors })),
data: responseCodec.encode(Object.assign(Object.assign({}, beforeResult.data), { code: beforeResult.code, body: beforeResult.errors })),
});

@@ -427,30 +375,34 @@ break;

}
return authorizationResult;
return beforeResult;
});
}
function beforeHandle(params) {
var _a;
function handle(params) {
return (0, tslib_1.__awaiter)(this, void 0, void 0, function* () {
const { message, data, injection, handler } = params;
let handleResult;
if (((_a = handler.beforeHandleMiddlewares) === null || _a === void 0 ? void 0 : _a.length) > 0) {
for (const handleMiddleware of handler.beforeHandleMiddlewares) {
handleResult = yield handleMiddleware.handle(handleResult ? handleResult.data : data, injection);
if (handleResult.code != 'OK') {
yield handleErrorResponse({
data: handleResult.data,
error: {
code: handleResult.code,
errors: handleResult.errors,
},
injection,
handler,
});
if (handler.handle) {
const handleLogService = createLogService({
prefix: `[handle]`,
logService: injection.logService,
});
const handleInjection = createHandleInjection(Object.assign(Object.assign({}, injection), { logService: handleLogService }));
try {
handleLogService.info('Handling');
handleResult = yield handler.handle(data, handleInjection);
if (handleResult.code !== 'OK') {
handleLogService.error(handleResult);
if (handler.respondError) {
handleLogService.info('Handling error response');
yield handler.respondError(data, { code: handleResult.code, errors: handleResult.errors }, injection);
}
respond({
message,
data: responseCodec.encode(Object.assign(Object.assign({}, handleResult.data), { code: handleResult.code, body: handleResult.errors })),
data: responseCodec.encode(Object.assign(Object.assign({}, data), { code: handleResult.code, body: handleResult.errors })),
});
break;
}
}
catch (error) {
handleLogService.error(error);
throw new UnhandledHandleError();
}
}

@@ -460,73 +412,34 @@ return handleResult;

}
function handle(params) {
function after(params) {
return (0, tslib_1.__awaiter)(this, void 0, void 0, function* () {
const { message, data, injection, handler } = params;
let handleResult;
if (handler.handle) {
handleResult = yield handler.handle(data, injection);
if (handleResult.code !== 200) {
yield handleErrorResponse({
data,
error: {
code: handleResult.code,
errors: handleResult.errors,
},
const { message, data, result, injection, middlewares } = params;
let afterResult;
if (middlewares.length > 0) {
for (const middleware of middlewares) {
afterResult = yield middleware.handle({
data: afterResult ? afterResult.data : data,
result: afterResult ? afterResult.result : result,
injection,
handler,
});
respond({
message,
data: responseCodec.encode(Object.assign(Object.assign({}, data), { code: handleResult.code, body: handleResult.errors })),
});
}
}
return handleResult;
});
}
function afterHandle(params) {
var _a;
return (0, tslib_1.__awaiter)(this, void 0, void 0, function* () {
const { message, data, result, injection, handler } = params;
let handleResult;
if (((_a = handler.afterHandleMiddlewares) === null || _a === void 0 ? void 0 : _a.length) > 0) {
for (const handleMiddleware of handler.afterHandleMiddlewares) {
handleResult = yield handleMiddleware.handle(handleResult ? handleResult.data : data, handleResult ? handleResult.result : result, injection);
if (handleResult.code !== 'OK') {
yield handleErrorResponse({
data: handleResult.data,
error: {
code: handleResult.code,
errors: handleResult.errors,
},
injection,
handler,
});
if (afterResult.code !== 'OK') {
respond({
message,
data: responseCodec.encode(Object.assign(Object.assign({}, handleResult.data), { code: handleResult.code, body: handleResult.errors })),
data: responseCodec.encode(Object.assign(Object.assign({}, afterResult.data), { code: afterResult.code, body: afterResult.errors })),
});
return;
break;
}
}
}
const lastData = handleResult ? handleResult.data : data;
const lastResult = handleResult ? handleResult.result : result;
respond({
message,
data: responseCodec.encode(Object.assign(Object.assign({}, lastData), { headers: (lastResult === null || lastResult === void 0 ? void 0 : lastResult.headers)
? Object.assign(Object.assign({}, lastData === null || lastData === void 0 ? void 0 : lastData.headers), lastResult === null || lastResult === void 0 ? void 0 : lastResult.headers) : lastData === null || lastData === void 0 ? void 0 : lastData.headers, code: (lastResult === null || lastResult === void 0 ? void 0 : lastResult.code) || 200, body: lastResult === null || lastResult === void 0 ? void 0 : lastResult.body })),
});
return afterResult;
});
}
function handleErrorResponse(params) {
return (0, tslib_1.__awaiter)(this, void 0, void 0, function* () {
const { data, error, injection, handler } = params;
if (handler.respondError) {
yield handler.respondError(data, error, injection);
}
});
}
function respondUnhandledError(params) {
var _a, _b;
return (0, tslib_1.__awaiter)(this, void 0, void 0, function* () {
const { message, data, error, injection, handler } = params;
const isUnhandledMiddlewareError = error instanceof UnhandledMiddlewareError;
const isUnhandledHandleError = error instanceof UnhandledHandleError;
if (!isUnhandledMiddlewareError && !isUnhandledHandleError) {
(_a = injection === null || injection === void 0 ? void 0 : injection.logService) === null || _a === void 0 ? void 0 : _a.error(error);
}
if (handler.respondUnhandledError) {

@@ -537,3 +450,3 @@ try {

catch (error) {
console.error(`[${handler.subject}]respondUnhandledError`, error);
(_b = injection === null || injection === void 0 ? void 0 : injection.logService) === null || _b === void 0 ? void 0 : _b.error('respondUnhandledError', error);
}

@@ -555,14 +468,32 @@ }

setup: (params) => {
const { urls, injections, user, pass, verbose, namespace } = params;
const { urls, injections, user, pass, verbose, logLevels } = params;
let natsHandlers;
let natsService;
const client = {
start: () => start({
urls,
injections,
user,
pass,
verbose,
namespace,
start: () => (0, tslib_1.__awaiter)(void 0, void 0, void 0, function* () {
natsService = yield start({
urls,
handlers: natsHandlers,
user,
pass,
verbose,
});
}),
stop: () => stop(urls),
register: (handlers) => register({ urls, handlers }),
stop: () => (0, tslib_1.__awaiter)(void 0, void 0, void 0, function* () {
yield stop(natsService);
natsService = undefined;
natsHandlers = undefined;
}),
register: (handlers) => (0, tslib_1.__awaiter)(void 0, void 0, void 0, function* () {
const isStarted = !!natsService;
if (isStarted) {
throw new Error(`Can't register more handler after nats client started`);
}
const result = yield register({
handlers,
logService: injections === null || injections === void 0 ? void 0 : injections.logService,
logLevels,
});
natsHandlers = Object.assign(Object.assign({}, natsHandlers), result);
}),
};

@@ -569,0 +500,0 @@ return client;

import type { Msg, NatsConnection, PublishOptions, RequestOptions } from 'nats';
import type { NatsService, NatsRequest, NatsResponse } from '@silenteer/natsu-type';
declare type NatsInjection = {
declare type NatsInjection<TService extends NatsService<string, unknown, unknown>, TInjection extends Record<string, unknown> = Record<string, unknown>> = {
subject: string;
message: Msg;
handler: Pick<NatsHandler<TService, TInjection>, 'validate' | 'authorize' | 'handle'>;
natsService: {

@@ -12,68 +13,113 @@ request: (subject: string, data?: NatsRequest, opts?: RequestOptions) => Promise<Msg>;

};
logService: {
log: (message?: any, ...optionalParams: any[]) => void;
info: (message?: any, ...optionalParams: any[]) => void;
warn: (message?: any, ...optionalParams: any[]) => void;
error: (message?: any, ...optionalParams: any[]) => void;
};
};
declare type NatsValidationResult = {
code: 'OK' | 400 | 404;
code: 'OK' | number;
errors?: unknown;
};
declare type NatsAuthorizationResult = {
code: 'OK' | 403;
code: 'OK' | number;
errors?: unknown;
};
declare type NatsHandleResult<TBody> = {
code: number;
declare type NatsHandleResult<TService extends NatsService<string, unknown, unknown>> = {
code: 'OK' | number;
headers?: {
[key: string]: unknown;
};
body?: TBody;
body?: TService['response'];
errors?: unknown;
};
declare type NatsMiddlewareValidationResult<TRequest = unknown> = {
declare type NatsMiddlewareBeforeResult<TService extends NatsService<string, unknown, unknown>, TInjection extends Record<string, unknown> = Record<string, unknown>> = {
code: 'OK' | number;
data?: NatsRequest<TRequest>;
data: NatsRequest<TService['request']>;
injection: TInjection & NatsInjection<TService, TInjection>;
errors?: unknown;
};
declare type NatsMiddlewareAuthorizationResult<TRequest = unknown> = {
declare type NatsMiddlewareAfterResult<TService extends NatsService<string, unknown, unknown>, TInjection extends Record<string, unknown> = Record<string, unknown>> = {
code: 'OK' | number;
data?: NatsRequest<TRequest>;
data: NatsRequest<TService['request']>;
injection: TInjection & NatsInjection<TService, TInjection>;
result: NatsHandleResult<TService>;
errors?: unknown;
};
declare type NatsMiddlewareHandleResult<TRequest = unknown, TResponse = unknown> = {
code: 'OK' | number;
data?: NatsRequest<TRequest>;
result?: NatsHandleResult<TResponse>;
errors?: unknown;
declare type NatsMiddlewareBeforeInjection<TService extends NatsService<string, unknown, unknown>, TInjection extends Record<string, unknown> = Record<string, unknown>> = NatsInjection<TService, TInjection> & {
ok: (params: {
data: NatsRequest<TService['request']>;
injection: NatsMiddlewareBeforeInjection<TService, TInjection>;
}) => NatsMiddlewareBeforeResult<TService, TInjection>;
error: (params: {
data: NatsRequest<TService['request']>;
injection: NatsMiddlewareBeforeInjection<TService, TInjection>;
code?: number;
errors: unknown;
}) => NatsMiddlewareBeforeResult<TService, TInjection>;
};
declare type NatsBeforeValidate<TService extends NatsService<string, unknown, unknown>, TInjection extends Record<string, unknown> = Record<string, unknown>> = (data: NatsRequest<TService['request']>, injection: TInjection & NatsInjection) => Promise<NatsMiddlewareValidationResult>;
declare type NatsValidate<TService extends NatsService<string, unknown, unknown>, TInjection extends Record<string, unknown> = Record<string, unknown>> = (data: NatsRequest<TService['request']>, injection: TInjection & NatsInjection) => Promise<NatsValidationResult>;
declare type NatsAfterValidate<TService extends NatsService<string, unknown, unknown>, TInjection extends Record<string, unknown> = Record<string, unknown>> = (data: NatsRequest<TService['request']>, injection: TInjection & NatsInjection) => Promise<NatsMiddlewareValidationResult>;
declare type NatsBeforeAuthorize<TService extends NatsService<string, unknown, unknown>, TInjection extends Record<string, unknown> = Record<string, unknown>> = (data: NatsRequest<TService['request']>, injection: TInjection & NatsInjection) => Promise<NatsMiddlewareAuthorizationResult>;
declare type NatsAuthorize<TService extends NatsService<string, unknown, unknown>, TInjection extends Record<string, unknown> = Record<string, unknown>> = (data: NatsRequest<TService['request']>, injection: TInjection & NatsInjection) => Promise<NatsAuthorizationResult>;
declare type NatsAfterAuthorize<TService extends NatsService<string, unknown, unknown>, TInjection extends Record<string, unknown> = Record<string, unknown>> = (data: NatsRequest<TService['request']>, injection: TInjection & NatsInjection) => Promise<NatsMiddlewareAuthorizationResult>;
declare type NatsBeforeHandle<TService extends NatsService<string, unknown, unknown>, TInjection extends Record<string, unknown> = Record<string, unknown>> = (data: NatsRequest<TService['request']>, injection: TInjection & NatsInjection) => Promise<NatsMiddlewareHandleResult>;
declare type NatsHandle<TService extends NatsService<string, unknown, unknown>, TInjection extends Record<string, unknown> = Record<string, unknown>> = (data: NatsRequest<TService['request']>, injection: TInjection & NatsInjection) => Promise<NatsHandleResult<TService['response']>>;
declare type NatsAfterHandle<TService extends NatsService<string, unknown, unknown>, TInjection extends Record<string, unknown> = Record<string, unknown>> = (data: NatsRequest<TService['request']>, result: NatsHandleResult<TService['response']>, injection: TInjection & NatsInjection) => Promise<NatsMiddlewareHandleResult>;
declare type NatsBeforeValidateMiddleware<TService extends NatsService<string, unknown, unknown>, TInjection extends Record<string, unknown> = Record<string, unknown>> = {
id: string;
handle: NatsBeforeValidate<TService, TInjection>;
declare type NatsMiddlewareAfterInjection<TService extends NatsService<string, unknown, unknown>, TInjection extends Record<string, unknown> = Record<string, unknown>> = NatsInjection<TService, TInjection> & {
ok: (params: {
data: NatsRequest<TService['request']>;
result: NatsHandleResult<TService>;
injection: NatsMiddlewareAfterInjection<TService, TInjection>;
}) => NatsMiddlewareAfterResult<TService, TInjection>;
error: (params: {
data: NatsRequest<TService['request']>;
result: NatsHandleResult<TService>;
injection: NatsMiddlewareAfterInjection<TService, TInjection>;
code?: number;
errors: unknown;
}) => NatsMiddlewareAfterResult<TService, TInjection>;
};
declare type NatsAfterValidateMiddleware<TService extends NatsService<string, unknown, unknown>, TInjection extends Record<string, unknown> = Record<string, unknown>> = {
id: string;
handle: NatsAfterValidate<TService, TInjection>;
declare type NatsValidationInjection<TService extends NatsService<string, unknown, unknown>, TInjection extends Record<string, unknown> = Record<string, unknown>> = TInjection & NatsInjection<TService, TInjection> & {
ok: (params: {
data: NatsRequest<TService['request']>;
}) => NatsValidationResult;
error: (params: {
data: NatsRequest<TService['request']>;
code?: number;
errors: unknown;
}) => NatsValidationResult;
};
declare type NatsBeforeAuthorizeMiddleware<TService extends NatsService<string, unknown, unknown>, TInjection extends Record<string, unknown> = Record<string, unknown>> = {
id: string;
handle: NatsBeforeAuthorize<TService, TInjection>;
declare type NatsAuthorizationInjection<TService extends NatsService<string, unknown, unknown>, TInjection extends Record<string, unknown> = Record<string, unknown>> = TInjection & NatsInjection<TService, TInjection> & {
ok: (params: {
data: NatsRequest<TService['request']>;
}) => NatsAuthorizationResult;
error: (params: {
data: NatsRequest<TService['request']>;
code?: number;
errors: unknown;
}) => NatsAuthorizationResult;
};
declare type NatsAfterAuthorizeMiddleware<TService extends NatsService<string, unknown, unknown>, TInjection extends Record<string, unknown> = Record<string, unknown>> = {
id: string;
handle: NatsAfterAuthorize<TService, TInjection>;
declare type NatsHandleInjection<TService extends NatsService<string, unknown, unknown>, TInjection extends Record<string, unknown> = Record<string, unknown>> = TInjection & NatsInjection<TService, TInjection> & {
ok: (params: Pick<NatsHandleResult<TService>, 'headers' | 'body'>) => NatsHandleResult<TService>;
error: (params: {
data: NatsRequest<TService['request']>;
code?: number;
errors: unknown;
}) => NatsHandleResult<TService>;
};
declare type NatsBeforeHandleMiddleware<TService extends NatsService<string, unknown, unknown>, TInjection extends Record<string, unknown> = Record<string, unknown>> = {
declare type NatsBefore<TService extends NatsService<string, unknown, unknown>, TInjection extends Record<string, unknown> = Record<string, unknown>> = (params: {
data: NatsRequest<TService['request']>;
injection: NatsMiddlewareBeforeInjection<TService, TInjection>;
}) => Promise<NatsMiddlewareBeforeResult<TService, TInjection>>;
declare type NatsAfter<TService extends NatsService<string, unknown, unknown>, TInjection extends Record<string, unknown> = Record<string, unknown>> = (params: {
data: NatsRequest<TService['request']>;
result: NatsHandleResult<TService>;
injection: NatsMiddlewareAfterInjection<TService, TInjection>;
}) => Promise<NatsMiddlewareAfterResult<TService, TInjection>>;
declare type NatsValidate<TService extends NatsService<string, unknown, unknown>, TInjection extends Record<string, unknown> = Record<string, unknown>> = (data: NatsRequest<TService['request']>, injection: NatsValidationInjection<TService, TInjection>) => Promise<NatsValidationResult>;
declare type NatsAuthorize<TService extends NatsService<string, unknown, unknown>, TInjection extends Record<string, unknown> = Record<string, unknown>> = (data: NatsRequest<TService['request']>, injection: NatsAuthorizationInjection<TService, TInjection>) => Promise<NatsAuthorizationResult>;
declare type NatsHandle<TService extends NatsService<string, unknown, unknown>, TInjection extends Record<string, unknown> = Record<string, unknown>> = (data: NatsRequest<TService['request']>, injection: NatsHandleInjection<TService, TInjection>) => Promise<NatsHandleResult<TService>>;
declare type NatsMiddleware<TService extends NatsService<string, unknown, unknown>, TInjection extends Record<string, unknown> = Record<string, unknown>> = {
id: string;
handle: NatsBeforeHandle<TService, TInjection>;
init: (params: {
injection: TInjection;
}) => Promise<{
before?: NatsBefore<TService, TInjection>;
after?: NatsAfter<TService, TInjection>;
}>;
};
declare type NatsAfterHandleMiddleware<TService extends NatsService<string, unknown, unknown>, TInjection extends Record<string, unknown> = Record<string, unknown>> = {
id: string;
handle: NatsAfterHandle<TService, TInjection>;
};
declare type NatsHandler<TService extends NatsService<string, unknown, unknown>, TInjection extends Record<string, unknown> = Record<string, unknown>> = {

@@ -84,14 +130,9 @@ subject: TService['subject'];

handle: NatsHandle<TService, TInjection>;
beforeValidateMiddlewares?: Array<NatsBeforeValidateMiddleware<TService, TInjection>>;
afterValidateMiddlewares?: Array<NatsAfterValidateMiddleware<TService, TInjection>>;
beforeAuthorizeMiddlewares?: Array<NatsBeforeAuthorizeMiddleware<TService, TInjection>>;
afterAuthorizeMiddlewares?: Array<NatsAfterAuthorizeMiddleware<TService, TInjection>>;
beforeHandleMiddlewares?: Array<NatsBeforeHandleMiddleware<TService, TInjection>>;
afterHandleMiddlewares?: Array<NatsAfterHandleMiddleware<TService, TInjection>>;
middlewares?: Array<NatsMiddleware<TService, TInjection>>;
respondError?: (data: NatsRequest<TService['request']>, error: {
code: number;
errors?: unknown;
}, injection: TInjection & NatsInjection) => Promise<void>;
respondUnhandledError?: (data: NatsRequest<TService['request']>, error: Error, injection: TInjection & NatsInjection) => Promise<void>;
}, injection: TInjection & NatsInjection<TService, TInjection>) => Promise<void>;
respondUnhandledError?: (data: NatsRequest<TService['request']>, error: Error, injection: TInjection & NatsInjection<TService, TInjection>) => Promise<void>;
};
export type { NatsService, NatsRequest, NatsResponse, NatsInjection, NatsValidationResult, NatsAuthorizationResult, NatsHandleResult, NatsMiddlewareValidationResult, NatsMiddlewareAuthorizationResult, NatsMiddlewareHandleResult, NatsBeforeValidate, NatsValidate, NatsAfterValidate, NatsBeforeAuthorize, NatsAuthorize, NatsAfterAuthorize, NatsBeforeHandle, NatsHandle, NatsAfterHandle, NatsHandler, NatsBeforeValidateMiddleware, NatsAfterValidateMiddleware, NatsBeforeAuthorizeMiddleware, NatsAfterAuthorizeMiddleware, NatsBeforeHandleMiddleware, NatsAfterHandleMiddleware, };
export type { NatsInjection, NatsValidationInjection, NatsAuthorizationInjection, NatsHandleInjection, NatsMiddlewareBeforeInjection, NatsMiddlewareAfterInjection, NatsValidationResult, NatsAuthorizationResult, NatsHandleResult, NatsMiddlewareBeforeResult, NatsMiddlewareAfterResult, NatsBefore, NatsAfter, NatsValidate, NatsAuthorize, NatsHandle, NatsMiddleware, NatsHandler, };
{
"name": "@silenteer/natsu",
"version": "1.0.15",
"version": "1.0.16",
"license": "MIT",

@@ -21,3 +21,3 @@ "private": false,

"dependencies": {
"@silenteer/natsu-type": "0.0.11",
"@silenteer/natsu-type": "0.0.12",
"nats": "^2.2.0"

@@ -24,0 +24,0 @@ },

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc