Skip to content

Commit

Permalink
Merge pull request #84 from microcmsio/fix/remove-undefined-property-…
Browse files Browse the repository at this point in the history
…from-searchparams

Remove undefined values from query string in parseQuery
  • Loading branch information
himorishige authored Jun 24, 2024
2 parents 1bc3145 + f48a8bc commit 836942f
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 3 deletions.
4 changes: 3 additions & 1 deletion src/utils/parseQuery.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,9 @@ export const parseQuery = (queries: MicroCMSQueries): string => {
const queryString = new URLSearchParams(
Object.entries(queries).reduce(
(acc, [key, value]) => {
acc[key] = String(value);
if (value !== undefined) {
acc[key] = String(value);
}
return acc;
},
{} as Record<string, string>,
Expand Down
35 changes: 33 additions & 2 deletions tests/utils/parseQuery.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,14 +7,45 @@ describe('parseQuery', () => {
limit: 100,
fields: ['id', 'title'],
orders: 'publishedAt',
})
}),
).toBe('limit=100&fields=id%2Ctitle&orders=publishedAt');
});

test('Throws an error if a non-object is specified', () => {
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-expect-error
expect(() => parseQuery('')).toThrowError(
new Error('queries is not object')
new Error('queries is not object'),
);
});

test('Undefined values are removed from the query string', () => {
expect(
parseQuery({
limit: 100,
fields: undefined,
orders: 'publishedAt',
}),
).toBe('limit=100&orders=publishedAt');
});

test('Multiple undefined values are removed from the query string', () => {
expect(
parseQuery({
limit: undefined,
fields: undefined,
orders: 'publishedAt',
}),
).toBe('orders=publishedAt');
});

test('All undefined values results in an empty query string', () => {
expect(
parseQuery({
limit: undefined,
fields: undefined,
orders: undefined,
}),
).toBe('');
});
});

0 comments on commit 836942f

Please sign in to comment.