0

I have a basic route that implements the following:

router.get('/twitter/tweets', async (ctx) => {
  const { limit, page, search } = ctx.query
  ctx.body = {
    tweets: await twitter.all(limit, page, search),
  }
})

The problem I have is with types. The items from ctx.query return string[] | string.

The service that it calls is as follows:
async function all(_limit = 50, _page = 0, _search = '') {

Therefore the limit and page values are expected to be numbers. What is the best way to handle koa ctx validation in order to pass the correct types to the service.

StuartM
  • 6,743
  • 18
  • 84
  • 160

1 Answers1

0

Due to the documentation (https://koajs.com/#request), request.query return an object and the values are strings and you are correctly destructuring this object and now have the values as strings in your variables limit, page and search.

So there are different possibilities of validating the values:

For the your input values you could do something like:

isInt = (n) => {
    const intVal = parseInt(n, 10);
    return !isNaN(intVal) && ('' + intVal === n)
}

isAlphanumeric = (str) => {
    return str.match(/^[a-zA-Z0-9]+$/);
},

if (isInt(limit) && isInt(page) && isAlphanumeric(str)) {
  ctx.body = {
    tweets: await twitter.all(parseInt(limit,10), parseInt(page, 10), search),
  } 
}

Maybe you need to be more sophisticated validating your numeric and string values. E.g. you could check also min and max values for your numeric values, or string length ... but this is depending on your specific use case.

Dharman
  • 30,962
  • 25
  • 85
  • 135
Sebastian Hildebrandt
  • 2,661
  • 1
  • 14
  • 20
  • Thanks, I think that even though they are destructured the type is "string" | ["string"] so it could either be a string or an array of strings from ctx.query. – StuartM Mar 23 '21 at 11:15