typescriptdenooak

Deno: Access query params in controller


I wrote a couple of apis for a Deno POC.

This is the route code:

const router = new Router()
router.get('/posts', getPosts)
      .get('/posts/:id', getPostsById)

For the second route, I am able to get path param in controller: getPostsById using the keyword: params. This is the controller code:

export const getPostsById = (
  { params, response }: { params:any, response: any }) => {
    console.log(params, '||| params')}

How can I get the query param in similar fashion (eg: /posts/2222?userId=3)

I am using oak for routing. I tried various keywords from oak codebase: query, search etc but no success.

I tried getQuery from the Oak documentation as well, but I am completely unable to import it.


Solution

  • In Oak ou can use .searchParams

    ctx.request.url.searchParams
    

    For getting userId you would use:

    const userId = ctx.request.url.searchParams.get('userId')
    

    getQuery from helpers.ts is only on master currently since it was introduced 12 hours ago.

    Instead of using https://deno.land/x/oak@v4.0.0/mod.ts you can import https://deno.land/x/oak/helpers.ts that will pull from master. This is not recommended though, but will do until a new version is released and you can use a tagged import.

    import { getQuery } from 'https://deno.land/x/oak/helpers.ts'
    
    router.get("/book/:id/page/:page", (ctx) => {
      getQuery(ctx, { mergeParams: true });
    });