mirror of
https://github.com/Abdulazizzn/n8n-enterprise-unlocked.git
synced 2025-12-17 10:02:05 +00:00
fix(core): amend typing for jsonParse() options (#4423)
* 📘 Amend typing for `jsonParse()` options * ✏️ Update rule message and description * 🔀 Cherrypick Adi's work * 🐛 Account for falsy fallback values * ♻️ Use `else if` * ⚡ Add explicit error message as type * ⚡ Consolidate utils tests * ♻️ Use optional chaining * 🔥 Remove patchy type error Co-authored-by: कारतोफ्फेलस्क्रिप्ट™ <aditya@netroy.in>
This commit is contained in:
@@ -30,22 +30,23 @@ export const deepCopy = <T>(source: T): T => {
|
||||
return clone;
|
||||
};
|
||||
// eslint-enable
|
||||
type ErrorMessage = { errorMessage: string };
|
||||
type FallbackValue<T> = { fallbackValue: T };
|
||||
|
||||
export const jsonParse = <T>(
|
||||
jsonString: string,
|
||||
options: ErrorMessage | FallbackValue<T> | {} = {},
|
||||
): T => {
|
||||
type MutuallyExclusive<T, U> =
|
||||
| (T & { [k in Exclude<keyof U, keyof T>]?: never })
|
||||
| (U & { [k in Exclude<keyof T, keyof U>]?: never });
|
||||
|
||||
type JSONParseOptions<T> = MutuallyExclusive<{ errorMessage: string }, { fallbackValue: T }>;
|
||||
|
||||
export const jsonParse = <T>(jsonString: string, options?: JSONParseOptions<T>): T => {
|
||||
try {
|
||||
return JSON.parse(jsonString) as T;
|
||||
} catch (error) {
|
||||
if ('fallbackValue' in options) {
|
||||
if (options?.fallbackValue !== undefined) {
|
||||
return options.fallbackValue;
|
||||
}
|
||||
if ('errorMessage' in options) {
|
||||
} else if (options?.errorMessage) {
|
||||
throw new Error(options.errorMessage);
|
||||
}
|
||||
|
||||
throw error;
|
||||
}
|
||||
};
|
||||
|
||||
Reference in New Issue
Block a user