28
loading...
This website collects cookies to deliver better user experience
mkdir phonebook && cd phonebook
npm init -y
{
"name": "phonebook",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC"
}
npm install express body-parser
npm install --save-dev nodemon jest supertest
const express = require('express')
const app = express()
const bodyParser = require('body-parser')
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({ extended: true }))
app.use((req, resp, next) => {
resp.set('Access-Control-Allow-Origin', '*')
next()
})
const server = app.listen(3000, () => console.log('A API está funcionando!'))
module.exports = server
npm run dev
> [email protected] dev /Users/guilherme/develop/repo/phonebook
> nodemon index.js
[nodemon] 2.0.7
[nodemon] to restart at any time, enter `rs`
[nodemon] watching path(s): *.*
[nodemon] watching extensions: js,mjs,json
[nodemon] starting `node index.js`
A API está funcionando!
const Contact = {
id: 0,
name: "",
telephone: "",
address: ""
}
module.exports = Object.create(Contact)
class InMemoryRepository{
constructor(){
this._data = []
}
insert(contact){
this._data.push(contact)
}
selectAll(){
return this._data
}
selectById(id){
return this._data.find(c => c.id === id)
}
update(id, contact){
const elementId = this._data.findIndex(element => element.id === id);
contact.id = id
const updateContact = Object.assign(this._data[elementId], contact)
this._data[elementId] = updateContact
return this._data[elementId]
}
remove(id){
const index = this._data.findIndex(element => element.id === id)
this._data.splice(index, 1)
}
}
module.exports = InMemoryRepository
class Service{
constructor(repository){
this.repository = repository
}
create(body){
this.repository.insert(body)
}
getById(id){
return this.repository.selectById(parseInt(id, 2))
}
getAll(){
return this.repository.selectAll()
}
put(id, body){
return this.repository.update(parseInt(id, 2), body)
}
remove(id){
this.repository.remove(parseInt(id, 2))
}
}
module.exports = Service
const router = require('express').Router()
const InMemoryRepository = require('../repository')
const Service = require('../service')
const service = new Service(new InMemoryRepository())
router.post('/', (req, res) => {
const contact = req.body
service.create(contact)
res.status(201).json(contact)
})
router.get('/:id', (req, res) => {
const id = req.params.id
const result = service.getById(id)
if(result !== undefined){
res.status(200).json(result)
return
}
res.sendStatus(204)
})
router.get('/', (req, res) => {
const result = service.getAll()
if(result.length > 0){
res.status(200).json(result)
return
}
res.sendStatus(204)
})
router.put("/:id", (req, res) => {
const id = req.params.id
const body = req.body
const result = service.put(id, body)
res.status(200).json(result)
})
router.delete("/:id", (req, res) => {
const id = req.params.id
service.remove(id)
res.sendStatus(204)
})
router.get('/health', (req, res) => {
res.status(200).json({status: "Ok"})
})
router.options('/', (req, res) => {
res.set('Access-Control-Allow-Methods', 'GET, POST')
res.set('Access-Control-Allow-Headers', 'Content-Type')
res.status(204)
res.end()
})
module.exports = router
const router = require('express').Router()
const InMemoryRepository = require('../repository')
const Service = require('../service')
const service = new Service(new InMemoryRepository())
router.post('/', (req, res) => {
const contact = req.body
service.create(contact)
res.status(201).json(contact)
})
router.get('/:id', (req, res) => {
const id = req.params.id
const result = service.getById(id)
if(result !== undefined){
res.status(200).json(result)
return
}
res.sendStatus(204)
})
router.get('/', (req, res) => {
const result = service.getAll()
if(result.length > 0){
res.status(200).json(result)
return
}
res.sendStatus(204)
})
const express = require('express')
const app = express()
const bodyParser = require('body-parser')
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({ extended: true }))
app.use((req, resp, next) => {
resp.set('Access-Control-Allow-Origin', '*')
next()
})
const server = app.listen(3000, () => console.log('A API está funcionando!'))
module.exports = server
const express = require('express')
const app = express()
const bodyParser = require('body-parser')
const router = require('./router')
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({ extended: true }))
app.use((req, resp, next) => {
resp.set('Access-Control-Allow-Origin', '*')
next()
})
app.use('/api', router)
const server = app.listen(3000, () => console.log('A API está funcionando!'))
module.exports = server
nodemon index.js
curl --location --request POST 'http://localhost:3000/api' \
--header 'Content-Type: application/json' \
--data-raw '{
"id": 1,
"name": "Kelly",
"telephone": "118888888",
"address": "Rua dos Bobos n 1"
}' | json_pp
{
"id" : 1,
"name" : "Kelly",
"address" : "Rua dos Bobos n 1",
"telephone" : "118888888"
}
const supertest = require('supertest')
const server = require('../index')
afterAll( async () => {
server.close()
});
describe('Make requests to the server', () => {
it('Should create a contact', async () => {
const resp = await supertest(server).post('/api').send({
"id": 1,
"name": "Kelly",
"telephone": "118888888",
"address": "Rua dos Bobos n 1"
});
expect(resp.statusCode).toEqual(201)
expect(resp.body.name).toEqual("Kelly")
})
})
const resp = await supertest(server).post('/api').send({
"id": 1,
"name": "Kelly",
"telephone": "118888888",
"address": "Rua dos Bobos n 1"
});
expect(resp.statusCode).toEqual(201)
expect(resp.body.name).toEqual("Kelly")
jest --coverage
> jest --coverage --runInBand
PASS router/route.test.js
Make requests to the server
✓ Should create a contact (65 ms)
console.log
A API está funcionando!
at Server.<anonymous> (index.js:16:47)
---------------------------|---------|----------|---------|---------|----------------------------------
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s
---------------------------|---------|----------|---------|---------|----------------------------------
All files | 48.68 | 0 | 29.17 | 50 |
phonebook | 100 | 100 | 100 | 100 |
index.js | 100 | 100 | 100 | 100 |
phonebook/model | 100 | 100 | 100 | 100 |
index.js | 100 | 100 | 100 | 100 |
phonebook/repository | 20 | 100 | 22.22 | 25 |
index.js | 20 | 100 | 22.22 | 25 | 12-35
phonebook/router | 39.47 | 0 | 14.29 | 39.47 |
index.js | 39.47 | 0 | 14.29 | 39.47 | 16-24,30-37,43-48,53-57,62,66-69
phonebook/service | 50 | 100 | 33.33 | 50 |
index.js | 50 | 100 | 33.33 | 50 | 14-26
---------------------------|---------|----------|---------|---------|----------------------------------
Test Suites: 1 passed, 1 total
Tests: 1 passed, 1 total
Snapshots: 0 total
Time: 2.015 s
Ran all test suites.