Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- 'use strict';
- const mysql = require('mysql');
- const Q = {
- 'GET_USER': 'SELECT username, password FROM users WHERE username = ?',
- 'ADD_USER': 'INSERT INTO users (username, password) VALUES (?, ?)'
- };
- const E = {
- 'BAD_ADD': 'An error occured when adding your credentials to the database.',
- 'BAD_VALIDATION': 'An error occured when validating your credentials.',
- 'WRONG_CREDENTIALS': 'Your username or password was wrong.'
- };
- const pool = mysql.createPool({
- connectionLimit: 20,
- host: 'localhost',
- user: 'developer',
- password: 'developer',
- database: 'chat-app'
- });
- function query(query, args) {
- return new Promise((resolve, reject) => {
- pool.query(query, args, (err, res) => {
- if (err) return reject(err);
- return resolve(res);
- });
- });
- }
- exports.addUser = (user, cb) => {
- query(Q.ADD_USER, [user.username, user.password])
- .then(resultSet => cb(null, resultSet))
- .catch(error => cb(E.BAD_ADD, null));
- }
- exports.validateUser = (user, cb) => {
- query(Q.GET_USER, [user.username])
- .then(resultSet => {
- if (user.password === resultSet[0].password) return cb(null, true);
- return cb(E.WRONG_CREDENTIALS, false);
- })
- .catch(error => cb(E.BAD_VALIDATION, null));
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement