You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
The same `customer` schema in PostgreSQL database using sequelize.
24
24
25
25
```js
26
+
constSequelize=require("sequelize");
27
+
26
28
module.exports= (sequelize, DataTypes) => {
27
29
constCustomer=sequelize.define("customer", {
28
30
name: {
@@ -43,20 +45,31 @@ We can see that the schema definition for the `customer` has a `name` that is ty
43
45
44
46
When we are building APIs, we want our models to provide four basic types of functionality. The model must be able to Create, Read, Update, and Delete resources. Computer scientists often refer to these functions by the acronym CRUD. A model should have the ability to perform at most these four functions in order to be complete.
45
47
46
-
### CRUD and REST
48
+
### CRUD in REST
47
49
48
-
**What is REST?**
50
+
In a REST environment, CRUD often corresponds to the [HTTP request methods](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods)`POST`, `GET`, `PUT`, and `DELETE`, respectively. These are the fundamental elements of a persistent storage system.
49
51
50
-
REST is a set of architectural constraints. API developers can implement REST in a variety of ways. When a client request is made via a RESTful API, it transfers data as an object in some format to the requester or endpoint. There are several formats, JSON is the most generally popular file format to use.
52
+
For example, imagine we are working with a system that is keeping track of meals and their corresponding prices for a restaurant. Let’s look at how we would implement CRUD operations.
51
53
52
-
**Resource in REST**
53
-
A resource in REST is a like an Object or an Entity in a Database. Once a resource is identified then its representation is to be decided using a standard format so that the server can send the resource in the decided on format and client can understand the same format. A resource can be any information that can be named (e.g. a person, a user, an invoice, a collection of invoices, etc).
54
+
First of all, we need to define our food item schema (we will use mongoose for that), and let's call it "dish".
54
55
55
-
### CRUD (CREATE, READ, UPDATE, DELETE)
56
+
```js
57
+
constmongoose=require("mongoose");
56
58
57
-
In a REST environment, CRUD often corresponds to the [HTTP request methods](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods)`POST`, `GET`, `PUT`, and `DELETE`, respectively. These are the fundamental elements of a persistent storage system.
59
+
constdish=newmongoose.Schema({
60
+
title: {
61
+
type:String,
62
+
required:true,
63
+
},
64
+
image: {
65
+
type:String,
66
+
required:true,
67
+
},
68
+
tags: [String],
69
+
});
58
70
59
-
For example, imagine we are working with a system that is keeping track of meals and their corresponding prices for a restaurant. Let’s look at how we would implement CRUD operations.
71
+
module.exports=mongoose.model("dish", dish);
72
+
```
60
73
61
74
#### Create
62
75
@@ -65,11 +78,11 @@ Imagine that we are adding a new food item to the stored list of dishes for this
65
78
66
79
Note: Use `POST` when you want to add a child resource under resources collection.
67
80
68
-
##### Request:
81
+
Request:
69
82
70
83
`POST http://www.myrestaurant.com/api/dishes/`
71
84
72
-
We will need to send the dish data too as an object.
85
+
We will need to send the dish data too as an object in the body.
73
86
74
87
For example
75
88
@@ -79,6 +92,26 @@ For example
79
92
image:"www.food.com/lasagna.jpg",
80
93
tags: ["simple", "classic"]
81
94
}
95
+
96
+
```
97
+
98
+
On the backend side, our express route will be
99
+
100
+
```js
101
+
router.post("/dishes", async (req, res) => {
102
+
// get the data we sent in the body
103
+
constdishData=req.body;
104
+
try {
105
+
// using the create() method with Mongoose will insert the data we sent in the body to our MongoDB database
106
+
// and return an object of that data when done
107
+
constnewDish=awaitDishModel.create(dishData);
108
+
// then, we return the new created dish object
109
+
res.status(201).json(newDish);
110
+
} catch (err) {
111
+
res.status(422).json({ message:err.message });
112
+
}
113
+
});
114
+
})
82
115
```
83
116
84
117
#### Read
@@ -87,18 +120,29 @@ To read resources in a REST environment, we use the GET method. In practice, rea
87
120
88
121
To read resources in a REST environment, we use the GET method. Reading a resource should never change any information - it should only retrieve it. REST itself is more like a set of guidelines. Technically, you can change data in a `GET` request, but since we are creating a RESTful API, you shouldn't do that. Having a GET request that updates data in your database would be confusing to the users of your API and violate the expected behavior of REST.
89
122
90
-
##### Request:
123
+
Request:
91
124
92
125
`GET http://www.myrestaurant.com/api/dishes/`
93
126
127
+
The express route for getting all dished will be
128
+
129
+
```js
130
+
router.get("/dishes", async (_, res) => {
131
+
// here, we are using the find() to return all dishes from our MongoDB database
132
+
// find() will return an array of dish objects
133
+
constposts=awaitDishModel.find();
134
+
res.json(posts);
135
+
});
136
+
```
137
+
94
138
#### Update
95
139
96
140
PUT is the HTTP method used for the CRUD operation, Update.
97
141
So if the price of Avocado Toast has gone up, we should go into the database and update that information using PUT.
98
142
99
143
Note: Use `PUT` when you want to modify a singular resource which is already a part of resources collection. `PUT` replaces the resource with the data you send in its entirety.
100
144
101
-
##### Request:
145
+
Request:
102
146
103
147
`PUT http://www.myrestaurant.com/dishes/:id`
104
148
@@ -114,15 +158,60 @@ For example
114
158
}
115
159
```
116
160
161
+
Note that when using Mongoose you don't have to send all the object fields, you can only send the ones that got changed.
162
+
163
+
For example, we can only send the title.
164
+
165
+
```js
166
+
{
167
+
title:"New dish title",
168
+
}
169
+
```
170
+
171
+
Respectively, our express route for both these examples will be
172
+
173
+
```js
174
+
router.put("/dishes/:id", async (req, res) => {
175
+
// we need the dish id in order to tell Mongoose which dish to update in our database
176
+
const { id } =req.params;
177
+
try {
178
+
// the findByIdAndUpdate() will make sure the dish exist before updating it
// the { new: true } here is just to tell Mongoose we want the newely updated dish back
181
+
new:true,
182
+
});
183
+
// we return the updated dish as a JSON object to the user
184
+
res.json(updatedDish);
185
+
} catch (err) {
186
+
res.status(422).json({ message:err.message });
187
+
}
188
+
});
189
+
```
190
+
117
191
#### Delete
118
192
119
193
The CRUD operation Delete corresponds to the HTTP method DELETE. It is used to remove a resource from the system.
120
194
Let’s say that the world avocado shortage has reached a critical point, and we can no longer afford to serve this modern delicacy at all. We should go into the database and delete the item that corresponds to **Avocado Toast**, which we know has an `id` of 1223.
121
195
122
-
##### Request:
196
+
Request:
123
197
124
198
`DELETE http://www.myrestaurant.com/dishes/:id`
125
199
200
+
The express route for this deleting request can be
0 commit comments