|
1 |
| -# Code Express ORM MariaDB |
| 1 | +# Code REST API ORM SQL Database |
2 | 2 |
|
3 |
| -Express-based REST API server with ORM and MariaDB/MySQL. |
| 3 | +Code example to build a REST API with ORM and SQL Database. |
| 4 | + |
| 5 | +Technologies: |
| 6 | + |
| 7 | +- [Express](https://expressjs.com) REST API server |
| 8 | +- [Sequelize](http://docs.sequelizejs.com) ORM |
| 9 | +- [MariaDB](https://mariadb.org)/[MySQL](https://mysql.com) database |
4 | 10 |
|
5 | 11 | ---
|
6 | 12 |
|
7 | 13 | ## Preparation
|
8 | 14 |
|
9 | 15 | ### Database Installation
|
10 | 16 |
|
| 17 | +We recommend using `mariadb` instead of `mysql`. Although the `node` adapter can be using `mysql2` adapter. |
| 18 | + |
11 | 19 | **macOS:**
|
12 | 20 |
|
13 | 21 | ```sh
|
@@ -178,47 +186,47 @@ Change the `server.listen` code block.
|
178 | 186 |
|
179 | 187 | ```js
|
180 | 188 | server.listen(port, function() {
|
181 |
| - console.log('Express server listening on port ' + server.address().port); |
182 |
| -}); |
183 |
| -server.on('error', onError); |
184 |
| -server.on('listening', onListening); |
| 189 | + console.log('Express server listening on port ' + server.address().port) |
| 190 | +}) |
| 191 | +server.on('error', onError) |
| 192 | +server.on('listening', onListening) |
185 | 193 | ```
|
186 | 194 |
|
187 | 195 | Into this, to be wrapped with `models.sequelize`.
|
188 | 196 |
|
189 | 197 | ```js
|
190 |
| -const models = require('./models'); |
| 198 | +const models = require('./models') |
191 | 199 |
|
192 | 200 | // ...
|
193 | 201 |
|
194 | 202 | models.sequelize.sync().then(function() {
|
195 | 203 | server.listen(port, function() {
|
196 |
| - console.log('Express server listening on port ' + server.address().port); |
197 |
| - debug('Express server listening on port ' + server.address().port); |
198 |
| - }); |
199 |
| - server.on('error', onError); |
200 |
| - server.on('listening', onListening); |
201 |
| -}); |
| 204 | + console.log('Express server listening on port ' + server.address().port) |
| 205 | + debug('Express server listening on port ' + server.address().port) |
| 206 | + }) |
| 207 | + server.on('error', onError) |
| 208 | + server.on('listening', onListening) |
| 209 | +}) |
202 | 210 | ```
|
203 | 211 |
|
204 | 212 | Use the model from anywhere. For instance, in your controller functions.
|
205 | 213 |
|
206 | 214 | ```js
|
207 |
| -const models = require('../../models'); |
| 215 | +const models = require('../../models') |
208 | 216 |
|
209 | 217 | // ...
|
210 | 218 |
|
211 | 219 | models.User.findAll()
|
212 | 220 | .then(users => {
|
213 | 221 | res.send({
|
214 | 222 | users
|
215 |
| - }); |
| 223 | + }) |
216 | 224 | })
|
217 | 225 | .catch(error => {
|
218 | 226 | res.status(400).send({
|
219 | 227 | error
|
220 |
| - }); |
221 |
| - }); |
| 228 | + }) |
| 229 | + }) |
222 | 230 | ```
|
223 | 231 |
|
224 | 232 | Run `express` server as usual.
|
|
0 commit comments