Creating a simple Node.js app
Course: SQL databases - chapter 9
- Initialise an empty typescript project
npm init -ynpx tsc --init- Change the
rootDirandoutDirintsconfig.json
"rootDir": "./src","outDir": "./dist",- Install the
pglibrary and it’s types (because we’re using TS)
npm install pgnpm install @types/pg- Create a simple Node.js app that lets you put data
Create a function that let’s you insert data into a table. Make it
async, make sureclient.connectresolves before u do the insert
Answer
import { Client } from 'pg';
// Async function to insert data into a tableasync function insertData() { const client = new Client({ host: 'localhost', port: 5432, database: 'postgres', user: 'postgres', password: 'mysecretpassword', });
try { await client.connect(); // Ensure client connection is established const insertQuery = "INSERT INTO users (username, email, password) VALUES ('username2', 'user3@example.com', 'user_password');"; const res = await client.query(insertQuery); console.log('Insertion success:', res); // Output insertion result } catch (err) { console.error('Error during the insertion:', err); } finally { await client.end(); // Close the client connection }}
insertData();💡 This is an
insecureway to store data in your tables. When you expose this functionality eventually viaHTTP, someone can do anSQL INJECTIONto get access to your data/delete your data.
- More secure way to store data.
Update the code so you don’t put
user provided fieldsin theSQL string
What are user provided strings?
In your final app, this insert statement will be done when a user signs up on your app. Email, username, password are all user provided strings
What is the `SQL string` ?
const insertQuery = "INSERT INTO users (username, email, password) VALUES ('username2', 'user3@example.com', 'user_password');";Hint
const insertQuery = 'INSERT INTO example_table(column1, column2) VALUES($1, $2)';const res = await client.query(insertQuery, [column1Value, column2Value]);Solution
import { Client } from 'pg';
// Async function to insert data into a tableasync function insertData(username: string, email: string, password: string) { const client = new Client({ host: 'localhost', port: 5432, database: 'postgres', user: 'postgres', password: 'mysecretpassword', });
try { await client.connect(); // Ensure client connection is established // Use parameterized query to prevent SQL injection const insertQuery = "INSERT INTO users (username, email, password) VALUES ($1, $2, $3)"; const values = [username, email, password]; const res = await client.query(insertQuery, values); console.log('Insertion success:', res); // Output insertion result } catch (err) { console.error('Error during the insertion:', err); } finally { await client.end(); // Close the client connection }}
// Example usageinsertData('username5', 'user5@example.com', 'user_password').catch(console.error);- Query data
Write a function
getUserthat lets you fetch data from the database given aemailas input.
$1b