Skip to content

Commit

Permalink
Avoid question mark in API calls without query string (#6455)
Browse files Browse the repository at this point in the history
  • Loading branch information
acelaya authored Jul 22, 2024
1 parent 59ce336 commit cbf339f
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 6 deletions.
10 changes: 4 additions & 6 deletions lms/static/scripts/frontend_apps/utils/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -111,11 +111,8 @@ export async function apiCall<Result = unknown>(
headers['Content-Type'] = 'application/json; charset=UTF-8';
}

let query = '';
if (params) {
const urlParams = recordToSearchParams(params);
query = '?' + urlParams.toString();
}
const queryString = recordToSearchParams(params ?? {}).toString();
const query = queryString.length > 0 ? `?${queryString}` : '';

const defaultMethod = data === undefined ? 'GET' : 'POST';
const result = await fetch(path + query, {
Expand Down Expand Up @@ -211,6 +208,7 @@ export function useAPIFetch<T = unknown>(
// something simpler, as long as it encodes the same information. The auth
// token is not included in the key, as we assume currently that it does not
// change the result.
const paramStr = params ? '?' + recordToSearchParams(params).toString() : '';
const queryString = recordToSearchParams(params ?? {}).toString();
const paramStr = queryString.length > 0 ? `?${queryString}` : '';
return useFetch(path ? `${path}${paramStr}` : null, fetcher);
}
15 changes: 15 additions & 0 deletions lms/static/scripts/frontend_apps/utils/test/api-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -417,11 +417,26 @@ describe('useAPIFetch', () => {
params: undefined,
expectedURL: '/api/some/path',
},
{
path: '/api/some/path',
params: {},
expectedURL: '/api/some/path',
},
{
path: '/api/some/path',
params: { ignored: [] },
expectedURL: '/api/some/path',
},
{
path: '/api/some/path',
params: { foo: 'bar', baz: 'meep' },
expectedURL: '/api/some/path?foo=bar&baz=meep',
},
{
path: '/api/some/path',
params: { foo: 'bar', array: ['hello', 'world'] },
expectedURL: '/api/some/path?foo=bar&array=hello&array=world',
},
].forEach(({ path, params, expectedURL }) => {
it('fetches data from API if a path is provided', async () => {
const result = useAPIFetch(path, params);
Expand Down

0 comments on commit cbf339f

Please sign in to comment.