Search code examples
restapi-designdatamodel

Thoughts on how to structure data model


Lets say I have two models for use with a RESTful API contract: User and Delivery

// User

id      | Long
-----------------
name    | String
-----------------
street1 | String
-----------------
street2 | String
-----------------
city    | String
-----------------
state   | String
-----------------


// Delivery

id           | Long
--------------------
recipient_id | Long
--------------------

This structure assumes that deliveries are tied to users when in reality they are tied to an address. It seems to make more sense to structure the data in three models: User, Delivery, and Address:

// User

id         | Long
--------------------
name       | String
--------------------
address_id | Long


// Delivery

id           | Long
--------------------
recipient_id | Long
--------------------
address_id   | Long
--------------------

// Address

id      | Long
-----------------
street1 | String
-----------------
street2 | String
-----------------
city    | String
-----------------
state   | String
-----------------

The downside to having three models is that if one was to fetch the street address of a delivery there would have to be a join on every request. However, the business logic is semantically sound this way. Deliveries are linked to addresses, as are users, which is an apt description of their relationship. If the api response needed a union type between users and addresses, one could declare a UserAddress type that has values from the address and user models. But I'm not sure which one is the correct approach. Please lend some advice on what to do here.


Solution

  • Personal idea, the second structure would be the suitable one. Since the total address (include the street, city, etc.) would be one attribute of a single user, so I think it won't be a nice decision to add all these attributes to the user info.

    Secondary, how would if a user update his/her address?If the updated address has been in the address table, you could only changed the bounded address_id, but if use the first structure, you shall update all the address attributes of the user.

    BTW, from the UML side the second choice would also be better. As seen from the the flow, the delivery is tided with address, and one address is bounded with one user. Meanwhile, the address is only bounded with user, but not an attribute of a user, e.g: I use the hotel address as an order's address, but what if I've checked out? Shall you also update the user table for this case?

    So in one word, I think the second choice would be a better choice than the first, both from the structure side and the real-world side.

    Hope could do a little help for you. :-)