mardi 18 août 2020

Object naming conventions for both REST and database

I keep reinventing the wheel when it comes to building a CRUD app with a REST API in Java, and I'm looking for some kind of standard to apply.

Let's do this by example. Let's say I have a table of "users" and these REST endpoints:

GET  /users/{user_id} // returns a user
POST /users           // creates a user
PUT  /users/{user_id} // updates a user

Within each method, I have to select, insert, or update the user in a database.

For each of the six operations (3 for REST, 3 for the database), I need a different set of properties for the "user" POJO that comes in over REST or gets sent to the database.

For example, on the REST side, when creating a user, I don't want a user_id (because that gets created by the database), but I do want a password. When getting a user, I do want user_id, but I never want to return a password back to the client. When updating a user, I may want omit some fields because they are read-only (like username or creation date).

On the database side, I may need different fields that don't get passed back in the REST API, like "is_approved" or "some_secret". And I often need to create derived fields, like "password_hash".

So, as I say, six different representations of the same thing. In Java, I do it by making six different POJO classes. It doesn't always take that many unique classes, but sometimes it does.

In the REST API, I do not want to use the same class for all endpoints and just ignore some fields, because this class gets passed to our API documentation tool and its properties get published.

Are there any standard naming conventions for these six classes?

For REST, in the past, I've used CreateUser, GetUser, and UpdateUser. I don't like these names because they're verbs and they should be nouns.

UserForCreation and UserForUpdate are awkward. NewUser and ModifiedUser might be good, but I don't know what to call a user for a GET.

And I need another whole set of names for the database side.

Surely there is a standard or a convention for this kind of thing. Anyone know what it is?

Aucun commentaire:

Enregistrer un commentaire