Skip to content

Commit

Permalink
add key assertion
Browse files Browse the repository at this point in the history
  • Loading branch information
tintinthong committed Nov 4, 2024
1 parent 148551a commit 2611f1a
Showing 1 changed file with 17 additions and 38 deletions.
55 changes: 17 additions & 38 deletions packages/runtime-common/query.ts
Original file line number Diff line number Diff line change
Expand Up @@ -307,9 +307,9 @@ function assertEveryFilter(
`${pointer.join('/') || '/'}: every must be an array of Filters`,
);
} else {
filter.every.every((value: any, index: number) =>
assertFilter(value, pointer.concat(`[${index}]`)),
);
filter.every.forEach((value: any, index: number) => {
assertFilter(value, pointer.concat(`[${index}]`));
});
}
}

Expand Down Expand Up @@ -348,9 +348,10 @@ function assertEqFilter(
if (typeof filter.eq !== 'object' || filter.eq == null) {
throw new Error(`${pointer.join('/') || '/'}: eq must be an object`);
}
Object.entries(filter.eq).every(([key, value]) =>
assertJSONValue(value, pointer.concat(key)),
);
Object.entries(filter.eq).forEach(([key, value]) => {
assertKey(key, pointer);
assertJSONValue(value, pointer.concat(key));
});
}

function assertContainsFilter(
Expand All @@ -371,9 +372,10 @@ function assertContainsFilter(
if (typeof filter.contains !== 'object' || filter.contains == null) {
throw new Error(`${pointer.join('/') || '/'}: contains must be an object`);
}
Object.entries(filter.contains).every(([key, value]) =>
assertJSONValue(value, pointer.concat(key)),
);
Object.entries(filter.contains).forEach(([key, value]) => {
assertKey(key, pointer);
assertJSONValue(value, pointer.concat(key));
});
}

function assertRangeFilter(
Expand Down Expand Up @@ -420,33 +422,10 @@ function assertRangeFilter(
});
}

const removeBrackets = (obj: any): any => {
if (!obj || typeof obj !== 'object') return obj;

// Handle arrays
if (Array.isArray(obj)) {
return obj.map((item) => removeBrackets(item));
export function assertKey(key: string, pointer: string[]) {
if (key.startsWith('[') && key.endsWith(']')) {
throw new Error(
`${pointer.join('/')}: field names cannot be wrapped in brackets: ${key}`,
);
}

return Object.entries(obj).reduce((acc, [key, value]) => {
// Remove surrounding brackets if they exist
const newKey = key.replace(/^\[(.*)\]$/, '$1');

// Handle arrays in values
if (Array.isArray(value)) {
acc[newKey] = value.map((item) => removeBrackets(item));
} else if (typeof value === 'object' && value !== null) {
// Recursively removeBrackets nested objects
acc[newKey] = removeBrackets(value);
} else {
// Handle primitive values
acc[newKey] = value;
}

return acc;
}, {} as any);
};

export const parseQuery = (queryString: string) => {
return removeBrackets(qs.parse(queryString));
};
}

0 comments on commit 2611f1a

Please sign in to comment.