Analyzing the object for interface compatibility

When I receive a query string in one of my REST endpoints using koa-router, each value of the query string object parameter is always a string:

{
  count: "120",
  result: "true",
  text: "ok"
}

Within my codebase, I have an Interface that represents the query string object:

interface Params {
  count: number;
  result: boolean;
  text: string;
}

I aim to convert the query string object so that all values match this interface. What are the best practices for accomplishing this?

Answer №1

It's unusual to receive numbers and booleans as strings, given that JSON allows unquoted values for both numeric and boolean data types.

The JSON.parse() method includes an optional reviver callback parameter, which you can utilize within a request interceptor to standardize string representations of numbers and booleans before they reach your interface.

const data = `{
  "count": "120",
  "resut": "false",
  "text": "ok"
}`

const reviver = (key, value) => {
   if(typeof value === 'string' && !isNaN(value)){
       return Number(value)
   }else if(value === 'true' || value === 'false'){
       return value === 'true' ? true : false;
   }   
   return value;
}

console.log(JSON.parse(data, reviver ))

Answer №2

To ensure the input aligns with the expected interface, it is important to convert each property to the correct type.

function convertInputToParams(input:any) : Params {
    var obj = typeof input === "string" 
            ? JSON.parse(input) 
            : input;
    obj.count = +obj.count;
    obj.result = obj.result === "true" ? true : false;
    return obj as Params;
}

An alternative approach would be to create a default instance of Params with predefined properties, then iterate over them to verify that each property in the converted object matches the expected type.

function convertInputToInterface(example:any, input:any) {
    Object.keys(example).forEach(function(key,index) {
        if (!input[key]) return;
        let exampleType = typeof example[key];
        let inputType = typeof input[key];
        if (exampleType !== inputType) {
            if (exampleType == "string") input[key] = input[key] + "";
            if (exampleType == "number") input[key] = +input[key];
            if (exampleType == "boolean") input[key] = input[key] === "true" ? true : false;
            // Handle other cases as needed
        }
    });
    return input;
}

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

I am interested in setting up a flickr gallery where clicking on an image will display a pop-up showing the image along with its relevant tags, title, and photo ID

Page´s photo Hello there, I am currently working on creating a Flickr API using JavaScript and HTML. My goal is to search for photos and display them in an HTML page, but I'm struggling with implementing a pop-up feature that includes the photo' ...

What is causing the failure of success function commands to be executed?

Currently, I am facing some inconsistencies between my locally hosted app on WAMP (working perfectly) and the deployed version of my app. In an attempt to resolve this issue, I am working with CodeIgniter and jQuery AJAX. As part of my troubleshooting proc ...

How can I set up Prettier to exclude a line following a specific pattern?

Is there a method to configure Prettier in Visual Studio Code to exclude lines following a specific pattern? Sometimes, I require a directive like /**@ts-ignore */ followed by a lengthy line. However, when Prettier formats the code, it introduces new line ...

"Encountered issues during compiling: X ERROR found at line 9 in the Header.js file, spanning from characters

An error occurred while compiling the module. The following message was displayed: Module not found: Error: Can't resolve '@mui/icons-material/Search' in 'C:\Users\pande\Documents\slack-clone\src\component ...

The server encountered a "Cannot GET /socket.io" error while trying

I am experiencing an issue with my app that uses express/socket.io. The app is running smoothly without any errors, but when I make an http-request, I receive the following error message: GET http://xxxxxxx.com:3035/socket.io/1/?t=1449090610579 400 (Bad R ...

Creating an asynchronous function using EventEmitter

I am new to node.js and I'm trying to take advantage of asynchronous and event-driven behavior in my code. I used to think that in node, anything involving an Event object would result in asynchronous execution. So I decided to test this theory with ...

Updating the titles of Bootstrap 4 Switches on the fly

Currently utilizing Bootstrap 4 Toggle on my website, I'm struggling to figure out how to dynamically modify the labels on the toggles at runtime. My objective is to implement a toggle-switch that, once activated, displays a countdown indicating the ...

Error: Validation error occurred with document - reason unknown

Recently, I've been working on developing a basic CRUD application using MongoDB as my database. However, I keep encountering an error labeled MongoError: Document failed validation, and I am struggling to pinpoint the issue. The data appears to be s ...

Tips for placing modal box in the exact desired position upon loading

I've been searching for a solution on how to dynamically calculate the position of each image loaded in a Twitter modal box and place the box underneath a custom toolbar element I have created. The situation is depicted in the image. The height of the ...

The undefined dispatch function issue occurs when trying to pass parameters from a child component to React

There is an action that needs to be handled. It involves saving a new task with its name and description through an API call. export const saveNewTask = (taskName, taskDescription) => async dispatch => { console.log(taskName, taskDescription); c ...

execute the function within the data() method

I'm currently working on retrieving data for my search tree, and I'm facing issues with fetching the data directly from axios or calling a function because it cannot be found. export default { name: 'SideNavMenu', data () { return ...

Tips for enabling selection of list items in an input tag

Below is the code I have written to create an InputFilter. MyFilter = function(args) { var dataUrl = args.url; var divID = args.divID; var div = document.getElementById(divID); var myTable = '<input type="text" id="myInput" on ...

Module not found in Node.js Express JS

I've read several topics on this issue here at stackoverflow, but I am still unable to get my node application running. When I try to run the command: node app.js local I receive the following error: Error: Cannot find module './config' ...

Arranging an ng-repeat list in a dynamic order

I am currently working with AngularJS and focusing on reordering the ng-repeat list. The list represents online users who can receive messages at any time. When a user receives a message, I update the UI to display the most recent message beneath their nam ...

Positioning a material UI dialog in the middle of the screen, taking into account variations in its height

Dealing with an MUI Dialog that has a dynamic height can be frustrating, especially when it starts to "jump around" the screen as it adjusts to fit the content filtered by the user. Take a look at this issue: https://i.stack.imgur.com/IndlU.gif An easy f ...

Using a semicolon at the end of the line is considered a favorable practice when writing ES6 code in Babel

After browsing through various tutorials on the internet that utilize redux and react, I came across a common trend of omitting semicolons in ES6 code when using Babel. For instance, some examples neglect to include semicolons at the end of import or expo ...

How can I dynamically insert various FormGroup instances into a FormArray in Angular?

I am looking to dynamically populate the order array with multiple dishes. Each dish will be stored as a FormGroup in the form, such as pizza, salad, drink, or any other type of dish. Prior to adding any items, the form structure should resemble this: this ...

What is the best way to define a custom route in react-router-dom?

My goal is to have the URL display "/login" in the address bar when I am on the login page. // App.js <Routes> {isLoggedIn ? ( <Route path="/" element={<Root onLogout={handleLogout} />}> <Route index e ...

Tips for customizing the background color of the MUI Menu Popover within a TextField that has the select property

In my quest to customize the appearance of a popover or menu in a TextField with the 'select' property, I referred to MUI customization docs for guidance. Successfully changing the text and label color of a TextField using the code below: const u ...

How to prevent unnecessary new instances from being created by the Inject() function in Angular

Can someone please clarify if the inject() function provides different instances of a service? I suspect this might be why my code is not functioning as expected. Let's examine the code snippet below: { path: 'recipes', comp ...