Let's assume I have the following routes:
POST /users
where all fields are required and this adds a user to my DB, let's say this one gets an id
of 1
{
"firstName": "FirstName",
"lastName": "LastName",
"email": "email@example.com",
"address": "address"
}
I also have route GET /users
which shows all users from the DB.
[
{
"id": 1,
"firstName": "FirstName",
"lastName": "LastName",
"email": "email@example.com",
"address": "address"
}
]
Now, I am trying to have a route for updating a specific user, PATCH /users
.
I want to make all the fields optional and send only the fields I update through the PATCH route and the id
will be decoded from the JWT token.
It's important to note that the data is shown in a form on the front-end and I want to update the form but only send values which have been updated from the form rather than the whole form. The actual form has over 30 fields.
I know if I use a PUT
request, I can send all the values from the form and execute the following:
editUser = async ({ firstName, lastName, email, address }) => {
let sql = `UPDATE users
SET firstName = ?, lastName = ?, email=?, address=? WHERE id = ?`;
const result = await query(sql, [firstName, lastName, email, address, userId ]);
return result;
}
Now, let's say I update only the email in the form and send it. For example:
PATCH /users
{
"email":"email@gmail.com"
}
That's also easy enough with the following:
editUser = async ({ email }) => {
let sql = `UPDATE users
SET email = ? WHERE id = ?`;
const result = await query(sql, [email, userId]);
return result;
}
The above would be a good way to PATCH
the email only.
So now when I do GET /users
I get the following:
[
{
"id": 1,
"firstName": "FirstName",
"lastName": "LastName",
"email": "email@gmail.com",
"address": "address"
}
]
But how do I handle different cases where I don't know which keys are being sent to the back-end? For example, one set can be as follows:
PATCH /users
{
"lastName": "updatedLastName"
"email":"email@gmail.com"
}
The above can be any combination of all the different keys in the object in practice. What would be a good way to do generate custom queries depending on the keys and update the rows in my table with only the column which need to be updated?