$ mkdir myapp
$ cd myapp
$ npm init #follow instructions - wizard app
$ git init
$ npm i express
Create an index.js
file, this will contain the bootstrap of your app.
const express = require('express')
const app = express()
// here will go the routing
app.listen(3000, () => {
console.log('App started and listening on port 3000')
})
Add start
and dev
commands to your package.json
file so you can run your app executing npm start
and npm run dev
in your terminal.
// package.json
…
"scripts": {
"start": "node index.js",
"dev": "nodemon index.js"
}
…
Now its time to define your routes. Go to the index.js
file before the listen command. It's time to define our routes:
app.get('/', (req, res, next) => {
res.send('Hello World')
})
You can run get
, post
, put
and delete
functions for defining your methods. Also, you can pass a function reference so you write the function in another file.
const entitiesController = require('./controllers/entities.controller')
app.get('/entities', entitiesController.getEntities)
app.post('/entities', entitiesController.createEntity)
app.get('/entities/:id', entitiesController.getEntity)
// req.params.id will be available on entitiesController.getEntity call
Pay attention, this function is referenced, not executed. The router will execute it when our app receives a request.
Express routing is very powerful, you have a full guide in here
The controller is the object or class that contains our middlewares (business logic).
const getEntities = (req, res) => {
// Retrieve data from the database
res.send(/*response content*/)
}
const createEntity = (req, res) => {
// Write data to the database
res.send(/*response content*/)
}
modules.exports = {
getEntities: getEntities,
createEntity: createEntity
}
// OR using ES6 construction
// modules.exports = {
// getEntities,
// createEntity
// }
In here we're going full opinionated, we're deciding to work with SQLite and sequelize (totally outside the express domain).
npm i sequelize
Create a db.js
file in the root folder and connect to the db in it. You only have to import it from the index.js
(require('db')
)
// ./utils/db.js
const Sequelize = require('sequelize');
const sequelize = new Sequelize('events', null, null, {
host: 'localhost',
dialect: 'sqlite',
storage: './myDB.sqlite'
});
sequelize
.authenticate()
.then(() => {
console.log('Database connection established successfully.');
})
.catch(err => {
console.error('Unable to connect to the database:', err);
});
module.exports = sequelize;
Then you can create your model file in models/entity.js
and create the schema in it.
// models/entity.js
const Sequelize = require('sequelize');
const sequelize = require('../utils/db');
class MyEntity {
constructor () {
this.entity = sequelize.define('MyEntity', {
info: {type: Sequelize.STRING}
});
}
async getEntities () {
try {
return await this.entity.findAll();
} catch (error) {
console.error(error);
}
}
async createEntity (info) {
try {
return await this.entity.create({info: info});
} catch (error) {
console.error(error);
}
}
async deleteEntity (id) {
try {
return await this.entity.destroy({
where: {
id: id
}
});
} catch (error) {
console.error(error);
}
}
}
module.exports = Entity;
Finally, require it in your controller and start working with the db data!
// Credits: Jean-Marie Porchet