Skip to content

Commit

Permalink
version 1.0.0
Browse files Browse the repository at this point in the history
  • Loading branch information
gabrielboliveira committed Jan 3, 2017
1 parent 1aa5d78 commit 57ce338
Show file tree
Hide file tree
Showing 14 changed files with 967 additions and 2 deletions.
9 changes: 9 additions & 0 deletions .babelrc
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
{
"presets": ["es2015"],
"plugins": ["babel-plugin-add-module-exports"],
"env": {
"production": {
"presets": ["babili"]
}
}
}
2 changes: 1 addition & 1 deletion .editorconfig
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,6 @@ indent_size = 4
trim_trailing_whitespace = true
charset = utf-8

[*.json]
[{*.json,.babelrc,.jshintrc}]
indent_style = space
indent_size = 2
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -41,3 +41,4 @@ jspm_packages

# Build files
dist
prod
9 changes: 9 additions & 0 deletions .jshintrc
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
{
"node": true,
"mocha": true,
"esversion": 6,
"globalstrict": false,
"asi": true,
"curly": true,
"trailing": true
}
69 changes: 68 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,70 @@
# rest-tracking

REST developed for [tracking-correios](https://github.com/gabrielboliveira/tracking-correios) package.
API REST para abstrair o método `track` do pacote [tracking-correios](https://github.com/gabrielboliveira/tracking-correios).

## Pré-requisitos

- Node.js (versão 0.12 a latest)
- npm

## Instalação

```sh
# ssh
$ git clone [email protected]:gabrielboliveira/rest-tracking.git

# https
$ git clone https://github.com/gabrielboliveira/rest-tracking.git

$ cd rest-tracking
$ npm install
$ node start
```

A configuração da porta padrão (3000) é feita no arquivo [env.json](src/env.json).

## Uso

A API expõe o endpoint `/track` para obter os dados de rastreio dos pacotes. Recebe um objeto com atributo `codes` e um array de códigos:

```json
{
"codes": ["DU123123123BR"]
}
```

Exemplo:

```sh
$ curl -i -H "Accept: application/json" -H "Content-Type: application/json" -X POST -d '{"codes": ["DU123123123BR"]}' http://localhost:3000/track

> HTTP/1.1 200 OK
Content-Type: application/json
Content-Length: 101
Date: Tue, 03 Jan 2017 12:29:09 GMT
Connection: keep-alive

{"data":[{"numero":"DU123123123BR","erro":"Objeto não encontrado na base de dados dos Correios."}]}
```

## Produção

Para executar a API em produção é recomendado um _process manager_ como por exemplo [PM2](https://github.com/Unitech/pm2) ou [forever](https://github.com/foreverjs/forever).

```sh'
$ npm run build-prod
$ pm2 start prod/track.js --name="rest-tracking"
```

## Testes

Para desenvolvimento, foram desenvolvidos testes unitários e E2E. Para executá-los, deve rodar o seguinte script:

```sh
$ npm test
```

## Licença

[MIT](LICENSE.md).

43 changes: 43 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
{
"name": "rest-tracking",
"version": "1.0.0",
"description": "REST desenvolvido para abstrair o pacote tracking-correios.",
"main": "dist/track.js",
"keywords": [],
"author": "Gabriel Oliveira",
"license": "MIT",
"repository": {
"type": "git",
"url": "https://github.com/gabrielboliveira/rest-tracking.git"
},
"bugs": {
"url": "https://github.com/gabrielboliveira/rest-tracking/issues"
},
"scripts": {
"test": "npm run test-unit && npm run test-e2e",
"test-e2e": "mocha --compilers js:babel-core/register tests/e2e/*.spec.js --timeout 15000",
"test-unit": "mocha --compilers js:babel-core/register tests/unit/*.spec.js",
"build": "babel src --out-dir dist --copy-files",
"build-prod": "BABEL_ENV=production babel src --out-dir prod --copy-files",
"postinstall": "npm run build",
"start": "node dist/track.js",
"prod": "node prod/track.js"
},
"dependencies": {
"restify": "^4.3.0",
"tracking-correios": "^1.0.4"
},
"devDependencies": {
"babel-cli": "^6.18.0",
"babel-core": "^6.20.0",
"babel-plugin-add-module-exports": "^0.2.1",
"babel-preset-es2015": "^6.18.0",
"babili": "0.0.9",
"chai": "^3.5.0",
"chai-as-promised": "^6.0.0",
"chai-http": "^3.0.0",
"chai-subset": "^1.3.0",
"mocha": "^3.2.0",
"nock": "^9.0.2"
}
}
4 changes: 4 additions & 0 deletions src/env.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
{
"name": "REST Tracking",
"port": 3000
}
33 changes: 33 additions & 0 deletions src/track.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
const restify = require('restify')
const TrackingCorreios = require('tracking-correios')
const env = require('./env')

const server = restify.createServer({
name: env.name
})

server.use(restify.bodyParser())

server.post('/track', (req, res, next) => {
if (req && req.params && req.params.codes) {
TrackingCorreios.track(req.params.codes)
.then( success => {
res.send( { data: success } )
})
.catch( error => {
res.send(new restify.InvalidArgumentError(error.message))
})
.finally( () => {
next()
})
} else {
res.send(new restify.InvalidArgumentError("Nenhum dado válido recebido."))
next()
}
});

server.listen(env.port, () => console.log(`${server.name} listening at ${server.url}`))

process.on('uncaughtException', function (err) {
console.error(JSON.parse(JSON.stringify(err, ['stack', 'message', 'inner'], 2)))
})
87 changes: 87 additions & 0 deletions tests/e2e/track.spec.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
"use strict"

const chai = require('chai')
const chaiHttp = require('chai-http')
const server = require('../../src/track')
const { port } = require('../../src/env')

const path = require('path')

chai.use(chaiHttp)

const expect = chai.expect;

describe('rest-tracking (unit)', () => {

describe('/POST', () => {
let testFileOne = require('../responses/valid-one.json')
let testFileTwo = require('../responses/valid-two.json')
let postObj = {
"codes": [ ]
}

it('it should POST with valid code', (done) => {
postObj.codes = [ "DU897123996BR" ]

chai.request(`localhost:${port}`)
.post('/track')
.send(postObj)
.end((err, res) => {
expect(err).to.be.null;
expect(res).to.have.status(200);
expect(res).to.be.a('object');
expect(res.body).to.have.property('data');
expect(res.body.data).to.be.deep.equal(testFileOne);
done();
});
});

it('it should POST with several valid code', (done) => {
postObj.codes = [ 'DU897123996BR', 'PN273603577BR' ]

chai.request(`localhost:${port}`)
.post('/track')
.send(postObj)
.end((err, res) => {
expect(err).to.be.null;
expect(res).to.have.status(200);
expect(res).to.be.a('object');
expect(res.body).to.have.property('data');
expect(res.body.data).to.be.deep.equal(testFileTwo);
done();
});
});

it('it should POST with invalid code', (done) => {
postObj.codes = [ "invalid" ]

chai.request(`localhost:${port}`)
.post('/track')
.send(postObj)
.end((err, res) => {
expect(err).to.not.be.null;
expect(res).to.have.status(409);
expect(res).to.be.a('object');
expect(res.body).to.have.property('code');
expect(res.body).to.have.property('message');
done();
});
});

it('it should POST with nothing', (done) => {
chai.request(`localhost:${port}`)
.post('/track')
.send('')
.end((err, res) => {
expect(err).to.not.be.null;
expect(res).to.have.status(409);
expect(res).to.be.a('object');
expect(res.body).to.have.property('code');
expect(res.body).to.have.property('message');
done();
});
});

});

})
101 changes: 101 additions & 0 deletions tests/responses/valid-one.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,101 @@
[
{
"numero": "DU897123996BR",
"sigla": "DU",
"nome": "ENCOMENDA E-SEDEX",
"categoria": "E-SEDEX",
"evento": [
{
"tipo": "BDE",
"status": "01",
"data": "12/12/2016",
"hora": "19:06",
"descricao": "Objeto entregue ao destinatário",
"recebedor": "",
"documento": "",
"comentario": "",
"local": "CEE BAURU",
"codigo": "17034972",
"cidade": "Bauru",
"uf": "SP"
},
{
"tipo": "OEC",
"status": "01",
"data": "12/12/2016",
"hora": "10:30",
"descricao": "Objeto saiu para entrega ao destinatário",
"local": "CEE BAURU",
"codigo": "17034972",
"cidade": "Bauru",
"uf": "SP"
},
{
"tipo": "RO",
"status": "01",
"data": "12/12/2016",
"hora": "04:34",
"descricao": "Objeto encaminhado",
"local": "CTCE BAURU",
"codigo": "17034970",
"cidade": "Bauru",
"uf": "SP",
"destino": {
"local": "CEE BAURU",
"codigo": "17034972",
"cidade": "Bauru",
"bairro": "Distrito Industrial",
"uf": "SP"
}
},
{
"tipo": "RO",
"status": "01",
"data": "08/12/2016",
"hora": "21:13",
"descricao": "Objeto encaminhado",
"local": "CTCE LONDRINA",
"codigo": "86066970",
"cidade": "LONDRINA",
"uf": "PR",
"destino": {
"local": "CTCE BAURU",
"codigo": "17034970",
"cidade": "Bauru",
"bairro": "Distrito Industrial",
"uf": "SP"
}
},
{
"tipo": "RO",
"status": "01",
"data": "08/12/2016",
"hora": "13:37",
"descricao": "Objeto encaminhado",
"local": "AGF JARDIM ALVORADA",
"codigo": "87030981",
"cidade": "Maringa",
"uf": "PR",
"destino": {
"local": "CTCE LONDRINA",
"codigo": "86066970",
"cidade": "LONDRINA",
"bairro": "JARDIM COLUMBIA",
"uf": "PR"
}
},
{
"tipo": "PO",
"status": "09",
"data": "07/12/2016",
"hora": "17:37",
"descricao": "Objeto postado após o horário limite da agência",
"detalhe": "Objeto sujeito a encaminhamento no próximo dia útil",
"local": "AGF JARDIM ALVORADA",
"codigo": "87030981",
"cidade": "Maringa",
"uf": "PR"
}
]
}
]
Loading

0 comments on commit 57ce338

Please sign in to comment.