Skip to content

Commit

Permalink
fix: allow array query parameter for a single value
Browse files Browse the repository at this point in the history
Signed-off-by: mrmodise <modisemorebodi@gmail.com>
  • Loading branch information
mrmodise committed Oct 12, 2020
1 parent cf61cef commit a133736
Show file tree
Hide file tree
Showing 2 changed files with 53 additions and 0 deletions.
Expand Up @@ -144,6 +144,14 @@ describe('Coercion', () => {
) {
return filter;
}

@get('/array-parameters-from-query')
getArrayFromQuery(
@param.array('stringArray', 'query', {type: 'string'})
stringArray: string[],
) {
return stringArray;
}
}

it('coerces parameter in path from string to number', async () => {
Expand Down Expand Up @@ -283,6 +291,30 @@ describe('Coercion', () => {
);
});

describe('coerces array parameters', () => {
it('coerces a single value into an array with one item', async () => {
const response = await client
.get('/array-parameters-from-query')
.query({
stringArray: 'hello',
})
.expect(200);

expect(response.body).to.eql(['hello']);
});

it('preserves array values as arrays', async () => {
const response = await client
.get('/array-parameters-from-query')
.query({
stringArray: ['hello', 'loopback', 'world'],
})
.expect(200);

expect(response.body).to.eql(['hello', 'loopback', 'world']);
});
});

async function givenAClient() {
app = new RestApplication({rest: givenHttpServerConfig()});
app.controller(MyController);
Expand Down
21 changes: 21 additions & 0 deletions packages/rest/src/coercion/coerce-parameter.ts
Expand Up @@ -95,6 +95,9 @@ export async function coerceParameter(
case 'password':
result = coerceString(data, spec);
break;
case 'array':
result = coerceArray(data, spec);
break;
}

if (result != null) {
Expand All @@ -103,6 +106,7 @@ export async function coerceParameter(
await validateParam(spec, data, options);
return result;
}

result = await validateParam(spec, result, options);
}
return result;
Expand Down Expand Up @@ -199,6 +203,23 @@ async function coerceObject(input: string | object, spec: ParameterObject) {
return data;
}

function coerceArray(
data: string | number | boolean | object,
spec: ParameterObject,
) {
if (spec.in === 'query') {
if (
typeof data === 'string' ||
typeof data === 'number' ||
typeof data === 'boolean'
) {
return [data];
}
}

return data;
}

function validateParam(
spec: ParameterObject,
// eslint-disable-next-line @typescript-eslint/no-explicit-any
Expand Down

0 comments on commit a133736

Please sign in to comment.