Pregunta

I am building a blog system's comment api, and decided to provide the REST api like:

post: /blogs/{blogId}/comments/
put: /blogs/{blogId}/comments/{commentId}

These api accept the same parameter:

public class CommentEditParam {
    private String content;

    // identify the reply to user's id
    private Long replyTo;
}

And the comment entity has these fields:

@Entity
public class Comment {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    private String content;

    private Integer status;

    @ManyToOne
    @JoinColumn(name = "author_id")
    private User author;

    @ManyToOne
    @JoinColumn(name = "reply_to")
    @Column(nullable = true)
    private User replyTo;

    @ManyToOne
    @JoinColumn(name = "blog_id")
    private Blog blog;
}

Now here's the problem, do i need to check the existence of blogId/ReplyToUserId when adding a new comment? If i need to do the check, it seems that i need to query the database two more times. But if i don't, what's the drawback?

¿Fue útil?

Solución

Not validating user input... what is the worst that could happen?

  • You accept a comment that will never be displayed, ever.

  • A user creates a new blog entry only to find two million FIRST!!! comments.

  • The most popular blog entry based on comments is a 404 Not Found

  • A New user suddenly becomes the most reviled person ever with 200 thousand troll comments aimed at their first comment.

  • A user becomes the most prolific commentator, just not on any blog around here...

  • A user has who hasn't logged in for months (and still hasn't) has been very busy posting and commenting. They must be a ventriloquist... textriloquest? blogtriloquist?

And those are the pleasant consequences.

The unpleasant consequences involve lawyers and governments suing for damages and launching investigations into your organisation for negligence, copy right, misrepresentation, illegal advertising, and more.


Yes, validating input requires work. Two additional database queries for such trivial pieces of information should be quite quick. If they are not quick, "why is it not quick" is the better question to ask.

Licenciado bajo: CC-BY-SA con atribución
scroll top