Deno: Access query params in controller
Asked Answered
E

1

7

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.

Exhibitioner answered 26/5, 2020 at 18:48 Comment(0)
J
12

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 });
});
Jasper answered 26/5, 2020 at 19:20 Comment(1)
Thanks! @marcos: this worked. This is my controller code now: export const getPosts = ( { request, response }: { request: any, response: any }) => { const userId = request.url.searchParams.get('userId'); console.log(userId, '||| userId'); }Exhibitioner

© 2022 - 2024 — McMap. All rights reserved.