5.0.1 • Published 3 years ago

@smn-official/node.helpers v5.0.1

Weekly downloads
-
License
ISC
Repository
github
Last release
3 years ago

NODE HELPERS

Version v5.0.0

Node >= v.10

 > npm i @smn-official/node.helpers
helpers = require('@smn-official/node.helpers');

#----------------------------------------------------------------------

CLUSTER

const Cluster = new helpers.Cluster({
    cpus: 2, // Quantidade de processadores 
    isProduction: false, //Variavel indicar com aplicação estiver em produção
    maxTentativas: 4, // Maximo de tentativas para subir a aplicação
    clusterError: (worker)=>{}; // função executada caso acabe as tentativas de subir a aplicação
});

Cluster.init();     //Iniciar a aplicação
Cluster.started();  //Se iniciar com sucesso

#----------------------------------------------------------------------

CRYPT

const Crypt = new helpers.crypt.Blowfish('key');

Crypt.encrypt(value);
Crypt.decrypt(value);

#----------------------------------------------------------------------

SETTINGS

Config

  • Objeto para parâmetros da aplicação
const Settings = new helpers.Settings({
    //atributos
});
//Acessar os parâmetros
Settings.?;

Métodos

//Merge Settings.config com objetos passados
Settings.$assign({},...);

//Retorna true ou false para valor passado
Settings.$idObject({});

//Merge Settings.config com config local caso nâo produção
Settings.$devSettings('./config/environment/localSettings.js');

// Retorna -> porta setada em Settings.port OU Settings.api.nomeApi.port
Settings.$port 

// Retorna -> host setado em Settings.host OU Settings.api.nomeApi.host
Settings.$host 

// Retorna -> $host + $port + '/'
Settings.$url 

#----------------------------------------------------------------------

DATE

RETURN STRING

helpers.Date.short      // 00/00/0000
helpers.Date.shortTime  // 00/00/0000 24:00:00
helpers.Date.long       // November 19th 2017, 20:46:06
helpers.Date.dayWeek    // Domingo

RETURN DATE

helpers.Date.now        // new Date()

MÉTODOS

helpers.Date.dateDiff(new Date(2000, 2, 1));                                // 17 'anos'
helpers.Date.dateDiff(new Date(2000, 2, 1), 'm');                           // 231 'meses'
helpers.Date.dateDiff(new Date(2000, 2, 1), new Date(2005, 2, 1));          // 5 'anos'
helpers.Date.dateDiff(new Date(2000, 2, 1), new Date(2005, 2, 1), 'd');     // 1826 dias
//--
helpers.Date.addDay(dias, date);        // Quantidade de dias = 1, date = new Date()
helpers.Date.addMonth(meses, date);     // Quantidade de meses = 1, date = new Date()
helpers.Date.addYear(anos, date);       // Quantidade de anos = 1, date = new Date()

#----------------------------------------------------------------------

FORMAT

MÉTODOS

helpers.Format.money(value, currency)                   //  R$ 0,00
helpers.Format.cpfCnpj(value)                           //  000.000.000-00 OR 00.000.000/0000-00
helpers.Format.rg(value)                                //  00.000.000-0
helpers.Format.telefone(numero, ddd, parentese)         //  00 00000-0000 OR (00) 0000-0000            
helpers.Format.cep(value)                               //  00000-000
helpers.Format.porcentagem(value)                       //  0% , 0,00% 
helpers.Format.date(date, format /* Opcional */)        //  Default - dd/MM/yyyy
 

EMAIL

Config

email = helpers.email({
    host : "host",
    port : 587,
    auth : {
        user : "user email",
        pass : "password",
        name: 'nome'
    },
    logger : false,
    secure : false
});

USE

const Email = email({
    from: '', // Opcional --> default config.auth.user
    to: '',
    subject: '',
    text: '',
    html: ''
});

await Email
    .attachment('logo.png', './src/resources', 'logo')              // Add cid
    .attachment('doc.txt', 'src/resources')                         // Add anexo
    .attachment('data:text/plain;base64,aGVw12sbGda8gd29dswybGQ=')  // Add Base64
    .send();

#----------------------------------------------------------------------

EXCEL

Config

const Excel = new helpers.Excel({
    headers: ['Nome', 'E-mail', 'Telefone', 'Celular'],
    rowsName: ['nome', 'email', 'telefone', 'celular'],
    rows: {
        "nome": "Thiago Moreira",
        "email": "email@email.net",
        "telefone": "(47) 3565-4587",
        "celular": "(47) 99231-2600",
    },
    root: './caminho',
    fileName: 'excel.xlsx',
    planName: 'sheet1' /* Opcional */,
    widthCols: [30, 40, 20, null, 15, 15, 15, 15]
});

USE

await Excel.build(); //Gerar excel

#----------------------------------------------------------------------

FILE

Config

const File = new helpers.File('filename.txt', '/src/resources');

Métodos

File.upload(file);
File.remove();
File.get(encoding /* Opcional */);
File.base64ToFile(base64); // Convert base64 para file
File.uploadImgBase64(imagem, extensao /* Opcional -> override extensão do base64 */);
File.base64Prepare(base64); // Prepara o base64 para a conversão.

Path

File._fullPath; // Retorna caminho completo com filename
File._path; // Retorna caminho diretório

#----------------------------------------------------------------------

CORS

  • MIDDLEWARE *

SET

  • Set function finish no 'res'
  • Recebe objeto contendo statusCode para informar status da resposta
app.use(helpers.cors())

/*
    res.finish = (response, noNext) => {
        res.status(response.statusCode).json(response);
        if (!noNext) next();
    };
*/

Override FINISH

  • Set função excutada dentro do cors
app.use(helpers.cors((req,res,next)=>{
    res.finish = (response, noNext) => {
        res.status(response.statusCode).json(response);
        if (!noNext) next();
    };
}));

#----------------------------------------------------------------------

RESPONSE

Config

Response = new helpers.Response();

Métodos

let Error = new Response.Error(message, content, status /* Opcional default = 500 */);
let Success = new Response.Ok(content, status /* Opcional default = 200 */);
let Scope = new Response.Scope(content, status /* Opcional default = 400 */);

Scope

let Scope = new Response.Scope(content, status /* Opcional default = 400 */);

Scope.validate(object)
    .field('atributo')
    .isNotEmpty()
    .isNotNull()
    .length(max, min /* OPCIONAL */)
    .isEmail()
    .isInt()
    .isNumber()
    .maxValue(value)
    .minValue(value)
    .equals(compare, message)
    .isCpf()
    .isCnpj()
    .end();

Scope.isSuccess // true OR false.
Scope.get // return objeto error {messages,statusCode,content,isSuccess}

Scope.end() // True OR False throw exception passando Scope.get
Scope.addMessage(campo, error, value);
Scope.addContent(content);

// Scope Mensagem retorno format

messages = {
    nome: { 
        required: true
    },
    email: {
        maxLength: true
    }
}

Padrão StatusCode Api Return

SCOPE
    * 400 -	dados inválidos.
SUCCESS
    * 200 - Ok	
    * 204 - Usuario/dados nao encontrado 
ERROR
    * 401 - inválido(nao autorizado).
    * 402 - usuario expirado
    * 404 - Erros de rota - caminha não encontrados.
    * 409 - Conflito

    * 502 - Erro na comunicação com api.
    * 502/500 - Erro na comunicação com banco de dados.(conexao/execucao)
    * 500 - Erro ao executar metodos/funcionalidades.	 

#----------------------------------------------------------------------

EXCEPTION

helpers.exception('message', 500 /* STATUS OPCIONAL - default 500 */, {} /* CONTENT OPCIONAL*/)
// throw interno.

#----------------------------------------------------------------------

MIDDLEWARE

Error

const errors = helpers.middleware.error;

// Tratar requisição não finalizada     -  next()
app.use(errors.notfound);
// Tratar requisição passando parâmetro -  next('error')
app.use(errors.serverError);

Response

// Gerar funções para finalizar requisição
app.use(helpers.middleware.response);

res.ok(content, status /* DEFAULT 200 */);
res.error(message, content, status /* DEFAULT 500 */);
res.finish(response);
res.default(status, content);

#----------------------------------------------------------------------