mirror of
https://github.com/Abdulazizzn/n8n-enterprise-unlocked.git
synced 2025-12-19 19:11:13 +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:
@@ -1,34 +0,0 @@
|
||||
import { deepCopy } from './utils';
|
||||
|
||||
describe('deepCopy', () => {
|
||||
it('should deep copy an object', () => {
|
||||
const object = {
|
||||
deep: {
|
||||
props: {
|
||||
list: [{ a: 1 }, { b: 2 }, { c: 3 }],
|
||||
},
|
||||
arr: [1, 2, 3],
|
||||
},
|
||||
arr: [
|
||||
{
|
||||
prop: {
|
||||
list: ['a', 'b', 'c'],
|
||||
},
|
||||
},
|
||||
],
|
||||
func: () => {},
|
||||
date: new Date(),
|
||||
undef: undefined,
|
||||
nil: null,
|
||||
bool: true,
|
||||
num: 1,
|
||||
};
|
||||
const copy = deepCopy(object);
|
||||
expect(copy).toEqual(object);
|
||||
expect(copy).not.toBe(object);
|
||||
expect(copy.arr).toEqual(object.arr);
|
||||
expect(copy.arr).not.toBe(object.arr);
|
||||
expect(copy.deep.props).toEqual(object.deep.props);
|
||||
expect(copy.deep.props).not.toBe(object.deep.props);
|
||||
});
|
||||
});
|
||||
@@ -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