Is it necessary for me to validate the type before making each database request?

Currently, I am in the process of honing my error-handling skills within Express while using a Postgres database.

My backend code consists of numerous small functions that serve as intermediaries for handling interactions with the database in larger functions.

When it comes to sending requests, should I validate the type beforehand or simply send the request and handle any errors returned by the database?

I find myself repeatedly writing similar sections of code, which feels like a poor coding pattern. Unfortunately, I haven't been able to locate a definitive answer to this dilemma online.

// Approach #1: Type-checking before executing query
export const getPerson = ({
  emailAddress,
  personID,
}: {
  emailAddress?: string;
  personID?: string;
}) => {
   // Custom BadRequestError is thrown if input types are incorrect
  if (!isString(emailAddress)) throw new BadRequestError(); 
  if (!isUUID(personID)) throw new BadRequestError();
  return pool
    .query(
      `SELECT
        *
      FROM person
      WHERE ($1::citext IS NULL OR person.emailAddress = $1)
        AND ($2::uuid IS NULL OR person.person_id = $2)`,
      [emailAddress, personID]
    )
    .then((res) => res.rows)
    .catch(() => { throw new InternalServerError(); })
  };

// Approach #2: No type checking prior to executing query, handling error based on response
// This method may seem cleaner but can result in losing information about invalid inputs
// It also sends a bad request directly to the database

export const getPerson = ({
  emailAddress,
  personID,
}: {
  emailAddress?: string;
  personID?: string;
}) => pool
    .query(
      `SELECT
        *
      FROM person
      WHERE ($1::citext IS NULL OR person.emailAddress = $1)
        AND ($2::uuid IS NULL OR person.person_id = $2)`,
      [emailAddress, personID]
    )
    .then((res) => res.rows)
    .catch((e) => { 
      switch (e.code) {
         case '23XXX':
            throw new BadRequestError();
      }
    }
 );

In most scenarios, would you recommend sticking with approach #1 or #2? Are there other common practices worth considering?

Answer №1

Implement Opaque Types for Better Type Safety

type uniqueID = string & {__type__: 'uuid'}

(refer to relevant libraries or TypeScript challenges on GitHub for correct usage)

Instead of checking if an argument is of type T, ensure that the caller does the validation (for example, you cannot assign 'qwe' to uniqueID without using as uniqueID).


Furthermore, make sure to handle cases where passing undefined to the database is not allowed by specifying non-undefined parameters:

export const retrieveUser = ({
  email,
  userID,
}: {
  email: string;
  userID: string;
}) => ...

This enforces the requirement for these values to be present.

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

The message sent by the postman returns an empty JSON response

When attempting to send a request to test the MongoDB connection, I am getting an empty object as a response. I have checked and suspect that my test.http file is being treated as text instead of JSON... despite using app.use(express.json()) for parsing. T ...

java code unicode feature in csharp

Here's the code I am using: $(document).ready(function () { var breadCrumps = $('.breadcrumb'); breadCrumps.find('span').text("<%= ArticleSectionData.title %>"); }); The 'title' property contains values en ...

Experimenting with ngModel in a Jasmine test suite

I've created a directive that generates input fields and connects them to the scope using ngModel. When a user uses this directive in the HTML file like so: <div tk-quick-form="formStructure" form-data="formData" id="main_form" ></div> a ...

Ways to smoothly navigate to a specific element across various browsers with jQuery animation

This particular piece of code is causing some cross-browser compatibility issues: jQuery('body').animate({scrollTop: target.offset().top}, 300); Interestingly, it works perfectly in Firefox but not in Chrome. A different version of the same co ...

using javascript to get array element when hovering

I am currently exploring ways to retrieve and display the value of a div tag created with a 2D array using JavaScript. I have considered using onclick or onmouseover, but so far, neither approach has worked as expected. I am looking for a solution that avo ...

Leverage the power of React, Material-UI, and Typescript to inherit button props and incorporate a variety of unique

Looking to enhance the Material-UI button with additional variants like "square." How can I create a prop interface to merge/inherit props? Check out the following code snippet: import React from "react"; import { Button as MuiButton } from "@material-u ...

Using jQuery to eliminate any symbols from a text field

I am working on a text symbol removal function. However, I want to make sure that commas and periods ( . , ) are retained in the text field. Currently, the function is removing everything except digits. How can I modify it to keep the commas and dots int ...

Issue with obtaining access token in Angular 8 authentication flow with Code Flow

As I work on implementing SSO login in my code, I encounter a recurring issue. Within my app.module.ts, there is an auth.service provided inside an app initializer. Upon hitting the necessary service and capturing the code from the URL, I proceed to send a ...

Tips for sending AngularJS expressions to a controller

I am looking to pass a value from an AngularJS Expression to the controller. Here is the HTML code : <div data-ng-controller="AlbumCtrl"> <div data-ng-repeat="z in songInfo"> <div data-ng-repeat="b in z.album& ...

When integrating react-hook-form with Material-UI TextField in a form, an error occurs stating that "TypeError: e.target is undefined" when

Hey there, I stumbled upon something fascinating and could really use some assistance. Every time I attempt to perform an onChange, I run into the following error: TypeError: e.target is undefined. Here's a snippet of my setup: import React, { useE ...

Retrieve JSON data from a RESTful API by utilizing pure javascript

I'm eager to try out the Wikipedia search API in JavaScript, even though it might be simpler with jQuery. I want to make sure I understand the basics first before turning to frameworks. Below is the code I've come up with, but for some reason, I ...

Are beta versions included in the "latest" versions of package.json?

Within the package.json file, you have the option to define a package to be synchronized with the most recent version: { ..., "devDependencies": { "gulp": "latest", ... }, ... } When "latest" is specified, does it encompass alpha ...

Are you interested in hosting a node.js/express app on a remote server to allow others to access it?

Apologies if this seems like a novice question or if it's in the wrong place, but I'm attempting to run a basic Hello World app (for testing) on a remote Linux server (red hat 7.6) that I connect to using Putty, with the goal of accessing the pag ...

Is there a way to choose the final JSON element using Javascript or Google Apps Script?

Imagine if I extracted this data from a constantly updating JSON file. [{ "data": { "member": "Feufoe, Robert", "project": "Random Event", }, "folder": null, "id": 1062110, "spam": null }, { "data": { "membe ...

How can data in the form be obtained as an array in Node.js with Express?

I am looking to develop a form that will use a POST request to send data to a node.js server with Express. Is there a way for the form to be transmitted and received as an array on the server? ...

Deleting an HTML column that has a dynamic header name <th> can be achieved by following these steps

I have a script that can add a new column to an HTML table. When the user clicks on add group, the header will change to Group1, Group2, and so on. I am currently adding a function for delete group that can delete all the added columns. The issue now is th ...

Issue with DWR and Android web browser

I recently encountered an issue while trying to access an application through the Android browser. The application uses DWR to maintain connections with connected clients. Everything seems to be working fine, except for the fact that if there is a 2-minut ...

Converting JSON to PNG format using FabricJS

An image has been created and saved as fabricjs-json. Here is the link to the image: https://i.sstatic.net/7Wrhd.png Below is the json representation of the image: { "version": "5.2.1", "objects": [ { ...

When you click on a single checkbox, it automatically selects all of them

Struggling with a form that uses HTML PDO and AngularJS for validation. When clicking one checkbox, all other checkboxes get checked as well. Here is my form: <input type="checkbox" name="declaration" id="declaration" ng-m ...

What is the best way to verify an email address in Vue.js?

Issue with email validation using regex in Vue.js <div class="input-wrapper"> <div class="email-icon"></div> <input type="email" v-model.trim="$v.email.$model" v-validate="'required'" :class="{ 'is-invalid': v ...