lundi 19 novembre 2018

RESTful implementation of factory method design pattern

How would you design a RESTful API for a class that uses the factory method pattern to create objects?

Let's say you have class Passport:

public class Passport {
   final String firstName;
   final String lastName;
   final Date   birthDate;
   State  state;

   private Passport(State state, String firstName, String lastName, Date birthDate) {
      this.state = state;
      this.firstName = firstName;
      this.lastName = lastName;
      this.birthDate = birthDate;
   } 


   public static Passport createPreliminary(String firstName, String lastName, Date birthDate) {
       return new Passport(PRELIMINARY, firstName, lastName, birthDate);
   }

   public static Passport createRegular(String firstName, String lastName, Date birthDate) {
       return new Passport(REGULAR, firstName, lastName, birthDate);
   }

   public void invalidate() {
      state = INVALID;
   }
}

public enum State {
    PRELIMINARY,
    REGULAR,
    EXPIRED,
    INVALID
}

A Passport instance can be created in two different states. After creation only the state property can be changed in a restricted way via state transition methods like invalidate().

What would be the RESTful way to create Passport resources? A POST to /passports including the state property and check on the server-side that the state is either REGULAR or PRELIMINARY and return a BAD REQUEST response if it is an illegal state? Or two different URLs for creating passport resources, one for "regular" and one for "preliminary" passports?

Aucun commentaire:

Enregistrer un commentaire