mercredi 17 janvier 2018

Clean CRUD Implementation with Nodejs using MySQL

I'm really new to Nodejs. I'm trying to write some "clean" code with it. I'm using MySQL as my database.

I would like to use MVC as my design pattern. Currently I would like to implement the "User" as CRUD. I don't like that all my code is in app.ts I don't use some mappers or something else just "normal" SQL queries.

    import express = require('express')
    import bodyParser = require('body-parser')
    import db      = require('mysql')
    import session = require('express-session')
    import {Connection, MysqlError} from "mysql"

    let connection: Connection = db.createConnection({
      host: 'localhost',
      user: 'admin',
      password: 'secret',
      database: 'test'
    });

var app = express();

app.use('/views', express.static(__dirname + '/views'))
app.use('/public', express.static(__dirname + '/public'))


app.use(bodyParser.urlencoded({ extended: false }))
app.use(bodyParser.json());

app.get('/', function (req, res) {
  connection.connect(function(err) {
    if (err) {
      console.error('error connecting: ' + err.stack);
      return;
    }

    console.log('connected as id ' + connection.threadId);
  });
});

app.listen(8080, function () {
  console.log('Listening on port 8080!');
  console.log('____________________________________')
  console.log('____________________________________')
  console.log('____________________________________')
  console.log("PLEASE VISIT ➡️ ➡️ ➡️ ➡️   http://localhost:8080/views/index.html   ⬅️ ⬅️ ⬅️ ⬅️")
  console.log('____________________________________')
});

Normally the connection should be in the model right? How I can use the controllers and the models? How I can use them in my app.js ? Thank you so much for your help I really appreciate it.

Aucun commentaire:

Enregistrer un commentaire