To implement an API endpoint for retrieving tasks for a specific user, we will use an Express.js framework along with a MongoDB database for data storage. Below is the complete server setup and the necessary API implementation, complete with error handling and input validation.
Dependencies:
const express = require('express');
const mongoose = require('mongoose');
const bodyParser = require('body-parser');
const { check, validationResult } = require('express-validator');
Server Setup Code:
// Importing dependencies
const express = require('express');
const mongoose = require('mongoose');
const bodyParser = require('body-parser');
const { check, validationResult } = require('express-validator');
// Initialize the app
const app = express();
const PORT = process.env.PORT || 3000;
// Middleware
app.use(bodyParser.json());
// MongoDB connection
mongoose.connect('mongodb://localhost:27017/todoapp', { useNewUrlParser: true, useUnifiedTopology: true })
.then(() => console.log('MongoDB connected'))
.catch(err => console.log(err));
// Task schema
const TaskSchema = new mongoose.Schema({
userId: String,
title: String,
completed: Boolean
});
const Task = mongoose.model('Task', TaskSchema);
// API endpoint to retrieve tasks for a specific user
app.get('/tasks/:userId', [
// Validate the userId parameter
check('userId').isString().notEmpty().withMessage('userId must be a valid non-empty string')
], async (req, res) => {
// Handle validation errors
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(400).json({ success: false, errors: errors.array() });
}
const userId = req.params.userId;
try {
// Fetch tasks for the specified userId from the database
const tasks = await Task.find({ userId: userId });
// Check if tasks were found
if (tasks.length === 0) {
return res.status(404).json({ success: false, message: 'No tasks found for this user.' });
}
// Return the tasks in the response
return res.status(200).json({ success: true, tasks: tasks });
} catch (error) {
// Handle unexpected errors
return res.status(500).json({ success: false, message: 'Server error', error: error.message });
}
});
// Start the server
app.listen(PORT, () => {
console.log(`Server is running on http://localhost:${PORT}`);
});
Code Explanation:
- Dependencies: We import necessary libraries like Express for routing, Mongoose for database interactions, and express-validator for input validation.
- Server Setup: We initialize the Express application and set up middleware for JSON parsing.
- Database Connection: We connect to a MongoDB database named "todoapp".
- Task Schema: We define a Mongoose schema for the "Task" which includes
userId, title, and completed.
- API Endpoint (
/tasks/:userId):
- We validate the
userId to ensure it is a non-empty string.
- We fetch tasks from the database for the provided
userId.
- We handle cases where no tasks are found and return appropriate messages.
- If an error occurs while fetching tasks, we return a 500 server error.
This code provides a complete setup for the task retrieval endpoint, following the specifications provided.