Skip to content
This repository has been archived by the owner on Jun 4, 2024. It is now read-only.

Commit

Permalink
version 1.0.0
Browse files Browse the repository at this point in the history
  • Loading branch information
gabrielboliveira committed Dec 15, 2016
1 parent 8926283 commit 0bccd5c
Show file tree
Hide file tree
Showing 18 changed files with 1,895 additions and 3 deletions.
4 changes: 4 additions & 0 deletions .babelrc
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
{
"presets": ["es2015"],
"plugins": ["babel-plugin-add-module-exports"]
}
13 changes: 13 additions & 0 deletions .editorconfig
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
root = true

[*]
end_of_line = lf
insert_final_newline = true
indent_style = space
indent_size = 4
trim_trailing_whitespace = true
charset = utf-8

[{package.json}]
indent_style = space
indent_size = 2
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
}
5 changes: 5 additions & 0 deletions .npmignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
dist
tests
.editorconfig
.jshintrc
.DS_Store
2 changes: 1 addition & 1 deletion LICENSE.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
The MIT License (MIT)

Copyright (c) 2014 Gabriel Oliveira
Copyright (c) 2016 Gabriel Oliveira

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
Expand Down
277 changes: 275 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,276 @@
# rastrear-pacote
# tracking-correios

Módulo para consultar o status do rastreio de pacotes do Correios.
Módulo para consulta do rastreio de pacotes do Correios. Consulta diretamento a API do Correios (SRO).

## Instalação

Requer `Node.js` e `npm` instalados.

```sh
$ npm install --save tracking-correios
```

Depois importe no seu código:

```js
// via require do Node.js
const TrackingCorreios = require('tracking-correios')

// ou via ES6
import TrackingCorreios from 'tracking-correios'
```

## Consulta de eventos do código de rastreio

Para consultas de um único código:

```js
// passando como string
TrackingCorreios.track( 'DU897123996BR' )
.then(console.log)

// ou como Array
TrackingCorreios.track( [ 'DU897123996BR' ] )
.then(console.log)

/*
{
"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"
}, { ... }, { ... }, { ... }
]
}
*/
```

Exemplo de código válido, porém sem rastreio

Para consultas de vários códigos simultâneos:

```js
TrackingCorreios.track([ 'DU897123996BR', 'PN273603577BR', 'DU910139445BR' ])
.then(console.log)

/*
[ { numero: 'DU897123996BR',
sigla: 'DU',
nome: 'ENCOMENDA E-SEDEX',
categoria: 'E-SEDEX',
evento: [ {...}, [Object], [Object], [Object], [Object], [Object] ] },
{ numero: 'PN273603577BR',
sigla: 'PN',
nome: 'ENCOMENDA PAC (ETIQ LOGICA)',
categoria: 'ENCOMENDA PAC',
evento: [ [Object], [Object], [Object], [Object], [Object], [Object] ] },
{ numero: 'DU910139445BR',
sigla: 'DU',
nome: 'ENCOMENDA E-SEDEX',
categoria: 'E-SEDEX',
evento: [ [Object], [Object], [Object], [Object], [Object] ] } ]
*/
```

O método `track` validará automaticamente os objetos, removendo os inválidos:

```js
TrackingCorreios.track([ 'DU897123996BR', 'invalido' ])
.then(console.log)

/*
{ "numero":"DU897123996BR",
"sigla":"DU",
"nome":"ENCOMENDA E-SEDEX",
"categoria":"E-SEDEX",
"evento": [...]
}
*/
```

Se não tiver nenhum objeto válido a Promise rejeitará com `TrackingError`:

```js
TrackingCorreios.track('invalido')
.catch(console.log)

/*
{ [TrackingError: Erro ao validar os objetos.]
name: 'TrackingError',
message: 'Erro ao validar os objetos.',
type: 'validation_error',
errors:
[ { message: 'Nenhum objeto válido para pesquisa.',
service: 'objects_validation' } ] }
*/
```

O método `track` retorna uma Promise, portanto o tratamento de erros deve ser feito pelo `.catch`. Exemplo de API fora do ar:

```js
TrackingCorreios.track('DU897123996BR')
.then(console.log)
.catch(console.log)

/*
{ [TrackingError: Erro ao se conectar ao o serviço dos Correios.]
name: 'TrackingError',
message: 'Erro ao se conectar com o serviço dos Correios.',
type: 'system',
errors:
[ { message: 'Ocorreu um erro ao se conectar ao serviço dos Correios: request to https://webservice.correios.com.br/service/rastro failed, reason: connect ECONNREFUSED webservice.correios.com.br',
service: 'service_error' } ] }
*/
```

Pode também passar um objeto de configuração como segundo parâmetro.

```js
// Valores padrão:
TrackingCorreios.track('DU897123996BR', {
username: undefined,
password: undefined,
type: "L",
result: "T",
language: "101",
limit: 5000
})
```

Os parâmetros `username`, `password`, `type`, `result` e `language` serão enviados a API dos Correios.

O parâmetro `limit` indica a quantidade máxima de objetos a ser enviado por requisição. Se passar 8 mil objetos e o limite for 5 mil, o módulo fará duas requisições. Se passar mil objetos e o limite for 1, fará mil requisições.

As requisições não são paralelas, serão realizadas uma após a outra. A Promise só resolverá quando todas as requisições terminarem.

## Validação de objetos

Esse módulo expõe três métodos auxiliares para validação de objetos.

* `isValid`: verifica se o tracking é válido seguindo as regras do Correios.
* `filter`: retorna somente os objetos válidos.
* `validate`: retorna um objeto com os itens válidos e inválidos.

Exemplos:

`isValid`:

```js
TrackingCorreios.isValid('DU897123996BR')
> true

TrackingCorreios.isValid(['DU897123996BR'])
> false

TrackingCorreios.isValid('AAAAA')
> false

TrackingCorreios.isValid()
> false
```

Verifica um único objeto por vez. Valida as iniciais também com as conhecidas do correios (veja [category](#categoria-do-objeto)). Retorna um `boolean`.

------------

`filter`:

```js
TrackingCorreios.filter( 'DU897123996BR' )
> [ 'DU897123996BR' ]

TrackingCorreios.filter( [ 'DU897123996BR' ] )
> [ 'DU897123996BR' ]

TrackingCorreios.filter( [ 'DU897123996BR', 'PN273603577BR', 'DU910139445BR' ] )
> [ 'DU897123996BR', 'PN273603577BR', 'DU910139445BR' ]

TrackingCorreios.filter([ 'DU897123996BR', 'invalid' ])
> [ 'DU897123996BR' ]

TrackingCorreios.filter([ 'invalid', 'AAAA' ])
> [ ]

TrackingCorreios.filter( { } )
> [ ]
```

Sempre retornará um Array, independente se houver ou não itens válidos.

------------

`validate`:

```js
TrackingCorreios.validate( 'DU897123996BR' )
> { valid: [ 'DU897123996BR' ], invalid: [ ] }

TrackingCorreios.validate( [ 'DU897123996BR' ] )
> { valid: [ 'DU897123996BR' ], invalid: [ ] }

TrackingCorreios.validate( [ 'DU897123996BR', 'PN273603577BR', 'DU910139445BR' ] )
> {
valid: [ 'DU897123996BR', 'PN273603577BR', 'DU910139445BR' ],
invalid: [ ]
}

TrackingCorreios.validate([ 'DU897123996BR', 'invalid' ])
> {
valid: [ 'DU897123996BR' ],
invalid: [ 'invalid' ]
}

TrackingCorreios.validate([ 'invalid', 'AAAA' ])
> {
valid: [ ],
invalid: [ 'invalid', 'AAAA' ]
}

TrackingCorreios.validate( { } )
> {
valid: [ ],
invalid: [ { } ]
}
```

Sempre retornará um objeto com os campos `valid` e `invalid`.

## Categoria do Objeto

O módulo expõe um método para retornar a categoria do objeto: `category`. Exemplo:

```js
TrackingCorreios.category('DU897123996BR')
> 'e-SEDEX'

TrackingCorreios.category(['PN273603577BR'])
> 'PAC'

TrackingCorreios.category(['AA123123123BR'])
> undefined

TrackingCorreios.category('AAAAA')
> undefined

TrackingCorreios.category()
> undefined
```

Se não for um código de rastreio válido, retornará `undefined`.

# Inspiração

Arquitetura inspirada no módulo [cep-promise](https://github.com/filipedeschamps/cep-promise) de Filipe Deschamps. Queria aprender mais sobre encadeamento de Promises, funções pequenas e vários outros assuntos que ele aborda [nesse vídeo](https://www.youtube.com/watch?v=gB5Gej0O400), por isso decidi desenvolver esse módulo.
43 changes: 43 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
{
"name": "tracking-correios",
"version": "1.0.0",
"description": "Módulo para consulta do rastreio de pacotes do Correios",
"main": "dist/track.js",
"scripts": {
"test": "npm run test-unit && npm run test-e2e",
"test-e2e": "mocha tests/e2e/*.spec.js --timeout 15000",
"test-unit": "mocha tests/unit/*.spec.js",
"build": "babel src --out-dir dist",
"prepublish": "npm run build"
},
"author": "Gabriel Oliveira",
"license": "MIT",
"repository": {
"type": "git",
"url": "https://github.com/gabrielboliveira/tracking-correios.git"
},
"bugs": {
"url": "https://github.com/gabrielboliveira/tracking-correios/issues"
},
"dependencies": {
"bluebird": "^3.4.6",
"isomorphic-fetch": "^2.2.1",
"lodash.assignin": "^4.2.0",
"lodash.chunk": "^4.2.0",
"lodash.difference": "^4.5.0",
"lodash.filter": "^4.6.0",
"lodash.flatten": "^4.4.0",
"lodash.get": "^4.4.2",
"xml2js": "^0.4.17"
},
"devDependencies": {
"babel-cli": "^6.18.0",
"babel-plugin-add-module-exports": "^0.2.1",
"babel-preset-es2015": "^6.18.0",
"chai": "^3.5.0",
"chai-as-promised": "^6.0.0",
"chai-subset": "^1.3.0",
"mocha": "^3.2.0",
"nock": "^9.0.2"
}
}
11 changes: 11 additions & 0 deletions src/errors/tracking.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
function TrackingError (options = {}) {
this.name = 'TrackingError'
this.message = options.message
this.type = options.type
this.errors = options.errors
}

TrackingError.prototype = Object.create(Error.prototype)
TrackingError.prototype.constructor = TrackingError

module.exports = TrackingError
Loading

0 comments on commit 0bccd5c

Please sign in to comment.