Skip to content

Commit

Permalink
1.0.0
Browse files Browse the repository at this point in the history
  • Loading branch information
andremarquezz committed Jul 12, 2024
1 parent 7bb0ef2 commit d1a6d28
Show file tree
Hide file tree
Showing 5 changed files with 2,192 additions and 107 deletions.
30 changes: 30 additions & 0 deletions .github/workflows/cy.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
name: Continuous Integration

on:
push:
branches:
- main
pull_request:
branches:
- main

jobs:
test:
runs-on: ubuntu-latest
strategy:
matrix:
node-version: [20.x]

steps:
- uses: actions/checkout@v4
- name: Use Node.js ${{ matrix.node-version }}
uses: actions/setup-node@v3
with:
node-version: ${{ matrix.node-version }}
cache: 'npm'

- name: Install dependencies
run: npm install

- name: Run Cypress tests
run: npm run test:headless
87 changes: 86 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
@@ -1 +1,86 @@
# fakerBankBR
<div align="center">
<img src="https://images.squarespace-cdn.com/content/v1/603a992bcf34a07d765e1085/1f51c872-40a9-4dfe-8d3e-c8868e05f2d7/16247556_9729.jpg" width="200"/>
<h1>FakerBankBR</h1>
<p>FakerBankBR é uma biblioteca que permite a geração de dados falsos, porém realistas, de contas bancárias brasileiras. É ideal para testes e desenvolvimento de aplicações que requerem dados bancários fictícios.</p>

[![npm version](https://badgen.net/npm/v/fakerbankbr)](https://www.npmjs.com/package/fakerbankbr)

</div>

## 📦Instalação

Para usar o FakerBankBR, você pode instalá-lo via npm:

```bash
npm install --save-dev fakerbankbr
```

## 🪄Uso

```javascript
const { createFakeBankAccount } = require('fakerbankbr');

// Gerar uma única conta bancária
createFakeBankAccount().then((conta) => {
//utilização
});

// Gerar múltiplas contas bancárias (de 1 a 10)
createFakeBankAccount(5).then((contas) => {
//utilização
});
```

### Exemplo de Resposta

#### Quando é gerada uma única conta:

```json
{
"account_number": "123456",
"verification_digit": "7",
"agency": "1234",
"bank": "Banco do Brasil"
}
```

#### Quando são geradas múltiplas contas:

```json
[
{
"account_number": "123456",
"verification_digit": "7",
"agency": "1234",
"bank": "Banco do Brasil"
},
{
"account_number": "654321",
"verification_digit": "9",
"agency": "5678",
"bank": "Santander"
},
{
"account_number": "987654",
"verification_digit": "2",
"agency": "9012",
"bank": "Bradesco"
}
]
```

## API

### `createFakeBankAccount(quantity)`

- `quantity`: (Opcional) Número de contas bancárias a serem geradas. O padrão é **1 e o máximo é 10**.

Retorna uma promise que resolve com um objeto de conta bancária ou um array de objetos de conta bancária, dependendo do parâmetro `quantity`.

## Créditos

- Esta biblioteca utiliza o site do 4Devs para gerar informações falsas de contas bancárias brasileiras.

## Licença

Este projeto é licenciado sob a Licença MIT - veja o arquivo [LICENSE](LICENSE) para mais detalhes.
176 changes: 96 additions & 80 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,15 +4,14 @@ const querystring = require('querystring');
const cheerio = require('cheerio');
const httpcodes = require('./codes.json');

exports.createFakeBankAccount = (quantity = '1', commas = 'N') => {
exports.createFakeBankAccount = (quantity = 1) => {
return new Promise((resolve, reject) => {
if (quantity > 10) {
quantity = '10';
quantity = 10;
}

let body = querystring.stringify({
acao: 'gerar_conta_bancaria',
pontuacao: commas,
txt_qtde: quantity,
});

Expand All @@ -30,92 +29,109 @@ exports.createFakeBankAccount = (quantity = '1', commas = 'N') => {
};

try {
let data = '';

const req = https.request(options, function (res) {
let response = {
error: true,
code: res.statusCode,
explain: httpcodes[res.statusCode],
headers: res.headers,
date: new Date().toLocaleString(),
error_msg: null,
dev_msg: null,
data: null,
};

res.on('data', function (chunk) {
data += chunk;
});
const requests = [];

req.on('error', function (err) {
response.error = true;
response.code = err.code;
response.error_msg = err.message;
reject(response);
});
for (let i = 0; i < quantity; i++) {
requests.push(makeRequest(options, body));
}

res.on('end', function () {
try {
if (data.trim().startsWith('<')) {
const $ = cheerio.load(data);

let conta_corrente_completa = $('#conta_corrente').text().trim();
let conta_corrente = conta_corrente_completa.split('-')[0];
let digito_verificador = conta_corrente_completa.split('-')[1];

let extractedData = {
account_number: conta_corrente,
verification_digit: digito_verificador,
agency: $('#agencia').text().trim(),
bank: $('#banco').text().trim(),
};

response.error = false;
response.data = extractedData;
resolve(response.data);
} else {
let Four_Devs = JSON.parse(data);

if (response.code !== 200 || !Four_Devs) {
response.error = true;
response.dev_msg =
'Talvez você tenha sido bloqueado pelo servidor. Certifique-se de que não está usando proxy ou algo similar e tente em outra máquina.';
Promise.all(requests)
.then((responses) => {
let accounts = [];

responses.forEach((response) => {
if (!response.error && response.data) {
if (Array.isArray(response.data)) {
accounts = accounts.concat(response.data);
} else {
response.error = false;
response.data = Four_Devs;
accounts.push(response.data);
}
resolve(response.data);
}
} catch (error) {
response.error = true;
response.error_msg =
'Erro ao analisar a resposta JSON: ' + error.message;
reject(response);
});

// Determine what to return based on quantity
if (quantity === 1) {
resolve(accounts.length > 0 ? accounts[0] : null);
} else {
resolve(accounts);
}
})
.catch((error) => {
reject(error);
});
} catch (error) {
reject(error);
}
});
};

function makeRequest(options, body) {
return new Promise((resolve, reject) => {
let data = '';

const req = https.request(options, function (res) {
res.on('data', function (chunk) {
data += chunk;
});

req.on('error', function (err) {
let response = {
error: true,
code: err.code,
error_msg: err.message,
data: null,
};
reject(response);
res.on('end', function () {
try {
let response = parseResponse(res, data);
resolve(response);
} catch (error) {
reject(error);
}
});
});

req.write(body);
req.end();
} catch (error) {
let response = {
error: true,
code: error.code,
error_msg: error.message,
data: null,
};
reject(response);
}
req.on('error', function (err) {
reject(err);
});

req.write(body);
req.end();
});
};
}

function parseResponse(res, data) {
let response = {
error: true,
code: res.statusCode,
explain: httpcodes[res.statusCode],
headers: res.headers,
date: new Date().toLocaleString(),
error_msg: null,
dev_msg: null,
data: null,
};

if (data.trim().startsWith('<')) {
const $ = cheerio.load(data);

let full_account_number = $('#conta_corrente').text().trim();
let account_number = full_account_number.split('-')[0];
let verification_digit = full_account_number.split('-')[1];

let extractedData = {
account_number: account_number,
verification_digit: verification_digit,
agency: $('#agencia').text().trim(),
bank: $('#banco').text().trim(),
};

response.error = false;
response.data = extractedData;
} else {
let Four_Devs = JSON.parse(data);

if (res.statusCode !== 200 || !Four_Devs) {
response.dev_msg =
'You may have been blocked by the server. Make sure you are not using a proxy or something similar and try on another machine.';
} else {
response.error = false;
response.data = Four_Devs;
}
}

return response;
}
Loading

0 comments on commit d1a6d28

Please sign in to comment.