Implement the conversion of a response to the JSON response standard within a NestJS application

I encountered an issue with converting the output of my object post saving it in the database. I attempted to adhere to the guidelines laid out by and convert my responses to the Json standard.

The approach I took is not optimal. Here it is:

  async findAll() {
    const data = new DataResponse<Product>();
    return await this.repository.find().then(value => {
      data.data = value;
      data.isError = false;
      data.message = "";
      data.statusCode = 1;

      return data;
    }).catch(e => {
      const error: HttpException = e;
      data.data = [];
      data.isError = true;
      data.message = error.message;
      data.statusCode = error.getStatus();

      return data;
    });
  }

In my json response, it appears as follows:

{
    "data": {
        "id": 1,
        "description": "Oreo",
        "price": "6.5",
        "category": "Oreo",
        "stock": 50,
        "createDate": "2021-10-28T14:11:47.454Z",
        "lastUpdateDate": "2021-10-28T14:11:47.454Z"
    },
    "message": "",
    "statusCode": 1,
    "isError": false
}

Answer №1

Instead of using stringified JSON Objects, consider creating a DTO or initializing an object of the entity like "new Product()" to assign values for saving in the database. This approach can help resolve the issue you are facing.

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

Retrieving JSON data using RestTemplate within a Spring project

My issue lies in attempting to extract values from a JSON response: {"BTC_BCN":{"id":7,"last":"0.00000086","lowestAsk":"0.00000086","highestBid":"0.00000085","percentChange":"0.14666666","baseVolume":"368.86654762","quoteVolume":"498378738.00151879","isFr ...

Utilize the type correctly within a React Higher Order Component

Having some trouble with types while using an HOC. The following is the code snippet for the HOC: export interface IWithLangProps { lang: ILang; } const withLang = <T extends object>(Comp: React.ComponentType<T>): React.ComponentClass ...

In the world of C#, treating null database values as empty in a JSON file is the

I am encountering an issue with converting decimal NULL values from a database to a JSON file. There is a SQL procedure that retrieves the values from the database, and a C# function then converts these values into a JSON file. Currently, when the procedur ...

Easy guide on establishing Relationships using Mongoose

I am new to working with Mongo db/Mongoose, specifically regarding mongoose and relationships between collections. Despite the availability of numerous tutorials on this subject, I am still struggling to find a straightforward way to make it work. I have t ...

What is the best way to convert a date string into a Date object when parsing JSON data?

Is there a way to convert a timestamp into a Date object from JSON? JSON data received from the server looks like this: { "date": "2610-02-16T03:16:15.143Z" } I am attempting to create a Date object from it using the following code: class M ...

Publishing Typescript to NPM without including any JavaScript files

I want to publish my *.ts file on NPM, but it only contains type and interface definitions. There are no exported JavaScript functions or objects. Should I delete the "main": "index.js" entry in package.json and replace it with "main": "dist/types.ts" inst ...

Quick + Vue Router - Lazy Loading Modules

For my personal project, I am using Vite alongside Vue 3 and have integrated vue-router@4 for managing routes. Since all of my modules share the same set of routes, I created a helper function: import { RouteRecordRaw } from 'vue-router' import p ...

What's the deal with TypeScript tsconfig allowing .json imports, but not allowing them in built .js files?

By including the line "resolveJsonModule": true in my project's .tsconfig file, I have successfully implemented direct importing of data from .json files. The project functions properly, even when using nodemon. However, upon building the project and ...

How can I deserialize a flat JSON array and exclude certain tokens during the process?

Upon receiving this response from the server: [{ "sys_id": "******************************", "dv_model_id": "*****************", "due": "YYYY-MM-DD HH:mm:ss", "assigned_to": "1524s32a54dss412s121s", "dv_assigned_to": "username", "assigned_to. ...

Using Mat-Error for Two Way Binding leads to frequent triggering of ngModelChange事件

I am working with a mat input field that has two-way data binding using ngModel, and I want to add validation using mat-error and formControl. <mat-form-field [formGroup]="myForm"> <input matInput formControlName="myFormName" autocomplete="off" ...

Leveraging the HTTP Client in golang to interact with the Places API, parsing JSON data and handling invalid characters

Just started learning Go and decided to test the Google Places API. I am struggling with writing the request as it goes through but I cannot Unmarshall the response. Would really appreciate some guidance on how to print the JSON in string form for decodi ...

The Datepicker in MUI - React is unable to recognize the `renderInput` prop on a DOM element

I've been experimenting with the MUI version 5 DatePicker component. I followed the example provided in the MUI documentation's codesandbox demo. Here is how my component looks: const MonthPicker: FC = () => { const [value, setValue] = Rea ...

Transferring dynamic parameters from a hook to setInterval()

I have a hook that tracks a slider. When the user clicks a button, the initial slider value is passed to my setInterval function to execute start() every second. I want the updated sliderValue to be passed as a parameter to update while setInterval() is r ...

An exploration of effortlessly moving elements using webdriver.io - the power of

I have been attempting to utilize the drag and drop method in WebDriver.io, but I am encountering issues. I followed the example for drag & drop on this website: https://www.w3schools.com/html/html5_draganddrop.asp. This functionality is essential for ...

Implementing Pagination for a JSON Object using Javascript and Jquery

I am looking for the most effective way to implement pagination in my current situation: I am using "$('body').append(htmlText);" to display the items from a JSON object. How can I set up pagination so that each page displays only one item based ...

What factors should be considered when deciding whether to create an entity in Django using Tastypie, based on data from another entity?

In my Event class, I have defined the number of participants and the participant limit. Additionally, there is a Ticket class which represents registration for the Event. I need to ensure that tickets for an event are not created if the event has reached ...

Persistent error caused by unresponsive Tailwind utility functions

Currently, I am working on a Next.js application and encountered a strange error while adjusting the styling. The error message points to a module that seems to be missing... User Import trace for requested module: ./src/app/globals.css GET /portraits 500 ...

The file refuses to download after an AJAX post

When accessing the URL directly from my program that generates a PDF, I am able to initiate a direct download. public void Download(byte[] file) { try { MemoryStream mstream = new MemoryStream(file); long dataLengthToRead = mstre ...

What is the best way to display items using Typeahead.js in combination with the Bloodhound engine?

I am struggling to showcase a collection of items using typeahead with a JSON file as the data source. Unfortunately, none of my information is appearing on the screen. My objective is to list the names and utilize the other attributes for different purpo ...

I am having trouble with CSS, JS, and image files not loading when using Angular 9 loadChildren

I am facing an issue with loading CSS, JS, and images in my Angular 9 project. I have separate 'admin' and 'catalog' folders where I want to load different components. However, the assets are not loading properly in the 'catalog&ap ...