I work on the frontend team, and the server team has started using a different approach for API requests. They now require me to send a property with the specific fields I want to be returned in the response.
For example:
http.post(`/api/v1/users`, { requiredFields: [1, 2, 3] })
// The response will be [{ firstname, lastname, age }]
// This means that firstname is 1, lastname is 2, and so on.
I want to make the response type-safe based on the numbers I send.
Here’s a small function that simulates what I need to send and what I get:
function server(fields) {
const allFields = {
1: 'firstname',
2: 'lastname',
3: 'age',
4: 'address',
5: 'email'
};
const result = {};
fields.forEach(field => {
if (allFields[field]) {
result[allFields[field]] = null;
}
});
return result;
}
I thought of creating an interface, type, enum, or some schema, but I’m not sure how to integrate that into JavaScript.