Example of Read
Let's write the endpoint that query user balance data from the database and response to the user.
- This the schema of
sample
database 👇🏻
1. Let's create a first endpoint query balance from the database by create getBalance.js
in controller->transaction directory
then use the code below.
- In the path
/balance
, it will query from balance of theusers
table. - We will use the
.query()
method to insert your SQL query. - The second argument to the
.query()
method is a callback function(err, rows)
, which will be called when the MySQL send the response. The callback function takes two arguments,err
androws
, which represent theerror
of the database androws
objects for response data from MySQL database. If
we found an error, we will response the error message to the client.else
, we will returnrow
which is data from theusers
table from the database. 👇🏻
const connection = require("../../services/database");
const getBalance = async (req, res) => {
// Assign the params as a variable
const userId = req.query.userId;
// Regex to check the userId is a number only or not
const checkUserId = new RegExp(/^\d+$/).test(userId); // Boolean
// Check if the userId is not exist or is not a number, return json with an error
if (!userId || !checkUserId) {
return res.json({
success: false,
data: null,
error: "user_id is invalid",
});
}
// Query the data from the database
try {
// Get user balance data
const userBalanceQuery = await connection
.promise()
.query(`SELECT balance FROM users WHERE id = ${userId}`);
const userBalance = userBalanceQuery[0][0];
// Check if user data is empty
if (!userBalance) {
return res.status(404).json({
success: false,
data: null,
error: "User not found",
});
}
// Return data to the client if success
return res.json({
success: true,
data: userBalance,
error: null,
});
} catch (error) {
console.error("Error:", error);
return res.status(500).json({
success: false,
data: null,
error: "Internal server error",
});
}
};
module.exports = getBalance;
2. Create transaction.js
under routers
and create router for transaction
const express = require("express");
const getBalance = require("../controllers/transactions/getBalance");
const transactionsRouter = express.Router();
transactionsRouter.get("/balance", getBalance);
module.exports = transactionsRouter;
3. Import transactionsRouter
into index.js
and make a path
const express = require("express");
const app = express();
// Add
const transactionsRouter = require("./routers/transactions");
const port = 5000;
app.use(express.json());
// Add
app.use("/transactions", transactionsRouter);
app.listen(port, () => {
console.log(`Example app listening on port ${port}`);
});
4. Let's run your application again, and use postman with localhost:5000/transactions/balance?userId=1
- You will see the result like this.
Another example of Read
1. Create getAll.js
under directory controller->users
2. Create an endpoint query all users from the database using the code below in getAll.js
const connection = require("../../services/database");
const getAll = async (req, res) => {
// Query the data from the database
try {
// Get user data
const userDataQuery = await connection
.promise()
.query(`SELECT * FROM users`);
const userData = userDataQuery[0];
// Check if user data is empty
if (!userData) {
return res.status(404).json({
success: false,
data: null,
error: "There is no user data in the database",
});
}
// Return data to the client if success
return res.json({
success: true,
data: userData,
error: null,
});
} catch (error) {
console.error("Error:", error);
return res.status(500).json({
success: false,
data: null,
error: "Internal server error",
});
}
};
module.exports = getAll;
3. Create users.js
under directory routers
and write
const express = require("express");
const getAll = require("../controllers/users/getAll");
const usersRouter = express.Router();
usersRouter.get("/all", getAll);
module.exports = usersRouter;
4. Import usersRouter
into index.js
and make a path
const express = require("express");
const app = express();
const usersRouter = require("./routers/users");
const transactionsRouter = require("./routers/transactions");
const port = 5000;
app.use(express.json());
app.use("/users", usersRouter);
app.use("/transactions", transactionsRouter);
app.listen(port, () => {
console.log(`Example app listening on port ${port}`);
});
5. Let's run your application again, and use postman with localhost:5000/users/all
- You will see the result like this.