Skip to content
Snippets Groups Projects
Commit 1d963772 authored by Oshani Weerakoon's avatar Oshani Weerakoon
Browse files

Example 11 + Instructions

parent ddf12844
Branches
No related tags found
No related merge requests found
In order to test the server-to-server data transfer and the database query optimization, you need to have a MySQL database set up with some data in it. Here's a step-by-step guide on how you could set up a simple MySQL database for testing:
1. **Install MySQL**: If you don't have MySQL installed, you'll need to install it. You can download it from the [official MySQL website](https://dev.mysql.com/downloads/) or use a package manager for your operating system.
2. **Set Up the Database**:
- Log in to the MySQL server using a command-line client or a GUI tool like MySQL Workbench.
- Create a new database:
```sql
CREATE DATABASE my_project_db;
```
- Select the database:
```sql
USE my_project_db;
```
- Create a `users` table:
```sql
CREATE TABLE users (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(255) NOT NULL,
address VARCHAR(255) NOT NULL,
email VARCHAR(255),
phone VARCHAR(255),
-- Add any other columns you might want
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
```
- Insert some sample data into the `users` table:
```sql
INSERT INTO users (name, address, email, phone) VALUES
('Alice', '123 Main St', 'alice@example.com', '555-1234'),
('Bob', '456 Maple Ave', 'bob@example.com', '555-5678'),
('Charlie', '789 Oak St', 'charlie@example.com', '555-9012');
```
3. **Configure Your Node.js Application**:
- Update the MySQL connection pool configuration in your `server.js` file with the correct database credentials and the name of the database you just created (`my_project_db`).
4. **Run Your Node.js Server**:
- Execute `node server.js` to start your server.
5. **Test the Endpoint**:
- Use a web browser, `curl`, or a tool like Postman to make a request to `http://localhost:3000/user/1`.
- You should receive a JSON response with the name and address of the user with ID 1.
This setup will allow you to test the optimized database query and ensure that your application server is only fetching the necessary data from the MySQL database, thus minimizing server-to-server data transfer.
\ No newline at end of file
For this example, let's assume we have a Node.js application server that communicates with a MySQL database.
**Backend Setup:**
1. **Install Node.js**: If you haven't already, install Node.js from [nodejs.org](https://nodejs.org/).
2. **Set up your project directory**:
```bash
mkdir my_project
cd my_project
npm init -y
```
3. **Install necessary packages** (Express for the server and a MySQL client for database interaction):
```bash
npm install express mysql2
```
4. **Create a file named `server.js`** and add the following code:
```javascript
const express = require('express');
const mysql = require('mysql2');
const app = express();
const port = 3000;
// Create a MySQL connection pool (adjust credentials as needed)
const pool = mysql.createPool({
host: 'your_database_host',
user: 'your_database_user',
password: 'your_database_password',
database: 'your_database_name',
waitForConnections: true,
connectionLimit: 10,
queueLimit: 0
});
// Endpoint to get user's name and address by ID
app.get('/user/:id', (req, res) => {
const userId = req.params.id;
// Optimized query to fetch only the necessary columns
pool.query('SELECT name, address FROM users WHERE id = ?', [userId], (error, results) => {
if (error) {
res.status(500).send('Error fetching user data');
return;
}
res.json(results[0]);
});
});
app.listen(port, () => {
console.log(`Server running on port ${port}`);
});
```
Replace `'your_database_host'`, `'your_database_user'`, `'your_database_password'`, and `'your_database_name'` with your actual MySQL database credentials.
**Testing the Setup:**
1. **Run the server**:
```bash
node server.js
```
2. **Test the endpoint**:
You can test the endpoint using a tool like `curl` or Postman, or simply by visiting `http://localhost:3000/user/1` in your web browser (assuming there is a user with ID 1).
With `curl`, the command would look like this:
```bash
curl http://localhost:3000/user/1
```
You should receive a JSON response with only the name and address of the user, demonstrating that the server is only transferring the necessary data from the database.
\ No newline at end of file
{
"name": "ex11",
"version": "1.0.0",
"description": "",
"main": "server.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "node server.js"
},
"keywords": [],
"author": "",
"license": "ISC"
}
const express = require('express');
const mysql = require('mysql2');
const app = express();
const port = 3000;
// Create a MySQL connection pool (adjust credentials as needed)
const pool = mysql.createPool({
host: 'your_database_host',
user: 'your_database_user',
password: 'your_database_password',
database: 'your_database_name',
waitForConnections: true,
connectionLimit: 10,
queueLimit: 0
});
// Endpoint to get user's name and address by ID
app.get('/user/:id', (req, res) => {
const userId = req.params.id;
// Optimized query to fetch only the necessary columns
pool.query('SELECT name, address FROM users WHERE id = ?', [userId], (error, results) => {
if (error) {
res.status(500).send('Error fetching user data');
return;
}
res.json(results[0]);
});
});
app.listen(port, () => {
console.log(`Server running on port ${port}`);
});
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment