Gallex
Gallex

Reputation: 549

NodeJS DELETE API

I have to build an API with Node and express as package with the following requirements:

DELETE on /api/posts — there will be one query parameters: id. If the server has a post with the given ID, it should remove it and the response should be only the 200 status code. No other posts should be affected; in particular, their IDs won't change. If the server did not have a post with the given ID, the response should be the 404 status code.

I have the following code that works ok

app.delete('/api/posts', (req, res) => {
  let id = req.query.id;
  if (typeof id !== 'number')
    id = parseInt(id, 10);
  let index;
  for (let i = 0; i < posts.length; i += 1) {
    if (posts[i].id === id) {
      index = i;
      break;
    }
  }
  if (index == null) {
    res.status(404).send();
    return;
  }
  posts.splice(index, 1);
  res.json(posts);
});

My question is, if this approach is correct or the code can be improved furthermore? I just started to learn about API's and Node....

Upvotes: 0

Views: 2098

Answers (1)

Thomas
Thomas

Reputation: 2536

I do not like logic within my route definition. So i would write it like this:

route.js:

const posts = require('./posts.js')

app.delete('/api/posts', (req, res) => {
    posts.delete(req.query.id)
        .then(res.json)
        .catch(() => { res.status(404).send() })
})

posts.js:

class posts {
    constructor() {
        this.posts = []
    }
    add(newPost) {
        this.posts.push(newPost)
    }

    delete(postId) {
        if (// test ob gelöscht werden kann) {
           // löschen
           return Promise.resolve(this.posts)
        } else {
           return Promise.reject(new Error('Can not delete post'))
        }
    }
}

This is more like pseudo code, but hopefully you get my point. I am able to recognise what the route does and what it needs with no trouble. If i fullfill the requirements and get an error then i deep dive into the class definition. For me this is better maintainable.

Upvotes: 3

Related Questions