Matching TypeScript search field names with column names

Seeking ways to create an API that allows admins to search for users in the database using various fields.

// Define allowed search fields
type SearchFieldType = 'name' | 'memberNo' | 'email' | 'companyName';

const dbColumns = ['username', 'member_no', 'email', 'company_name'] as const;

Admins can input one or multiple search fields when making requests through the API.

How can I determine which field is provided in the API request and search the corresponding column in the database without relying on if-else statements due to potential future expansions of columns?

Answer №1

It is crucial to have a corresponding SearchFieldType assigned to each database column. By meticulously creating this association, any attempt to introduce a new dbCol will be met with an error in the mapping process. For instance:

type SearchFieldType = 'fullName' | 'userNo' | 'emailAddress' | 'businessName';

type DbCol = 'uname'|'no_of_mem'|'e_address' |'biz_name';

const colToSearchTimeMapping: Record<DbCol, SearchFieldType> = {
    e_address: "fullName",
    uname: "userNo",
    no_of_mem: "userNo",
    biz_name: "businessName",
}

typescript playground showcasing an error due to an additional column

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

What is the best way to deliver pictures to the client?

While working on a website with express.js, I am considering the best way to store images. For certain aspects of the site, such as team pages, we will be using a database. When new team members join, we will update CouchDB with their information and a new ...

How can you navigate to a particular page within a Single Page Application using NodeNS?

My NodeJS server is hosting a single page application that was built using Angular5. In certain circumstances, I need to direct users to a specific page within the application. For instance, during a designated time period, I want users to be redirected t ...

Simulated database in a Service using TypeScript with Node

Struggling with a unit test, I need to mock the this.orderRepository.findById(id); method to find an object by its ID. Although I've set the return value, the test keeps failing. This is my first time creating a unit test in Node using TypeScript and ...

Exploring the use of MockBackend to test a function that subsequently invokes the .map method

I've been working on writing unit tests for my service that deals with making Http requests. The service I have returns a Http.get() request followed by a .map() function. However, I'm facing issues with getting my mocked backend to respond in a ...

Does Express.js not asynchronously call the router callback function in the same way?

When calling '/a', '/b' can be executed immediately. However, if I call another '/a', the second one waits for the first one to finish. How can I make the call to '/a' truly asynchronous? Code: app.get '/a&apo ...

Should you opt for returning [something] or (nothing) in Javascript with ExpressJS?

Is there a distinct contrast between returning something and returning nothing? Let's take a look at an example: user.save(function(err){ if ( err && err.code !== 11000 ) { console.log(err); console.log(err.code); res.send(&apo ...

What is the best way to integrate a plugin system into a web application built using Express and React?

My goal is to create a system where plugins (such as comments, games, communities, etc.) can be standalone from the main application. This way, not only can I develop plugins but other developers can also have the opportunity to create and sell their own ...

The Nodejs application experienced a crash on Heroku due to an error when attempting to connect to localhost at port

I've been trying to troubleshoot this issue, but every solution I attempt leads to the same outcome. It seems to be related to the localhost, but the specific problem eludes me. The errors I encounter when I check heroku logs are as follows: 2013-08- ...

Combining Mongoose OR conditions with ObjectIDs

After querying my Team schema, I am receiving an array of ids which I have confirmed is correct. The issue seems to lie in the fact that both home_team and away_team are ObjectIDs for the Team Schema within my OR statement. Team.find({ 'conferenc ...

Guide to Validating Fields in Angular's Reactive Forms After Using patchValue

I am working on a form that consists of sub-forms using ControlValueAccessor profile-form.component.ts form: FormGroup; this.form = this.formBuilder.group({ firstName: [], lastName: ["", Validators.maxLength(10)], email: ["", Valid ...

What is the cost associated with connecting to a MySQL database in terms of operation expenses?

During certain functions within the code, PHP performs numerous queries on the same tables using loops. Each query currently creates a new database connection, but how costly is this operation? Would reusing the same connection result in a noticeable speed ...

Ways to filter out specific fields when returning query results using Mongoose

I was wondering about the code snippet below: Post.create(req.body) .then(post => res.status(201).json(post)) .catch(err => res.status(500).json(err)) While this code works perfectly, I am curious about excluding a specific field, such as the __v fi ...

Using the as operator in TypeScript for type casting a string

function doSomething(a : any) { let b = (a as Array<any>) alert(typeof b) // displays "string" } doSomething("Hello") The alert is showing "string" instead of what I anticipated, which was something along the lines of a null value. The docu ...

The type 'xxxx' is not compatible with the parameter type 'JSXElementConstructor<never>'

I am currently enrolled in a TypeScript course on Udemy. If you're interested, you can check it out here. import { connect } from 'react-redux'; import { Todo, fetchTodos } from '../actions'; import { StoreState } from '../red ...

Experimenting with an Express route that includes a callback function for testing purposes

I am attempting to simulate a curl request to an express route that interacts with an API. While I have come across various resources on how to achieve this, I am encountering difficulties due to the presence of a callback in my code. var request = requir ...

Idea fails to detect imports

I have been attempting to use Angular2 in IntelliJ IDEA IDE. Although my code is valid (I have tried compiling and executing it), the IDE keeps showing me this error: https://i.stack.imgur.com/w6wIj.jpg Is there a way to configure IntelliJ IDEA to hide t ...

Filter the output from a function that has the ability to produce a Promise returning a boolean value or a

I can't help but wonder if anyone has encountered this issue before. Prior to this, my EventHandler structure looked like: export interface EventHandler { name: string; canHandleEvent(event: EventEntity): boolean; handleEvent(event: EventEntity ...

Establish a connection to mongoDB within a PHP script using inner join

I've been struggling to convert this MySQL query into MongoDB in order to optimize my data, but I just can't seem to crack it... MySQL query SELECT notifications.entity_id FROM notifications INNER JOIN discussions ON notifications.entity_id = ...

Steps for retrieving user information post authentication query:1. Begin by initiating the query to authenticate the

This is my script.js file var express = require('express'); var router = express.Router(); var expressValidator = require('express-validator'); var passport = require('passport'); const bcrypt = require('bcrypt'); c ...

When using a Redux action type with an optional payload property, TypeScript may raise complaints within the reducer

In my react-ts project, I define the following redux action type: type DataItem = { id: string country: string population: number } type DataAction = { type: string, payload?: DataItem } I included an optional payload property because there are tim ...