I am building a very simple REST platform using Node.JS and PostgreSQL, using pg-promise to access the database. My goal is to create an incredibly simple ticketing system with users and tickets. At this point I simply want to be able to query the server for a list of all tickets.
My database consists of two tables in the following format:
CREATE TABLE people (
ID SERIAL PRIMARY KEY,
NAME VARCHAR(128)
);
CREATE TABLE tickets (
ID SERIAL PRIMARY KEY,
SUBMITTED_BY int4 REFERENCES people(ID),
TITLE VARCHAR(128)
As you can see there is a single foreign key pointing tickets to persons. I have populated my database with the following data:
coop=> SELECT * FROM people;
id | name
----+----------
1 | John Doe
(1 row)
coop=> SELECT * FROM tickets;
id | submitted_by | title
----+--------------+------------------
1 | 1 | My first ticket!
(1 row)
And I use pg-promise with the following query function to render a JSON response:
// GET ALL query function
function getAllTickets(req, res, next) {
db.any('select * from tickets left join people on tickets.submitted_by = people.id;')
.then(function (data) {
res.status(200)
.json({
status: 'success',
data: data,
message: 'Retrieved ALL tickets'
});
})
.catch(function (err) {
return next(err);
});
}
The function works, I can retrieve JSON output in the following format:
:: GET /api/tickets
{"status":"success","data":[{"id":1,"submitted_by":1,"title":"My first ticket!","name":"John Doe"}],"message":"Retrieved ALL tickets"}
However this is not the format I want. I want to encapsulate the 'persons' object within the 'tickets' object, replacing the foreign key as follows:
{"status":"success","data":[{"id":1,submitted_by: {"id": 1, "name":"John Doe"},"title":"My first ticket!"}],"message":"Retrieved ALL tickets"}
The reason I want to do this so so I can easily consume this API from an Angular2 service and translate both ticket and person into object in my component. However I have absolutely no idea how to go about doing this and the pg-promise documentation has not been helpful.
I have been web-programming with Django for the past year but since I switched to Node.JS I feel like a complete novice. Could somebody offer me a hand or point me in the right direction?