REST API and polymorphism

半世苍凉 提交于 2019-12-23 02:42:10

问题


I have classes hierarchy in JAVA that should be available through a rest API for an angularJS SPA application (the data persisted in PostgreSQL DB)

the classes hierarchy looks as follows:

  • PERSON BASE ABSTRACT CLASS contains name and and age
  • CHILD EXTENDS PERSON contains favorite TV show
  • PARENT EXTENDS PERSON contains a list of children
  • GRANDPARENT EXTENDS PERSON contains a list of parents

The UI looks like an hierarchy tree, where you can view all the data and edit it.

I could thought of three ways to model this:

  1. one endpoint with hierarchy /grandparent:id/parents:id/children:id
    example
    POST /grandparent/1/parents/2/children
    in order to create a new child

PROS: more readable, more restful CONS: complex to implement, when I edit a child, I don't care about all the hierarchy at most I need the direct parent in order to create it, but for editing, child ID will be sufficient to find the it in the DB

  1. three endpoints : /grandparents:id, /parents:id, /children:id
    POST /children?parentID=2

PROS: ? CONS: a lot of duplication

3.one endpoint /people (in the request/response JSON, use type field to denote the class and a parentID field.

POST /people { name .. type : child parentId : 2 }

PROS: more polymorphic CONS: less restful?

what do you think?


回答1:


I think you should just have a 'people' endpoint, and a 'person' endpoint.

The people endpoint would return a list of person_ids fitting a criteria. For instance 'has_children' = true would return all parents. 'has_parents' = false would return all test tube babies, etc etc etc.

The 'person' endpoint would return details about the specific person, given a specific id. Here you would see eye color, gender, a list of children person_ids, a list of parent person_ids, perhaps a list of grandchildrens person_id. Any other details about the person would be here.

You might want to consider refactoring the Java code if the extended classes don't add any significant functionality that you couldn't get simply from a person class.

Essentially you are dealing with person 'nodes' here.

Check out Graph Commons API maybe much of your work is done for you.



来源:https://stackoverflow.com/questions/38797797/rest-api-and-polymorphism

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!