Skip to content

Instantly share code, notes, and snippets.

@carboleda
Last active February 8, 2019 14:09
Show Gist options
  • Save carboleda/2343ba714216fd3f0a42c50e8806d37c to your computer and use it in GitHub Desktop.
Save carboleda/2343ba714216fd3f0a42c50e8806d37c to your computer and use it in GitHub Desktop.
Conexión a base de datos usando mysql2
const mysql = require('mysql2');
let pool;
module.exports = {
getPoolConnection
}
function getPoolConnection() {
if(!pool) {
pool = mysql.createPool({
host: 'localhost',
user: 'root',
password: 'root',
database: 'db_posts',
waitForConnections: true,
connectionLimit: 10,
queueLimit: 0
});
}
return pool;
}
const db = require('./src/db');
async function getAuthorById(id) {
const pool = db.getPoolConnection();
const [ results, fields ] = await pool.promise().query('select * from authors where id = ?', [ id ]);
console.log('getAuthorById', results);
}
async function getAuthorAndPosts(idAuthor) {
const pool = db.getPoolConnection();
let [ authors, fields ] = await pool.promise().query('select * from authors where id = ?', [ idAuthor ]);
authorsPromise = authors.map(async (author) => {
console.log('author', author);
const [posts, fields] = await pool.promise().query('select * from posts where author_id = ?', [ author.id ]);
//console.log('posts', posts);
author.posts = posts;
return author;
});
//console.log('authors', authors);
Promise.all(authorsPromise)
.then((authors) => {
console.log('getAuthorAndPosts', authors);
});
}
getAuthorById(1);
getAuthorAndPosts(1);
'use strict'
const db = require('./src/db');
const pool = db.getPoolConnection();
async function getAuthorById(id) {
const [ results, fields ] = await pool.promise().query('select * from authors where id = ?', [ id ]);
console.log('getAuthorById', results);
}
async function getAuthorAndPosts(idAuthor) {
let [ authors, fields ] = await pool.promise().query('select * from authors where id = ?', [ idAuthor ]);
const authorsPromise = authors.map(async (author) => {
console.log('author', author);
const [posts, fields] = await pool.promise().query('select * from posts where author_id = ?', [ author.id ]);
//console.log('posts', posts);
author.posts = posts;
return author;
});
//console.log('authors', authors);
return Promise.all(authorsPromise)
/*.then((authors) => {
console.log('getAuthorAndPosts', authors);
});*/
}
getAuthorById(1)
.then(() => {
return getAuthorAndPosts(1);
})
.then(() => {
console.log('termino 1');
pool.end(function (err) {
// all connections in the pool have ended
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment