I am trying to create CRUD for user in my web App. I am using uuid for my id (also the primary key as shown in the user table below).
I am using the pg-promise library to connect to Postgres. The Route code to create users and get all users are working.
But I am having challenge on how to reference the uuid when creating the id const for getting one user, deleting user or updating user i.e
const user_id = parseInt(req.params.id);
Please see my sample codes below. I will also appreciate any online resource with example.
MY USER TABLE
CREATE TABLE m_user (
id uuid DEFAULT uuid_generate_v4() NOT NULL,
username text NOT NULL UNIQUE,
password text NOT NULL,
confirm_password text NOT NULL,
created_at timestamp NOT NULL default now(),
last_login timestamp NOT NULL default now(),
PRIMARY KEY (id)
);
CRUD TO GET ONE USER
function getSingleUser(req, res, next) {
const showoneuserquery = 'SELECT * FROM user where id = $1'
const user_id = parseInt(req.params.id);
db.one(showoneuserquery, user_id)
.then(function (data) {
res.status(200)
.json({
status: 'success',
data: data,
message: 'Retrieved ONE user'
});
})
.catch(function (err) {
return next(err);
});
}
CRUD TO EDIT USER
function editUser(req, res, next) {
const edituserquery = 'update user set username=$1, password=$2, confirm_password=$3 where id=$4'
db.none(edituserquery, [req.body.username, req.body.password, req.body.confirm_password, (req.params.id)])
.then(function () {
res.status(200)
.json({
status: 'success',
message: 'Updated user'
});
})
.catch(function (err) {
return next(err);
});
}