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

Is it feasible to generate multiple app.get requests with express.js using a for loop?

Hey there, looking for some assistance since this is my first post here. I'm currently working on my main.js file and trying to figure out an easier way to do things like this: var pages = { "/profile":{"page":"My Profile","loc":"./contentPages/prof ...

The issue with downloading all files in Firefox persists when attempting to download multiple files simultaneously due to an anchor click

I am currently facing an issue with downloading multiple files using TypeScript in Angular 6. I am receiving an array of blobs from a web API service. Here is the service method used to get multiple blobs for downloading: private downloadTest(): void { ...

Controlling CSS Styles in Angular using TypeScript

Currently, I am working on an Angular project that involves dynamically populating a calendar. In addition to this, I have a range of dates and the task at hand is to modify the background for specific days within this date range. To manage dates effective ...

The SQL query in my PHP code is not functioning properly with the specified value

After attempting to organize data from my SQL table by username, I realized that this is based on the user connected to the website. <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewpor ...

Exploring generic types using recursive inference

The scenario: export type SchemaOne<T> = | Entity<T> | SchemaObjectOne<T>; export interface SchemaObjectOne<T> { [key: string]: SchemaOne<T>; } export type SchemaOf<T> = T extends SchemaOne<infer R> ? R : nev ...

Determine the value added tax in your online shopping basket

Currently, I am in the process of developing a webshop for a pizzeria using Angular, and recently completed work on my cart component. One of the key features I wanted to incorporate was adding a 10% Value-Added Tax (VAT) for each item in the cart and incl ...

Adding an extra condition in the WHERE clause when using the MySQL Update statement

I've encountered an issue with my MySQL Update statement. Initially, it was functioning correctly. UPDATE Table1 SET Table1_field1='field1_content', Table1_field2='field2_content' where Table1_field3=2 All the fields mentioned ab ...

Encoding in utf-8 for MySQL and PHP

I'm facing a dilemma with UTF-8 characters like "Ä", "Ö", "Ü" and others. My webpage contains a form where users can input messages. These messages should be stored in a MySQL database and retrieved to display on the screen. The issue arises when ...

Even after ensuring the proper type checking, I am still receiving the error message "Property 'message' does not exist on type 'object'"

I have the following code snippet: try { // api call } catch (error) { if (typeof error === 'object' && error !== null && 'message' in error) { if (typeof error.message === 'string') { if (error.me ...

Determine the type of the final function within a variable number of nested closures

Imagine you have a function like this: const f = a => b => ... x => { return somevalue } Is there a way to determine the type of just the final function typeof x => { return somevalue } even if we don't know how many closures come before ...

In TypeScript, the NonNullable type is like Required, but it ensures that all object properties are converted to non-

When working with TypeScript, you may have come across the Required type which transforms object properties into defined ones. For instance: interface Person { name?: string; age?: number; } Using Required<Person> will result in: interface Pe ...

What is the best way to access a variable outside of an array in PHP when working with MySQL?

I have a significant foreach loop that contains nested loops and conditionals. Before diving into the code itself, I need to extract a value from the option_data array - what is the best way to do this? foreach ($this->cart->getProducts() as $prod ...

When executing an inner join query in MySql, multiple rows must be matched

I'm working on a MySQL query to retrieve an ID only if it matches specific criteria in the rows I specify. Table: view_layout_rows ID owner rows ___________________ 49 1 2 50 1 2 Table: view_layout_rows_columns ID r ...

Using TypeScript generics to add constraints to function parameters within an object

My Goal: Imagine a configuration with types structured like this: type ExmapleConfig = { A: { Component: (props: { type: "a"; a: number; b: number }) => null }; B: { Component: (props: { type: "b"; a: string; c: number }) =& ...

Implement Material-UI's built-in validation for form submission

I'm in the process of setting up a form with validation: import React from 'react'; import { useForm } from "react-hook-form"; import axios, {AxiosResponse} from "axios"; import {Box, Button, Container, Grid, Typography} ...

We encountered an error while trying to locate the 'socket.io' view in the views directory

Having an issue with my nodejs server. Check out the code below: server.js global.jQuery = global.$ = require('jquery'); var express = require('express'), path = require('path'), menu = require("./routes/menu"); var ...

Setting up ExpressJS with gulp for automatic reloading using gulp-live-server

I have a basic express 4.x testing application. I am aware that using gulp can enable auto-reloading, which automatically restarts the server after any content changes. I successfully configured the handlebars template engine with express. This is how my ...

Creating an Angular 2 component that utilizes an interface within the constructor

If you have an interface named IData, and you want to develop an Angular 2 component that can accept any Class utilizing IData in its constructor, could this concept be implemented or is it off track? Your insights are greatly appreciated. ...

Is there a way to transmit custom JSON to node.js without having to refresh the page?

My main objective is to send custom JSON data to node.js when a button is clicked. I am currently familiar with sending form input only. Below is the code snippet I have used to send form data: function postForm() { $('form').submit(function(e ...

Mismatched non-intersecting categories with TypeScript

I have an object that I need to conditionally render some JSX based on certain properties. I want to restrict access to specific parts of the object until certain conditions are met. Here is my scenario: const { alpha, bravo } = myObject; if (alpha.loadin ...