fields filtering in api from express
Certainly! Here's an example of implementing fields filtering in an Express API:
const express = require('express');
const app = express();
const users = [
{ id: 1, name: 'Alice', age: 25, email: '[email protected]' },
{ id: 2, name: 'Bob', age: 30, email: '[email protected]' },
{ id: 3, name: 'Charlie', age: 28, email: '[email protected]' }
];
app.get('/users', (req, res) => {
let filteredUsers = [...users];
if (req.query.fields) {
const fields = req.query.fields.split(',');
filteredUsers = filteredUsers.map(user => {
const filteredUser = {};
fields.forEach(field => {
if (user.hasOwnProperty(field)) {
filteredUser[field] = user[field];
}
});
return filteredUser;
});
}
res.json(filteredUsers);
});
const PORT = 3000;
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});
Explanation:
- Express Setup: Require Express and set up the Express app.
- User Data: A mock array of user data is created with properties like
id
,name
,age
, andemail
. - GET Endpoint: An endpoint
/users
is created for handling GET requests. - Filtering Logic: Checks if the query parameter
fields
exists in the request. If present, it splits the fields by comma and prepares to filter the user data accordingly. - Mapping User Data: If specific fields are requested (
fields
parameter exists), it iterates through each user and constructs a new object (filteredUser
) containing only the requested fields. - Response: Returns the filtered user data as JSON response using
res.json(filteredUsers)
. - Server Setup: The server is set to listen on port 3000.
This implementation allows the API to return a subset of user data based on the specified fields in the query parameters. For instance, accessing /users?fields=id,name
would return an array of users containing only their id
and name
properties.