Within my Express API functionality, I aim to offer the client flexibility in providing their contact details, namely phone number or website address, with the option of leaving them blank.
The SELECT queries in use are as follows:
-- Retrieve all users
SELECT * FROM users
ORDER BY user_id ASC;
-- Retrieve a specific user
SELECT * FROM users
WHERE user_id = $1;
When it comes to INSERT statement execution, any unspecified value defaults to NULL
:
INSERT INTO users (name, username, email, phone, website)
VALUES ($1, $2, $3, $4, $5) RETURNING *;
The POST request's callback function is structured as follows:
const createUser = async (req, res, next) => {
const { name, username, email, phone, website } = req.body;
try {
const create = await db.query(insertUser, [
name,
username,
email,
phone,
website,
]);
res
.status(201)
.json({ message: "User Created Successfully!", user: create.rows[0] });
} catch (err) {
// Handling UNIQUE constraint violation
if (err.code == "23505") {
uniqueConstraintError(err, next);
} else {
serverError(err, next);
}
}
};
The insertUser
variable stores the PostgreSQL statement.
In cases where the user data is added without specifying phone and website fields, the GET requests still display these as NULL
:
{
"user_id": 10,
"name": "Bruce Wayne",
"username": "Batman",
"email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="b3d1d2c7f3d0d2c5d69dd0dcde">[email protected]</a>",
"phone": null,
"website": null
}
Is there a method to conceal these NULL
values in the SELECT statements and obtain output similar to this?
{
"user_id": 10,
"name": "Bruce Wayne",
"username": "Batman",
"email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="1c7e7d685c7f7d6a79327f737f7775">[email protected]</a>"
}