Can a NestJS API be built using only ExpressJS and MySQL, without relying on TypeORM?

My current project involves creating an API in nestJS using only plain expressJS and mysql, without relying on typeorm. Unfortunately, I've found very limited information in the documentation or other sources to guide me through this process.

Here's what I've completed so far:

  1. Established a global variable to store the connection obtained from mysql.createConnection().
  2. Attempted to utilize this connection to retrieve data from the database:
async findAll() {
    return await connection.query('SELECT * from test', (error, results, fields) => {
        console.log(results);
        return results;
    });
}

The console displays the following data:

[ RowDataPacket {
    id: 1,
    firstName: 'test',
    middleName: '1',
    lastName: 'user' },
  RowDataPacket {
    id: 2,
    firstName: 'test',
    middleName: '2',
    lastName: 'user' }
]

However, it's also generating the error:

TypeError: Converting circular structure to JSON 
at JSON.stringify (<anonymous>)

EDIT:

To resolve this issue, I attempted a solution recommended by @Kim Kern:

return await connection.query('SELECT * from users', (error, results, fields) => {
    results = results.map((result) => {
        return Object.assign({}, result);
    });
    console.log(results);
    return results;
});

Although the updated results no longer display RowDataPacket, the same error persists.

Answer №1

Finally, after spending hours digging through the code, I have discovered the problem. The issue lies within the callback function not returning the expected Promise but instead returning an unparsable JSON.

To resolve this issue, here is what you need to do:

async getAll(){
 const res = await this.execExec(connection)
 return res;
}

execExec(connection){
 return new Promise((res, rej) => {
    connection.query('SELECT * from users', function (error,results,fields) {
      if (error) throw error;
      results = results.map((result) => {
         return Object.assign({}, result);
    });
      console.log(results);
      res(results);
    });
  });
}

Answer №2

const mysql = require('mysql2');
export class TestData {
async getAllData(): Promise<any> {
        let connection = mysql.createPool({
            host: 'localhost',
            user: 'root',
            password: 'root',
            database: 'testDB'
        });
        return new Promise((resolve, reject) => {
            connection.execute("select * from test", (error, results) => {
                if (error) throw error;
                //  console.log(results);
                resolve(results);
            });
        })
    }
}

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

Guide to creating multi-line routes for routing

At times, the routing path becomes too long for easy reading, so I would like to display it in multiple lines for better visibility. I understand that a multi-line string is typically formatted like so: var str = 'hello \ world &bsol ...

Using TypeScript, apply an event to every element within an array of elements through iteration

I have written the code snippet below, however I am encountering an issue where every element alerts the index of the last iteration. For instance, if there are 24 items in the elements array, each element will alert "Changed row 23" on change. I underst ...

Learn the proper way to specify the return type of a function as a class, rather than an instance, in Typescript

Is there a way to declare that a function returns a generic class definition? I have tried the following for non-generic classes, but it does not work for generic ones: export function composeAll(composeFunction: Function, depsFunction: Function): (compon ...

Exploring the power of PassportJS and Stripe integration

Currently, my code successfully charges users when they create an account. However, I am facing an issue where user accounts are created even if their credit card payment fails. I need to modify the code to prevent account creation if the credit card is de ...

Adjusting the IntelliSense Functionality in Monaco Editor

Currently, I am testing out the CompletionItemProvider feature for my project. I have implemented two separate CompletionItemProviders. One is set to trigger when any alphabet letter is typed and the other triggers when the user enters a single quote chara ...

Implement socket.io within expressjs routes instead of the bin/www file

Currently, I am utilizing socket.io within my expressJS application. I have established a socket connection in the bin/www file. My goal is to send data to the client side using socket.emit() in the sendmessage.js file when data is sent to it. bin/www ...

How can I automatically redirect to a different route in Express after sending a JSON response?

After a user successfully registers on my form, I want to display a success message and then redirect them to another route. The following code snippet is part of my post request to /register: newUser.save() .then((user: any) => { res.json({ ...

Tips for showing nested JSON data in a PrimeNG table within Angular version 7

I am struggling to display nested json data in a PrimeNG table. When I retrieve the data using an HTTP service, it appears as [object][object] when displayed directly in the table. What I want is to show the nested json data with keys and values separated ...

Identifying unique properties with specific keys in a Typescript object

Can a specific type be used with one property when using the key in of type? Playground. type ManyProps = 'name' | 'age' | 'height' type MyObj = {[key in ManyProps]: number, name?: string} ...

What are some ways to expand the width of a MaterialUI form control if no value has been chosen?

I am currently working on a project where I need a dropdown menu component with specific selections. However, the layout appears to be cramped and I'm struggling to adjust the width. Additionally, I've been unsuccessful in changing the font size ...

The type 'string' cannot be utilized to index type

Apologies for adding yet another question of this nature, but despite finding similar ones, I am unable to apply their solutions to my specific case. Could someone please assist me in resolving this TypeScript error? The element implicitly has an 'an ...

Utilizing a JSDoc comment from an external interface attribute

Currently, I am in the process of developing a React application. It is common to want the props of a child component to be directly connected to the state of a parent component. To achieve this, I have detailed the following instructions in the interface ...

ResizableBox is failing to render any content

My current project involves trying out react-resizable. Unfortunately, my basic example only shows the text XYZ in the browser without displaying any resizable box as expected. There are no error messages either. import { ResizableBox } from 'react-re ...

Typescript turns a blind eye to improper usage of a passed prop function within React components

My React component is structured like this: const BirthdaySearch: FC<{ onSearch: (year: string, month: string) => void }> = (props) => { const monthInputRef = useRef<HTMLInputElement>(null); const dayInputRef = useRef<HTMLInp ...

Guide on importing SVG files dynamically from a web service and displaying them directly inline

With an extensive collection of SVG files on hand, my goal is to render them inline. Utilizing create-react-app, which comes equipped with @svgr/webpack, I am able to seamlessly add SVG inline as shown below: import { ReactComponent as SvgImage } from &apo ...

Unable to retrieve an item from an array while simultaneously retrieving a value from its nested array

In the document provided below- { "_id": { "$oid": "61fb6bf71be79c03227d6bbf" }, "id": "17202155", "completed": ["cse331", "cse312"], "incompleted": ...

Guide to assigning positions in an array of a particular component with its selector utilizing Angular:

I am a beginner when it comes to Angular and I have a question regarding setting positions of an array that is initially declared as empty in one component, using its selector in another component. Let's take for example a component named "array" whe ...

declaration of function interface and property that cannot be modified

After reviewing some new TypeScript code, I encountered a part that left me puzzled. interface test { (a: number): number; readonly b: number; } While I understand that (a:number): number signifies a function where the argument is a:number and the ret ...

Navigating the NextJS App Directory: Tips for Sending Middleware Data to a page.tsx File

These are the repositories linked to this question. Client - https://github.com/Phillip-England/plank-steady Server - https://github.com/Phillip-England/squid-tank Firstly, thank you for taking the time. Your help is much appreciated. Here's what I ...

Issue with Multer s3 upload: File not functioning properly in s3 and size increase of file

I successfully uploaded an mp4 file to s3 using node.js and the code seems to be functioning well as I can see the file in s3. However, there seems to be a discrepancy in the file size. The original file is 860kb but after uploading it, it increases to 1.4 ...