Dia 46/2019 - CRUD com Node.js

Desafio #92daysofcode que fiz no final de 2019. Nesse artigo temos o dia 46, mostrando a contrução de uma API com Node.js.

Pré-visualização

Código

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
// day-46.js
// Prerequisites
// NodeJS - https://nodejs.org/en/
//
// cd 2019/40/day-46/ && npm install && node day-46.js

const express = require('express');
const logger = require('morgan');
const bodyParser = require('body-parser');
const methodOverride = require('method-override');
const cors = require('cors');

const routers = require('./routes/index');

// App
const app = express();

app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(cors());
app.use(methodOverride());

// routers
app.get('/', (req, res) => {
res.json({ message: 'CRUD API' })
});

app.use('/api/v1/movies', routers);

app.use((req, res, next) => {
res.status(404);
res.json({ message: 'Not Found' });
});

// Starting server
app.listen('3000');
console.log('http://localhost:3000/');
1
2
3
4
5
6
7
// routes/index
const express = require('express');
const router = express.Router();

require('./movies')(router);

module.exports = router;
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// routes/movies
const controllers = require('../controllers/movies');
const middleware = require('../middlewares');

// Movies API
module.exports = router => {
/* GET ALL */
router.get('/', controllers.readAll);
/* GET ID */
router.get('/:id', controllers.readId);
/* CREATE */
router.post('/', middleware.checkFields, controllers.createId);
/* UPDATE */
router.put('/:id', middleware.checkFields, controllers.updateId);
/* DELETE */
router.delete('/:id', controllers.deleteId);
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
// controllers/movies/index
const readAll = require('./read-all');
const readId = require('./read-id');
const createId = require('./create-id');
const updateId = require('./update-id');
const deleteId = require('./delete-id');

module.exports = {
// GET /movies
readAll: readAll,
// GET /movies/:id
readId: readId,
// POST /movies
createId: createId,
// PUT /movies/:id
updateId: updateId,
// DELETE /movies/:id
deleteId: deleteId
};
1
2
3
4
5
6
7
8
9
10
11
// controllers/movies/create-id
const movie = require('../../models/movie');

module.exports = async (req, res) => {
await movie.insertMovie(req.body)
.then(movie => res.status(201).json({
message: `${movie.id} created`,
content: movie
}))
.catch(err => res.status(500).json({ message: err.message }))
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// controllers/movies/delete-id
const movie = require('../../models/movie');

module.exports = async (req, res) => {
const id = req.params.id

await movie.deleteMovie(id)
.then(movie => res.json({
message: `${id} deleted`
}))
.catch(err => {
if (err.status) {
res.status(err.status).json({ message: err.message })
}
res.status(500).json({ message: err.message })
})
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
// controllers/movies/read-all
const movie = require('../../models/movie');

module.exports = async (req, res) => {
await movie.getMovies()
.then(movies => res.json(movies))
.catch(err => {
if (err.status) {
res.status(err.status).json({ message: err.message })
} else {
res.status(500).json({ message: err.message })
}
})
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
// controllers/movies/read-id
const movie = require('../../models/movie');

module.exports = async (req, res) => {
const id = req.params.id

await movie.getMovie(id)
.then(movie => res.json(movie))
.catch(err => {
if (err.status) {
res.status(err.status).json({ message: err.message })
} else {
res.status(500).json({ message: err.message })
}
})
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
// controllers/movies/update-id
const movie = require('../../models/movie');

module.exports = async (req, res) => {
const id = req.params.id

await movie.updateMovie(id, req.body)
.then(movie => res.json({
message: `The movie #${id} updated`,
content: movie
}))
.catch(err => {
if (err.status) {
res.status(err.status).json({ message: err.message })
}
res.status(500).json({ message: err.message })
})
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
// middlewares/index
const checkFields = (req, res, next) => {
const { title, description, category } = req.body;

if (title && description && category) {
next();
} else {
res.status(400).json({ message: 'invalid' });
}
}

module.exports = {
checkFields
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
// models/movie
let movies = require('../mock/movies.json');
const helper = require('../helpers');

const filename = './mock/movies.json';

const getMovies = () => {
return new Promise((resolve, reject) => {
if (movies.length === 0) {
reject({
message: 'no movies available',
status: 202
})
}
resolve(movies);
})
}

const getMovie = id => {
return new Promise((resolve, reject) => {
helper.verifyID(movies, id)
.then(movie => resolve(movie))
.catch(err => reject(err))
})
}

const insertMovie = newMovie => {
return new Promise((resolve, reject) => {
const date = {
createdAt: helper.newDate(),
updatedAt: helper.newDate()
}
newMovie = { id: helper.getNewId(), ...date, ...newMovie }
movies.push(newMovie)
helper.writeJSONFile(filename, movies)
resolve(newMovie)
})
}

const updateMovie = (id, newMovie) => {
return new Promise((resolve, reject) => {
helper.verifyID(movies, id)
.then(movie => {
const index = movies.findIndex(p => p.id == movie.id)
const date = {
createdAt: movie.createdAt,
updatedAt: helper.newDate()
}
movies[index] = { id: movie.id, ...date, ...newMovie }
helper.writeJSONFile(filename, movies)
resolve(movies[index])
})
.catch(err => reject(err))
})
}

const deleteMovie = id => {
return new Promise((resolve, reject) => {
helper.verifyID(movies, id)
.then(() => {
movies = movies.filter(p => p.id !== id)
helper.writeJSONFile(filename, movies)
resolve()
})
.catch(err => reject(err))
})
}

module.exports = {
insertMovie,
getMovies,
getMovie,
updateMovie,
deleteMovie
}
1
2
// mock/movies.json
[{"id":"1a","title":"Movie 1","description":"Lorem Ipsum 1","category":"action","createdAt":"2019-11-15 19:25:16","updatedAt":"2019-11-15 19:25:16"},{"id":"2b","title":"Movie 2","description":"Lorem Ipsum 2","category":"comedy","createdAt":"2019-11-15 20:25:16","updatedAt":"2019-11-15 20:25:16"},{"id":"3c","title":"Movie 3","description":"Lorem Ipsum 3","category":"comedy","createdAt":"2019-11-15 21:25:16","updatedAt":"2019-11-15 21:25:16"},{"id":"4d","title":"Movie 4","description":"Lorem Ipsum 4","category":"comedy","createdAt":"2019-11-15 22:25:16","updatedAt":"2019-11-15 22:25:16"}]
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
// helpers/index
const fs = require('fs');
const { format } = require('date-fns');

const getNewId = () => {
return (((1+Math.random())*0x10000)|0).toString(16).substring(1);
}

const newDate = () => format(new Date(), 'yyyy-MM-dd HH:mm:ss');

const verifyID = (array, id) => {
return new Promise((resolve, reject) => {
const row = array.find(r => r.id == id)
if (!row) {
reject({
message: 'invalid ID',
status: 404
})
}
resolve(row);
})
}

const writeJSONFile = (filename, content) => {
fs.writeFileSync(filename, JSON.stringify(content), 'utf8', (err) => {
if (err) {
console.log(err);
}
})
}

module.exports = {
getNewId,
newDate,
verifyID,
writeJSONFile
}

Conclusão

A postagem original pode ser vista no meu Instagram e o código está acessível no meu Github.

Relacionados

Ao fechar este aviso ou continuar navegando no site Nerd Calistênico, você aceita o uso de cookies.

Este site usa cookies para assegurar a melhor experiência para os nossos usuários. Consulte nossa política de privacidade.

Uma nova versão está disponível. Clique aqui para atualizar.