Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 625
atish Avatar asked Jul 22 '26 04:07

atish


1 Answers

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/[email protected]/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 });
});
like image 129
Marcos Casagrande Avatar answered Jul 24 '26 22:07

Marcos Casagrande



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!