Implementing query parameters in a Deno controller

I developed a couple of APIs for a Deno Proof of Concept.

This is the route implementation:

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

In the second route, I successfully retrieved the path parameter in the controller function getPostsById using the variable: params. Here is the corresponding controller code:

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

Now I am wondering how to retrieve query parameters in a similar manner (e.g., /posts/2222?userId=3)

My routing framework is Oak. Despite trying different keywords like query and search from the Oak library, I have not been able to succeed in fetching the query parameter.

I also attempted to use getQuery method as suggested in the Oak documentation, but I faced issues with importing it into my project.

Answer №1

When working with Oak, you have the option to utilize .searchParams

ctx.request.url.searchParams

To retrieve the userId, you can use:

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

The function getQuery from file helpers.ts is currently available only on the master branch as it was added just 12 hours ago.

If you want to avoid using

https://deno.land/x/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="1d727c765d6b29332d332d">[email protected]</a>/mod.ts
, you can import
https://deno.land/x/oak/helpers.ts
which will fetch from master. This approach is not preferred, but can be used temporarily until a new version is released and tagged import becomes an option.

import { getQuery } from 'https://deno.land/x/oak/helpers.ts'

router.get("/book/:id/page/:page", (ctx) => {
  getQuery(ctx, { mergeParams: true });
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Guide to turning off the previous button in FullCalendar using Angular 7 and TypeScript

Can someone help me with disabling the previous button on FullCalendar if I go back 2 months? For example, if it's currently April and I navigate to February, I want the previous button to be disabled. I have FullCalendar implemented, but all the sol ...

TypeScript interface designed to capture objects containing a flexible number of values

In my possession is an object that looks like the following: { "0001": "a", "0002": "b", "0003": "c", ... } Is it possible for me to create a TypeScript interface that accurately represents this type? ...

Varieties of data classifications for the information obtained from supabase

1 I'm encountering an issue while attempting to define the data types from Supabase. I received an error message stating: "type '{ id: string; title: string; capacity: number | null; start_date: Date | null; start_time: string | null; end_ ...

Ensure that the background view remains interactive while adding an overlay on top for an enhanced user experience

Hey everyone, I could use some help with a question I have. My issue is that I am struggling to figure out how to make two views overlap while still allowing the background view to be interactive. Currently, I am using absolute positioning for the foregr ...

Can you change the method definition of a built-in class using TypeScript?

Working with the Web Audio Api in TypeScript has presented me with a minor issue. I am trying to enhance AudioParam's prototype by adding some convenience methods that can be used on any parameter. However, I keep getting an error from the compiler st ...

Tidying up following the execution of an asynchronous function in useEffect

Recently, I've been facing a challenge while migrating a React project to TypeScript. Specifically, I'm having trouble with typing out a particular function and its corresponding useEffect. My understanding is that the registerListener function s ...

Tips for widening a union data type in a different section?

Is there a way to expand on a union type from another module? Below is an example showcasing the need for this, but I encountered a ts(3200) error due to duplicate identifiers. The Core module @org/core defines a union type called OptionType: // Defined i ...

Issue with Angular standalone component importation causing rendering issue in HTML

Recently, I started working with Angular and I am currently creating a clone using Firebase. While working on this project, Angular is throwing two errors at me: The Component AppComponent is standalone and cannot be declared in an NgModule. Should it b ...

What is the syntax for using typeof with anonymous types in TypeScript?

After reading an article, I'm still trying to grasp the concept of using typeof in TypeScript for real-world applications. I understand it's related to anonymous types, but could someone provide a practical example of how it can be used? Appreci ...

Using TypeScript to chain observables in a service and then subscribing to them in the component at the end

Working with Platform - Angualar 2 + TypeScript + angularFire2 Within my user.service.ts file, I have implemented the following code to initiate an initial request to a firebase endpoint in order to fetch some path information. Subsequently, I aim to util ...

Visual Studio Code continues to compile code automatically without requiring me to save any changes

Question: VSC triggers compilation even without any file changes in Angular(6) project ng serve It's frustrating when Visual Studio Code starts compiling repeatedly, even when no changes have been made. How can I prevent this from happening? I&apos ...

Optimal method for consecutively making N number of API calls in Angular 9 in a synchronous manner

Having a service method for API calls structured as follows: getUsers(id){ return this.http.get(`${env.apiURL}/id`) } Now, the requirement is to call this method for a list of users stored in an array: userId=[1,2,3,4,5,6,7,8,9] The goal is to retrieve ...

The variable type does not align with the export type

My TypeScript project includes a file that loads environment variables and exports them: const.ts: const { VARIABLE0, // type of VARIABLE0 is string | undefined VARIABLE1, } = process.env; if (!VARIABLE0 || !VARIABLE1) { throw new Error('Inval ...

Printing from a lengthy React DOM using window.print only generates a single page

My React component is capable of rendering markdown and can span multiple pages. Everything looks great when the component is displayed in the browser - scrolling works perfectly. However, whenever I try to print the page using window.print or ctrl + P, ...

How to resolve the issue of not being able to access functions from inside the timer target function in TypeScript's

I've been attempting to invoke a function from within a timed function called by setInterval(). Here's the snippet of my code: export class SmileyDirective { FillGraphValues() { console.log("The FillGraphValues function works as expect ...

Loading a view in Ionic2 with Angular2 after a successful subscription

After completing an http post request, I want to navigate to the next view in my app. Here is a breakdown of the three services I am using: The server service handles generic http calls such as get and post requests. The city service stores a list of ...

Currently, I am utilizing version 6.10.0 of @mui/x-date-pickers. I am interested in learning how to customize the color and format of a specific component within the library

I'm currently using @mui/x-date-pickers version 6.10.0 and I need to customize the color and format for a specific section in the mobile view. How can I achieve this? I want to display the date as "May 31st" like shown in the image below. Is there a ...

What causes the NavBar to show and hide within a specific range?

Recently, I encountered a perplexing issue with my navbar. It functions correctly except for one strange behavior that has left me baffled. Why does the menu appear when I adjust the width to 631px, but disappear at 600px? And vice versa – why does it wo ...

Jest is throwing an error: Unable to access property from undefined while trying to import from a custom

I developed a package called @package/test. It functions perfectly when imported into a new, empty React TypeScript application. However, issues arise within Jest test suites. The usage of the CommonJS package version causes Jest to throw an error: Test ...

In Typescript, inheritance of classes with differing constructor signatures is not permitted

While working on implementing a commandBus, I encountered an issue when trying to register command types with command handlers for mapping incoming commands. My approach was to use register(handler : typeof Handler, command : typeof Command), but it result ...