The server side often involves some adding, deleting, modifying and checking interfaces. In order to improve code reuse and enhance work efficiency, a general CRUD interface based on Nod-mongodb is developed.
The code analysis
Let’s take a look at the normal server interface:
Analyze the variables:
The routing resource
Model
Five requests:
Create data submission to the database
Get all the data
Get a single piece of data based on the ID
Submit a single piece of data according to the ID modification
Delete a single piece of data based on the ID
Turn routes and models into variables
First we observe that the routing resource is the plural of the model word with a smaller first letter, such as:
Model: the Category
Resource: catergories
The correspondence between the two: The model is a “class” form of resource.
Modify interface URL
Get the corresponding model from each routing URL
Since the parameters defined in app.use() need to be used in the router, merge the URL parameters:
The Serve project installs a third party module with the ability to turn a lowercase plural word into a class (uppercase and singular) :npm i inflection
Take one of the interfaces: comment out the code that requires a specific model.
Adding these two lines of code to each interface can change the Model into a variable, but this is a bit cumbersome. Placing these two lines of code in a front-end middleware that precedes each interface achieves the same effect:
Change the routing and model in each interface to variables:
Change the request path of the front-end project admin:
Judgment by Associated Query
Some pages need associated query, some do not need to make a judgment
Look at the interface, no problem.