Building a Web Service in Node is similar to other routes we’ve built so far this semester.
Example GET to return all records in a table
router.get('/people', async (req, res) => {
let query = 'SELECT * FROM PEOPLE';
db.all(query, [], (err, data) => {
if (err) {
throw err;
}
res.json(data);
});
});
Instead of rendering a view we are returning the data as json.
router.post('/people', async (req, res) => {
const firstName = req.body.first_name;
const lastName = req.body.last_name;
const uniqueID = req.body.uniqueId;
db.all(
'INSERT INTO PEOPLE (first_name, last_name, uniqueID) VALUES (?, ?, ?) returning * ',
[firstName, lastName, uniqueID],
(err, data) => {
res.status(201);
res.json(data[0]);
}
);
});
Because this created a new record we are returning the created record with a status code of 201, to signify that we created a new record.
res.status(201);
If we wanted to return something other than just the data from a query in our response we can do something like the following
let responseData = {};
responseData.data = queryData;
responseData.count = queryData.length();
This would create a response that contains additional data and would look like
{
data: [
{
id: 1,
name: Swoop
}
],
count: 1
}