nats-micro
Version:
NATS micro compatible extra-lightweight microservice library
61 lines • 2.35 kB
JavaScript
import { nanoid } from 'nanoid';
import { debug } from '../debug.js';
import { StatusError } from '../statusError.js';
import { headersPrefixContext } from '../types/index.js';
export function randomId() {
return nanoid(16);
}
export function kebabCase(s) {
return s.replace(/(?<=.)([A-Z])/g, '-$1').toLowerCase();
}
export function errorToString(error) {
if (typeof error === 'object' && error) {
return 'message' in error ? String(error.message) : JSON.stringify(error);
}
return String(error);
}
export function subjectToString(subject) {
if (typeof (subject) === 'string')
return subject;
if (typeof (subject) === 'object' && ('method' in subject)) {
if ('instance' in subject)
return `${subject.microservice}.${subject.instance}.${subject.method}`;
return `${subject.microservice}.${subject.method}`;
}
throw new Error('Unknown subject format');
}
export function errorFromHeaders(headers) {
if (!headers)
return undefined;
const headersArray = Array.from(headers);
const errorMessageHeader = headersArray.find((h) => h[0] === 'X-Error-Message');
const errorStatusHeader = headersArray.find((h) => h[0] === 'X-Error-Status');
if (errorMessageHeader) {
if (errorStatusHeader)
return new StatusError(errorStatusHeader[1], errorMessageHeader[1]);
return new Error(errorMessageHeader[1]);
}
return undefined;
}
const addPrefix = (str, prefix) => `${prefix}${str}`;
const removePrefix = (str, prefix) => str.replace(prefix, '');
const isContextHeaderKey = (key) => key.startsWith(headersPrefixContext);
export const contextHeadersToObject = (headers) => {
const obj = {};
for (const [key, value] of headers)
if (isContextHeaderKey(key))
try {
obj[removePrefix(key, headersPrefixContext)] = JSON.parse(value);
}
catch (error) {
debug.ms.thread.warn(`Failed to parse context header '${key}' with value '${value}'`);
}
return obj;
};
export const objectToContextHeaders = (object) => {
const headers = [];
for (const [key, value] of Object.entries(object))
headers.push([addPrefix(key, headersPrefixContext), JSON.stringify(value)]);
return headers;
};
//# sourceMappingURL=misc.js.map