Skip to content

Instantly share code, notes, and snippets.

@roger-dev-br
Created April 29, 2021 20:33
Show Gist options
  • Save roger-dev-br/72c1d882b0588a854a94eecd56a09a44 to your computer and use it in GitHub Desktop.
Save roger-dev-br/72c1d882b0588a854a94eecd56a09a44 to your computer and use it in GitHub Desktop.
Configuração de projeto node para utilização de Cache com REDIS

REDIS

1. Criar um pasta e inicializar o projeto

yarn init -y

2. Instalar dependencias

yarn add express cors dotenv sequelize consola sqlite3
yarn add -D nodemon sucrase sequelize-cli

3. Iniciar estrutura do projeto

- Pasta src
- Pasta src/config
    - Criar database.js
require('dotenv').config();

module.exports = {
  dialect: process.env.DB_DIALECT,
  storage: 'src/database/database.sqlite',
  define: {
    timestamp: true,
    underscored: true,
    underscoredAll: true,
  },
};
- Pasta database
    - Criar index.js
import Sequelize from 'sequelize';
import dataBaseConfig from '../config/database';

import User from '../app/models/User';
import Product from '../app/models/Product';

const models = [User, Product];

class DataBase {
  constructor() {
    this.init();
  }

  init() {
    this.connection = new Sequelize(dataBaseConfig);

    models
      .map((model) => model.init(this.connection))
      .map(
        (model) => model.associate && model.associate(this.connection.models),
      );
  }
}

export default new DataBase();
- Criar route.js
import { Router } from 'express';
import cors from 'cors';

const routes = Router();
routes.use(cors());

routes.get('/', (req, res) => res.send('<h1>🚀🚀🚀 Cache com REDIS 🚀🚀🚀</h1>'));

export default routes;
- Criar app.js
import express from 'express';
import routes from './routes';

import './database';

class App {
  constructor() {
    this.server = express();
    this.middleware();
    this.routes();
  }

  middleware() {
    this.server.use(express.json());
  }

  routes() {
    this.server.use(routes);
  }
}

export default new App().server;
- Criar server.js
import 'dotenv/config';

import app from './app';

app.listen(process.env.PORT);
- Criar scripts de execução
"dev": "nodemon src/server.js"
- Criar nodemon.json
{
  "execMap": {
    "js": "node -r sucrase/register"
  }
}
- Criar .sequelizerc
const {resolve} = require('path');

module.exports = {
  config: resolve(__dirname, 'src' , 'config', 'database.js'),
  'models-path': resolve(__dirname, 'src' , 'app', 'models'),
  'migrations-path': resolve(__dirname, 'src' , 'database', 'migrations'),
  'seeders-path': resolve(__dirname, 'src', 'database', 'seeds'),
}
- Criar models em app/models/Produto.js
import Sequelize, { Model } from 'sequelize';

class Produto extends Model {
    static init(sequelize) {
        super.init({
            id: {
                type: Sequelize.INTEGER,
                autoIncrement: true,
                primaryKey: true
            },
            nome: {
                type: Sequelize.STRING(100),
                allowNull: false
            },
            preco: {
                type: Sequelize.DECIMAL(15, 2),
                allowNull: false
            },
            disponivel: {
                type: Sequelize.BOOLEAN,
                defaultValue: true,
            },
        },{
            sequelize            
        });

        return this;
    }
}

export default Produto;
- Criar migration 
yarn sequelize migration:generate --name tab-produto
- Criar seeds
yarn sequelize seed:generate --name produtos
- Rodar seeds
yarn sequelize db:seed:all
- Adicionar o Model Produto no Database
import Sequelize from 'sequelize';
import Produto from '../app/models/Produto';
import dataBaseConfig from '../config/database';

const models = [
  Produto
];

class DataBase {
  constructor() {
    this.init();
  }

  init() {
    this.connection = new Sequelize(dataBaseConfig);

    models
      .map((model) => model.init(this.connection))
      .map(
        (model) => model.associate && model.associate(this.connection.models),
      );
  }
}

export default new DataBase();

3. Controller de Produtos

- Criar app/controllers/ProdutoController.js
import Produto from '../models/Produto';

class ProdutoController {
    async index(req, res) {
        try {
            const produtos = await Produto.findAll({
                attributes: ['id', 'nome', 'preco', 'disponivel'],
            });

            return res.status(200).json({
                data: produtos,
                cache: false,
            });
        } catch (error) {
            return res.status(500).json({ msg: error.message ?? error });
        }
    }
}

export default new ProdutoController();
- Criar rota para os produtos
import { Router } from 'express';
import cors from 'cors';
import ProdutosController from './app/controllers/ProdutoController';

const routes = Router();
routes.use(cors());

routes.get('/', (req, res) => res.send('<h1>🚀🚀🚀 Cache com REDIS 🚀🚀🚀</h1>'));

routes.get(
    '/produtos',
    ProdutosController.index,
);

export default routes;

4. Redis

- Instalar dependencias
yarn add redis bluebird
- Criar src/lib/Cache.js
import redis from 'redis';
import Promise from 'bluebird';
import * as consola from 'consola';

Promise.promisifyAll(redis);

class Cache {
  constructor() {
    this.client = redis.createClient(process.env.REDIS_URL);
    /*
    this.client = redis.createClient(process.env.REDIS_URL, {
      tls: {
        rejectUnauthorized: true,
      },
    });
    */

    this.client.monitor(() => {
      consola.success('Entering monitoring mode.');
    });

    this.client.on('monitor', (time, args) => {
      consola.info(`(monitor redis): ${time}:${args}`);
    });
  }

  get(key) {
    return this.client.getAsync(key);
  }

  set(key, data) {
    return this.client.setAsync(key, data);
  }

  async setExpire(key, data, ttl) {
    const response = await this.set(key, data);
    await this.client.expireAsync(key, ttl);

    return response;
  }

  hincrby(hash, key, data) {
    return this.client.hincrbyAsync(hash, key, data);
  }

  smembers(key) {
    return this.client.smembersAsync(key);
  }

  sadd(key, data) {
    return this.client.saddAsync(key, data);
  }

  srem(key, data) {
    return this.client.sremAsync(key, data);
  }

  delete(key) {
    return this.client.del(key);
  }
}

export default new Cache();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment