From 1c1a18a5e2cad58ea020367179f1fcb82365095b Mon Sep 17 00:00:00 2001 From: Kamynale Date: Wed, 2 Sep 2020 19:40:05 +0300 Subject: [PATCH 1/4] mysql with pool --- server/app.js | 49 +++++++++++++++++++++++-------------------------- 1 file changed, 23 insertions(+), 26 deletions(-) diff --git a/server/app.js b/server/app.js index 51b26ef..f9a2387 100644 --- a/server/app.js +++ b/server/app.js @@ -7,8 +7,8 @@ const bodyParser = require('body-parser'); const mysql = require('mysql'); const fs = require('fs'); const path = require('path'); -const config = require('./config'); const params = require('express-route-params'); +const config = require('./config'); const app = express(); params(express); @@ -38,29 +38,28 @@ config.facebook_api_key = '2640133479605924'; // let HOSTNAME = 'https://opexflow.com'; passport.use(new FacebookStrategy({ - clientID: config.facebook_api_key, - clientSecret: config.facebook_api_secret, - callbackURL: config.callback_url, - profileFields: ['id', 'displayName', 'name', 'gender', 'profileUrl', 'emails', 'photos'] - }, - ((accessToken, refreshToken, profile, done) => { - process.nextTick(() => { - console.log(profile); - if (profile && profile.id) { - const photo = profile.photos && profile.photos[0] && profile.photos[0].value || ''; - const email = profile.emails && profile.emails[0] && profile.emails[0].value || ''; - - pool.query(`INSERT INTO Users SET + clientID: config.facebook_api_key, + clientSecret: config.facebook_api_secret, + callbackURL: config.callback_url, + profileFields: ['id', 'displayName', 'name', 'gender', 'profileUrl', 'emails', 'photos'], +}, +((accessToken, refreshToken, profile, done) => { + process.nextTick(() => { + console.log(profile); + if (profile && profile.id) { + const photo = profile.photos && profile.photos[0] && profile.photos[0].value || ''; + const email = profile.emails && profile.emails[0] && profile.emails[0].value || ''; + + pool.query(`INSERT INTO Users SET id = '${profile.id}', login = '${profile.displayName}', email = '${email}', photo='${photo}', createdAt = NOW(), balance = 10000 ON DUPLICATE KEY UPDATE login = '${profile.displayName}', email = '${email}', photo='${photo}' `); - profile.accessToken = accessToken; - } - return done(null, profile); - }); - })) -); + profile.accessToken = accessToken; + } + return done(null, profile); + }); +}))); // app.set('views', __dirname + '/views'); // app.set('view engine', 'ejs'); @@ -95,7 +94,6 @@ app.get('/', (req, res) => { } }); - app.get('/api/account', (req, res) => { res.setHeader('Content-Type', 'application/json'); res.setHeader('Access-Control-Allow-Origin', replaceHost(HOSTNAME)); @@ -109,8 +107,8 @@ app.get('/api/account', (req, res) => { } pool.query(`SELECT * from Users where id=${req.user.id}`, (err, rows) => { - res.end(JSON.stringify({ user: req.user, finance: { balance: rows && rows[0] && rows[0].balance }})); - }) + res.end(JSON.stringify({ user: req.user, finance: { balance: rows && rows[0] && rows[0].balance } })); + }); }); app.get('/api/account/:id', (req, res) => { @@ -136,8 +134,7 @@ app.get('/api/logout', (req, res) => { return res.end('{}'); }); - -app.param('tick', /^\d+(min|h|d|m)$/i) +app.param('tick', /^\d+(min|h|d|m)$/i); // ========= Работа с тиками ========== app.get('/api/stocks/ticks/:tick', ensureAuthenticated, (req, res) => { @@ -170,7 +167,7 @@ app.get('/api/stocks/ticks/:tick', ensureAuthenticated, (req, res) => { return res.end(JSON.stringify(ticks)); }); -app.param('price', /^\d+\.?\d*$/i) +app.param('price', /^\d+\.?\d*$/i); // ========= Работа с тиками ========== app.get('/api/stocks/trades/buy/:price', ensureAuthenticated, (req, res) => { From 8cfa42844b9ae193230052b43417c60e4bfad4ba Mon Sep 17 00:00:00 2001 From: Kamynale Date: Thu, 3 Sep 2020 17:49:23 +0300 Subject: [PATCH 2/4] mysql with pool --- server/app.js | 184 +++++++++++++++++++++++++++++++++++++++++--------- 1 file changed, 151 insertions(+), 33 deletions(-) diff --git a/server/app.js b/server/app.js index f9a2387..6fddc67 100644 --- a/server/app.js +++ b/server/app.js @@ -7,8 +7,8 @@ const bodyParser = require('body-parser'); const mysql = require('mysql'); const fs = require('fs'); const path = require('path'); -const params = require('express-route-params'); const config = require('./config'); +const params = require('express-route-params'); const app = express(); params(express); @@ -38,28 +38,52 @@ config.facebook_api_key = '2640133479605924'; // let HOSTNAME = 'https://opexflow.com'; passport.use(new FacebookStrategy({ - clientID: config.facebook_api_key, - clientSecret: config.facebook_api_secret, - callbackURL: config.callback_url, - profileFields: ['id', 'displayName', 'name', 'gender', 'profileUrl', 'emails', 'photos'], -}, -((accessToken, refreshToken, profile, done) => { - process.nextTick(() => { - console.log(profile); - if (profile && profile.id) { - const photo = profile.photos && profile.photos[0] && profile.photos[0].value || ''; - const email = profile.emails && profile.emails[0] && profile.emails[0].value || ''; - - pool.query(`INSERT INTO Users SET - id = '${profile.id}', login = '${profile.displayName}', email = '${email}', photo='${photo}', createdAt = NOW(), balance = 10000 - ON DUPLICATE KEY UPDATE login = '${profile.displayName}', email = '${email}', photo='${photo}' - `); - - profile.accessToken = accessToken; - } - return done(null, profile); - }); -}))); + clientID: config.facebook_api_key, + clientSecret: config.facebook_api_secret, + callbackURL: config.callback_url, + profileFields: ['id', 'displayName', 'name', 'gender', 'profileUrl', 'emails', 'photos'] + }, + ((accessToken, refreshToken, profile, done) => { + process.nextTick(() => { + console.log(profile); + if (profile && profile.id) { + const photo = profile.photos && profile.photos[0] && profile.photos[0].value || ''; + const email = profile.emails && profile.emails[0] && profile.emails[0].value || ''; + + pool.query(`SELECT * from Users where id=${profile.id}`, (err, rows) => { + if (err) throw err; + if (rows && rows.length === 0) { + console.log('There is no such user, adding now'); + pool.query(`INSERT INTO Users SET + id = '${profile.id}', login = '${profile.displayName}', email = '${email}', photo='${photo}', createdAt = NOW(), balance = 10000 + ON DUPLICATE KEY UPDATE login = '${profile.displayName}', email = '${email}', photo='${photo}' + `); + } else { + console.log('User already exists in database'); + } + }); + + pool.query(`SELECT * from Transactions where id='${profile.id}'`, (err, rows) => { + if (err) throw err; + if (rows && rows.length === 0) { + console.log('There is no balance User in Transaction, adding now'); + pool.query(`INSERT INTO Transactions SET + id = '${profile.id}', login = '${profile.displayName}' + ON DUPLICATE KEY UPDATE login = '${profile.displayName}' + `); + } else { + console.log('Balance for User already exists in database'); + } + }); + + profile.accessToken = accessToken; + } + return done(null, profile); + }); + })) +); + + // app.set('views', __dirname + '/views'); // app.set('view engine', 'ejs'); @@ -94,6 +118,7 @@ app.get('/', (req, res) => { } }); + app.get('/api/account', (req, res) => { res.setHeader('Content-Type', 'application/json'); res.setHeader('Access-Control-Allow-Origin', replaceHost(HOSTNAME)); @@ -106,9 +131,12 @@ app.get('/api/account', (req, res) => { return res.end('{}'); } - pool.query(`SELECT * from Users where id=${req.user.id}`, (err, rows) => { - res.end(JSON.stringify({ user: req.user, finance: { balance: rows && rows[0] && rows[0].balance } })); - }); + /*pool.query(`SELECT * from Users where id=${req.user.id}`, (err, rows) => { + res.end(JSON.stringify({ user: req.user, finance: { balance: rows && rows[0] && rows[0].balance }})); + })*/ + pool.query(`SELECT * from Transactions where id=${req.user.id}`, (err, rows) => { + res.end(JSON.stringify({ user: req.user, finance: { balance: rows && rows[0] && rows[0].balance }})); + }) }); app.get('/api/account/:id', (req, res) => { @@ -134,7 +162,8 @@ app.get('/api/logout', (req, res) => { return res.end('{}'); }); -app.param('tick', /^\d+(min|h|d|m)$/i); + +app.param('tick', /^\d+(min|h|d|m)$/i) // ========= Работа с тиками ========== app.get('/api/stocks/ticks/:tick', ensureAuthenticated, (req, res) => { @@ -167,7 +196,7 @@ app.get('/api/stocks/ticks/:tick', ensureAuthenticated, (req, res) => { return res.end(JSON.stringify(ticks)); }); -app.param('price', /^\d+\.?\d*$/i); +app.param('price', /^\d+\.?\d*$/i) // ========= Работа с тиками ========== app.get('/api/stocks/trades/buy/:price', ensureAuthenticated, (req, res) => { @@ -182,10 +211,55 @@ app.get('/api/stocks/trades/buy/:price', ensureAuthenticated, (req, res) => { return res.end('{}'); } - pool.query(`UPDATE Users SET balance = balance - '${req.params.price}' WHERE id = '${req.user.id}'`); - return res.end(JSON.stringify({})); + const sql = `SELECT balance FROM Transactions WHERE id='${req.user.id}' AND balance>=${req.params.price}`; + const transaction = `UPDATE Transactions Set balance = balance - ${req.params.price} WHERE id='${req.user.id}'` + + pool.getConnection(function (err, connection) { + + connection.query(sql, (err, results) => { + if (err) throw err; + if (results && results.length === 0) { + connection.release(); + console.log('Not enough money'); + } else { + connection.beginTransaction(function (err) { + if (err) { //Transaction Error (Rollback and release connection) + connection.rollback(function () { + connection.release(); + console.log('connection is lost') + //Failure + }); + } else { + connection.query(transaction, function (err, results) { + if (err) { //Query Error (Rollback and release connection) + connection.rollback(function () { + connection.release(); + console.log('no money'); + }); + } else { + connection.commit(function (err) { + if (err) { + connection.rollback(function () { + connection.release(); + console.log('lost!'); + }); + } else { + connection.release(); + console.log(`'balance update - '${req.params.price}`); + console.log('success!'); + + } + }); + } + }); + } + }); + } + }); + }); }); + app.get('/api/stocks/trades/sell/:price', ensureAuthenticated, (req, res) => { // TODO: сделать общее решение для локальной разработки. res.setHeader('Content-Type', 'application/json'); @@ -197,9 +271,50 @@ app.get('/api/stocks/trades/sell/:price', ensureAuthenticated, (req, res) => { if (!req.isAuthenticated() || !req.user || !req.user.id) { return res.end('{}'); } - - pool.query(`UPDATE Users SET balance = balance + '${req.params.price}' WHERE id = '${req.user.id}'`); - return res.end(JSON.stringify({})); + const sql = `SELECT id FROM Transactions WHERE id='${req.user.id}'`; + const transaction = `UPDATE Transactions Set balance = balance + ${req.params.price} WHERE id='${req.user.id}'` + + pool.getConnection(function (err, connection) { + connection.query(sql, (err, results) => { + if (err) throw err; + if (results && results.length === 0) { + connection.release(); + console.log('Not enough money'); + } else { + connection.beginTransaction(function (err) { + if (err) { //Transaction Error (Rollback and release connection) + connection.rollback(function () { + connection.release(); + console.log('connection is lost') + //Failure + }); + } else { + connection.query(transaction, function (err, results) { + if (err) { //Query Error (Rollback and release connection) + connection.rollback(function () { + connection.release(); + console.log('no money'); + }); + } else { + connection.commit(function (err) { + if (err) { + connection.rollback(function () { + connection.release(); + console.log('lost!'); + }); + } else { + connection.release(); + console.log(`'balance update + '${req.params.price}`) + console.log('success!'); + } + }); + } + }); + } + }); + } + }) + }) }); function ensureAuthenticated(req, res, next) { @@ -208,4 +323,7 @@ function ensureAuthenticated(req, res, next) { return next(); } +// Transaction + + app.listen(3001); From b71304846984d25f2e380c95c1c6b005cd8f4e6b Mon Sep 17 00:00:00 2001 From: Kamynale Date: Fri, 4 Sep 2020 16:26:27 +0300 Subject: [PATCH 3/4] bd with logs --- server/app.js | 39 +++++++++++++++++++++++---------------- 1 file changed, 23 insertions(+), 16 deletions(-) diff --git a/server/app.js b/server/app.js index 6fddc67..91807e7 100644 --- a/server/app.js +++ b/server/app.js @@ -68,9 +68,9 @@ passport.use(new FacebookStrategy({ if (rows && rows.length === 0) { console.log('There is no balance User in Transaction, adding now'); pool.query(`INSERT INTO Transactions SET - id = '${profile.id}', login = '${profile.displayName}' - ON DUPLICATE KEY UPDATE login = '${profile.displayName}' - `); + id = '${profile.id}', login = '${profile.displayName}' + ON DUPLICATE KEY UPDATE login = '${profile.displayName}' + `); } else { console.log('Balance for User already exists in database'); } @@ -131,10 +131,10 @@ app.get('/api/account', (req, res) => { return res.end('{}'); } - /*pool.query(`SELECT * from Users where id=${req.user.id}`, (err, rows) => { - res.end(JSON.stringify({ user: req.user, finance: { balance: rows && rows[0] && rows[0].balance }})); - })*/ - pool.query(`SELECT * from Transactions where id=${req.user.id}`, (err, rows) => { + /* pool.query(`SELECT user from Users where id=${req.user.id}` , (err, rows) => { + res.end(JSON.stringify({ user: req.user, finance: { balance: rows && rows[0] && rows[0].balance }})); + })*/ + pool.query(`SELECT * from Users,Transactions WHERE Users.id=Transactions.id`, (err, rows) => { res.end(JSON.stringify({ user: req.user, finance: { balance: rows && rows[0] && rows[0].balance }})); }) }); @@ -212,8 +212,8 @@ app.get('/api/stocks/trades/buy/:price', ensureAuthenticated, (req, res) => { } const sql = `SELECT balance FROM Transactions WHERE id='${req.user.id}' AND balance>=${req.params.price}`; - const transaction = `UPDATE Transactions Set balance = balance - ${req.params.price} WHERE id='${req.user.id}'` - + const transaction = `UPDATE Transactions Set stock='SBER',commission=0, price=${req.params.price}+commission, balance = balance - price WHERE id='${req.user.id}'` + const logs = `INSERT INTO Transactions_logs SET id=(SELECT id FROM Transactions WHERE id='${req.user.id}'), balance=(SELECT balance FROM Transactions WHERE id='${req.user.id}'), price=(SELECT price FROM Transactions WHERE id='${req.user.id}'), commission=(SELECT commission FROM Transactions WHERE id='${req.user.id}'), stock=(SELECT stock FROM Transactions WHERE id='${req.user.id}')` pool.getConnection(function (err, connection) { connection.query(sql, (err, results) => { @@ -247,7 +247,9 @@ app.get('/api/stocks/trades/buy/:price', ensureAuthenticated, (req, res) => { connection.release(); console.log(`'balance update - '${req.params.price}`); console.log('success!'); - + connection.query(logs, (err, results) => { + console.log('Transactions logs added'); + }); } }); } @@ -260,6 +262,7 @@ app.get('/api/stocks/trades/buy/:price', ensureAuthenticated, (req, res) => { }); + app.get('/api/stocks/trades/sell/:price', ensureAuthenticated, (req, res) => { // TODO: сделать общее решение для локальной разработки. res.setHeader('Content-Type', 'application/json'); @@ -271,10 +274,11 @@ app.get('/api/stocks/trades/sell/:price', ensureAuthenticated, (req, res) => { if (!req.isAuthenticated() || !req.user || !req.user.id) { return res.end('{}'); } - const sql = `SELECT id FROM Transactions WHERE id='${req.user.id}'`; - const transaction = `UPDATE Transactions Set balance = balance + ${req.params.price} WHERE id='${req.user.id}'` - + const sql = `SELECT balance FROM Transactions WHERE id='${req.user.id}' AND balance>=${req.params.price}`; + const transaction = `UPDATE Transactions Set stock='SBER',commission=0, price=${req.params.price}+commission, balance = balance + price WHERE id='${req.user.id}'` + const logs = `INSERT INTO Transactions_logs SET id=(SELECT id FROM Transactions WHERE id='${req.user.id}'), balance=(SELECT balance FROM Transactions WHERE id='${req.user.id}'), price=(SELECT price FROM Transactions WHERE id='${req.user.id}'), commission=(SELECT commission FROM Transactions WHERE id='${req.user.id}'), stock=(SELECT stock FROM Transactions WHERE id='${req.user.id}')` pool.getConnection(function (err, connection) { + connection.query(sql, (err, results) => { if (err) throw err; if (results && results.length === 0) { @@ -304,8 +308,11 @@ app.get('/api/stocks/trades/sell/:price', ensureAuthenticated, (req, res) => { }); } else { connection.release(); - console.log(`'balance update + '${req.params.price}`) + console.log(`'balance update - '${req.params.price}`); console.log('success!'); + connection.query(logs, (err, results) => { + console.log('Transactions logs added'); + }); } }); } @@ -313,8 +320,8 @@ app.get('/api/stocks/trades/sell/:price', ensureAuthenticated, (req, res) => { } }); } - }) - }) + }); + }); }); function ensureAuthenticated(req, res, next) { From cf5136591557ac1da1a757a4795b3d5c787103ab Mon Sep 17 00:00:00 2001 From: Kamynale Date: Sun, 6 Sep 2020 10:55:29 +0300 Subject: [PATCH 4/4] bd with correction --- server/app.js | 24 +++++++++++------------- 1 file changed, 11 insertions(+), 13 deletions(-) diff --git a/server/app.js b/server/app.js index 91807e7..27efb0a 100644 --- a/server/app.js +++ b/server/app.js @@ -54,10 +54,7 @@ passport.use(new FacebookStrategy({ if (err) throw err; if (rows && rows.length === 0) { console.log('There is no such user, adding now'); - pool.query(`INSERT INTO Users SET - id = '${profile.id}', login = '${profile.displayName}', email = '${email}', photo='${photo}', createdAt = NOW(), balance = 10000 - ON DUPLICATE KEY UPDATE login = '${profile.displayName}', email = '${email}', photo='${photo}' - `); + pool.query(`INSERT INTO Users SET id = '${profile.id}', login = '${profile.displayName}', email = '${email}', photo='${photo}'`); } else { console.log('User already exists in database'); } @@ -67,10 +64,7 @@ passport.use(new FacebookStrategy({ if (err) throw err; if (rows && rows.length === 0) { console.log('There is no balance User in Transaction, adding now'); - pool.query(`INSERT INTO Transactions SET - id = '${profile.id}', login = '${profile.displayName}' - ON DUPLICATE KEY UPDATE login = '${profile.displayName}' - `); + pool.query(`INSERT INTO Transactions SET id = '${profile.id}'`); } else { console.log('Balance for User already exists in database'); } @@ -198,6 +192,7 @@ app.get('/api/stocks/ticks/:tick', ensureAuthenticated, (req, res) => { app.param('price', /^\d+\.?\d*$/i) + // ========= Работа с тиками ========== app.get('/api/stocks/trades/buy/:price', ensureAuthenticated, (req, res) => { // TODO: сделать общее решение для локальной разработки. @@ -212,8 +207,9 @@ app.get('/api/stocks/trades/buy/:price', ensureAuthenticated, (req, res) => { } const sql = `SELECT balance FROM Transactions WHERE id='${req.user.id}' AND balance>=${req.params.price}`; - const transaction = `UPDATE Transactions Set stock='SBER',commission=0, price=${req.params.price}+commission, balance = balance - price WHERE id='${req.user.id}'` - const logs = `INSERT INTO Transactions_logs SET id=(SELECT id FROM Transactions WHERE id='${req.user.id}'), balance=(SELECT balance FROM Transactions WHERE id='${req.user.id}'), price=(SELECT price FROM Transactions WHERE id='${req.user.id}'), commission=(SELECT commission FROM Transactions WHERE id='${req.user.id}'), stock=(SELECT stock FROM Transactions WHERE id='${req.user.id}')` + const transaction = `UPDATE Transactions SET stock='SBER', commission=0, price=${req.params.price}+commission, balance = balance - price WHERE id='${req.user.id}'` + const logs = `INSERT INTO Transactions_logs(id,balance,price,commission,stock) SELECT id,balance,price,commission,stock FROM Transactions WHERE id='${req.user.id}')` + pool.getConnection(function (err, connection) { connection.query(sql, (err, results) => { @@ -274,9 +270,11 @@ app.get('/api/stocks/trades/sell/:price', ensureAuthenticated, (req, res) => { if (!req.isAuthenticated() || !req.user || !req.user.id) { return res.end('{}'); } + const sql = `SELECT balance FROM Transactions WHERE id='${req.user.id}' AND balance>=${req.params.price}`; - const transaction = `UPDATE Transactions Set stock='SBER',commission=0, price=${req.params.price}+commission, balance = balance + price WHERE id='${req.user.id}'` - const logs = `INSERT INTO Transactions_logs SET id=(SELECT id FROM Transactions WHERE id='${req.user.id}'), balance=(SELECT balance FROM Transactions WHERE id='${req.user.id}'), price=(SELECT price FROM Transactions WHERE id='${req.user.id}'), commission=(SELECT commission FROM Transactions WHERE id='${req.user.id}'), stock=(SELECT stock FROM Transactions WHERE id='${req.user.id}')` + const transaction = `UPDATE Transactions SET stock='SBER', commission=0, price=${req.params.price}+commission, balance = balance + price WHERE id='${req.user.id}'` + const logs = `INSERT INTO Transactions_logs(id,balance,price,commission,stock) SELECT id,balance,price,commission,stock FROM Transactions WHERE id='${req.user.id}')` + pool.getConnection(function (err, connection) { connection.query(sql, (err, results) => { @@ -308,7 +306,7 @@ app.get('/api/stocks/trades/sell/:price', ensureAuthenticated, (req, res) => { }); } else { connection.release(); - console.log(`'balance update - '${req.params.price}`); + console.log(`'balance update + '${req.params.price}`); console.log('success!'); connection.query(logs, (err, results) => { console.log('Transactions logs added');