Confirm that the attributes of a JSON object align with an Enum

Having a Lambda function that receives a JSON object from the Frontend over HTTPS, I need to perform validation on this object

The expected structure of the body should be as follows (Notifications):

interface Notifications {
  type: NotificationType;
  frequency: FrequencyType;
}

enum NotificationType {
  SMS = 'SMS',
  EMAIL = 'EMAIL'
}

enum FrequencyType {
  INSTANT = 'INSTANT',
  DAILY = 'DAILY',
  WEEKLY = 'WEEKLY',
  NEVER = 'NEVER'
}

Previous attempts using code from another stack post have not been successful

if (body && body.frequency in FrequencyType && body.type in NotificationType) {
//do stuff
}

Is there a more efficient way to ensure that the Frontend never sends an invalid notification type? Although typings are used on the Frontend, I am looking to implement validation on the backend as well

The TypeScript to JavaScript conversion for the enums looks like this:

var NotificationType;

(function(NotificationType2) {

  NotificationType2["SMS"] = "SMS";

  NotificationType2["EMAIL"] = "EMAIL";

})(NotificationType || (NotificationType = {}));

var FrequencyType;

(function(FrequencyType2) {

  FrequencyType2["INSTANT"] = "INSTANT";

  FrequencyType2["DAILY"] = "DAILY";

  FrequencyType2["WEEKLY"] = "WEEKLY";

  FrequencyType2["NEVER"] = "NEVER";

})(FrequencyType || (FrequencyType = {}));

Answer №1

Understanding TypeScript Code

enum NotificationType {
  SMS = 'SMS',
  EMAIL = 'EMAIL'
}

enum FrequencyType {
  INSTANT = 'INSTANT',
  DAILY = 'DAILY',
  WEEKLY = 'WEEKLY',
  NEVER = 'NEVER'
}

type BodyType =  {
    frequency: NotificationType;
    type: NotificationType
}

const validate = (body:BodyType):boolean => !!body && body.frequency in FrequencyType && body.type in NotificationType; 

Once TS code is compiled, the validation should work correctly

validate({ frequency: 'INSTANT', type: 'SMS' }); // true
validate({}); // false
validate({ frequency: 'INSTANTS', type: 'SMS' }); // false

Consider adding an OR condition for further validation.

!!body && (body.frequency in FrequencyType || body.type in NotificationType)

Answer №2

During the troubleshooting process, it was discovered that the frontend provided keys for the JSON object in an incorrect case. Additionally, the SQL PUT command within the //doStuff code failed to work for a certain user due to their absence from the database. This required some adjustments to be made in order to resolve the issue.

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

Having Trouble Sending Text to InputBox Using Selenium WebDriver

Greetings everyone Can someone guide me on how to use Selenium to input a Login and Password in an Alert Dialog Box? Upon loading the webpage, the alert is already displayed: https://i.stack.imgur.com/F1O5S.png I have attempted the following code: Str ...

Combining Multiple .ts Files into a Single File: A Simplified Application Structure with TypeScript 1.8

Currently, I am in the process of developing an Electron application and I have decided to implement TypeScript for this project. While TypeScript essentially boils down to JavaScript in the end, my familiarity with it makes the transition seamless. As of ...

Execute a database query to search for patterns using Regular Expressions within the

As I embark on a new project, I find myself questioning my approach before diving in too deep and realizing it may not be the most efficient path. Within the realm of a large company where we develop unofficial tools for internal use, I am faced with limi ...

Incorporating HTML code within a .ts file: a basic guide

I'm relatively new to Angular, but I've been given a project that's built with Angular. As I examine the .ts file containing the list of property types, I need to wrap a span around the label text. Is this doable? Here is the current list ...

After clicking, I would like the text from the list item to have a style of "background-color: aqua" when displayed in the textarea

Is there a way to apply a highlight with a style of "background-color: aqua" in the textarea only to the word selected from the list above after clicking on it? See below for my HTML: <head> <script src="https://ajax.googleapis.com/ajax/libs/ ...

Issue with AngularJS: The select dropdown fails to update the selected option when the bound scope variable changes

I am facing an issue with a select control in my Angular app. The options for the select are generated dynamically from an array of objects in the scope. When I try to pre-select a specific option on app init by changing a bound variable on the scope, it d ...

What is the best approach to reverse the selection of <li> elements by utilizing :not() and :contains

I am looking to implement a live search feature using jQuery. Below is the code snippet I have written: $("#searchInput").on("keyup", function () { var searchTerm = $("#searchInput").val(); $('li:contains("' + searchTerm + ' ...

What happens in mongoose if one of several consecutive queries fails?

Currently, as I work on my API, I am utilizing two Models: SongModel and UserModel. Whenever a new song is saved, I also execute a query to link the song._id to the user who created it. Unfortunately, a mistake in my code caused the second query to throw a ...

Dynamically taking input in Vue JS while using v-for loop

Hey there! I'm trying to get input in this specific manner: itemPrices: [{regionId: "A", price: "200"},{regionId: "B", price: "100"}] Whenever the user clicks on the add button, new input fields should be added ...

Utilize a function to send an AJAX email

In my JavaScript function, I have been attempting to send an email from a contact form. The validation checks are working correctly, but when the code reaches the point of sending the form, it gets stuck and doesn't receive any response from $.ajax. I ...

Find and delete an item from a JSON array

Currently, I am attempting to locate a specific object within a JSON array and remove it. The structure of my JSON array containing objects is as follows: var data = [{ {id: "1", name: "Snatch", type: "crime"}, {id: "2", name: "Witches of Eastwic ...

Adding the classname "active" in ReactJS can be achieved by utilizing the `className` attribute within

I am facing an issue with adding the active classname in my code. Can anyone suggest a solution to add the active classname for this section: <li onClick = {() => onChangeStatus({status: 'on-hold'})} className = {appState === {'status& ...

Difficulty encountered with Mongoose/MongoDb FindOneAndUpdate functionality

My goal is to update a specific location only if it has a status of 0 or 2, but not if the status is 1. There is only one instance of this location in my database. Property.findOneAndUpdate({ status: 0, location: req.body.update.location }, req.body.updat ...

Is there a way to visualize the prototype chain of a JavaScript object?

Consider the following code snippet: function a() {} function b() {} b.prototype = new a(); var b1 = new b(); It can be observed that a has been incorporated into the prototype chain of b. This demonstrates that: b1 is an instance of b b1 is an instance ...

Stop Bootstrap 5 Accordion from collapsing

I have successfully implemented the Accordion component in Bootstrap 5, and it is working perfectly! However, I am facing an issue with the size of the collapse button in the accordion, which is too big. I want to add an additional link to it for some ext ...

Error in Typescript TS2322: Observable Type 'boolean | {}' - Using Angular 5 and Typescript 2.4.2

After upgrading from version 4 to 5, I'm puzzled by the plethora of TypeScript TS2322 errors I'm encountering. The migration involved setting up a new Angular project with the Angular CLI. Angular CLI: 1.5.5 Node: 8.9.1 OS: darwin x64 Angular: 5 ...

Update the appearance of a cell if the value within it is equal to zero

I have discovered a way to achieve this using inputs. input[value="0"] { background-color:#F7ECEC; color:#f00;} Now, I am looking for assistance in applying the same concept to table cells. Can anyone provide guidance? Thank you. ...

The magnitude of each new keystroke is squared compared to its predecessor

exploring the relationship between keyboard and console inputs Each subsequent e.key entry is occurring twice as frequently as the previous one. Once it reaches 8-9 characters, the rendering frequency skyrockets to over 1000 times per character. Here&apos ...

Unable to locate the name 'X' despite importing the name directly above

I'm a little confused about the situation at hand. The name is clearly mentioned right above. https://i.sstatic.net/D0CEV.png Displayed below is the content of storage-backend.interface.ts: export declare interface StorageBackend extends Storage { ...

Creating a dynamic hyperlink variable that updates based on user input

I am attempting to create a dynamic mailto: link that changes based on user input from a text field and button click. I have successfully achieved this without using the href attribute, but I am encountering issues when trying to set it with the href attr ...