Much like PHP, JS can make use of a client library where all of the API communication is handled. This is a separation of concerns and is considered good practice to follow.
When writing your API you should carefully consider the structure you would like.
Generally, your code will consist or
response objects that clearly identify the data required to make
requests and the data that is expected in return.
response objects you will find that it is more difficult to test your code and that new developers to
a project will have to decipher what data is being returned from the server and what data the server expects.
Your API may also need to deal with
entities, these are used on the server side to handle persistence logic but can also
be extended to the frontend. Entities are never returned directly dy an endpoint but usually come as part of a response/request object.
To summarise the above, JS can send
request objects to the server that may contain
entities, JS will receive responses that
entities that it can manipulate.
For example, in a todo list application, a
request object could be to
create a new todo item, this would contain a todo item
This also works in reverse where a
response contains a todo item
entity that we can then display in the frontend.
Here is an example directory structure:
1 2 3 4 5 6 7
. └── js └── Data ├── Api ├── Entities ├── Requests └── Responses
All of the API related logic is placed under the
Data module namespace.
Apidirectory contains all of the logic to accept
requestobjects and in turn returns
Entitiesare the objects used on the server side for persistence logic
Requestsare the possible requests that can be sent through different endpoints
Responsesare returned from endpoints and contain data from the server
Depending on the size of your project, you may find it easier to group your Api classes based on the entity they are associated with.
For example, if you have a
Sales module with a number of entities and endpoints you would not want this to be grouped under the top
js directory. This approach also allows you to split your module into a separate dependency should you find this appropriate.
Should you find you need to restructure things, providing you have not used