The index route will retrieve all of the contacts from the database and send them back to the client in a JSON object. We can use the mongoose .find() method to retrieve all of the entries of a model from the database.
Insert the following code into the ContactController.js file:
// ./controllers/ContactController.js
const Contact = require('../models/Contact');
module.exports = {
async index(ctx) {
const contacts = await Contact.find();
ctx.body = {
status: 'success',
data: contacts
};
}
};
Next, we head over to the ./middleware/router.js file, in order to add the corresponding route, as follows:
// ./middleware/router.js
// ...
const contactController = require('../controllers/ContactController');
router
.get('/', async ctx => (ctx.body = 'Welcome to the contacts API!'))
.get('/contact', contactController.index);
//...
Calling the GET /contact endpoint should send a JSON object with a success status and an empty array as the data property. The data property, which is meant to hold a list of contacts, is empty, as we have not yet inserted any records into the database. An example response object can be seen as follows:
{
"status": "success",
"data": []
}