I'm trying to implement a promise-based approach to accessing a PostgreSQL database. This is the original code:
// ./sql/config/pgQuery.js
module.exports = (text, values, cb) => {
pool.connect((err, client, done) => {
if (err) return cb(err);
client.query(text, values, (err, result) => {
done();
if (err) return cb(err);
return cb(null, result.rows, result);
});
});
};
// ./routes/pg.js
router.route('/')
.get((req, res) => {
const values = [];
query('DROP TABLE IF EXISTS users', values, (err, rows, all) => {
if (err) throw err;
console.log('DROP TABLE IF EXISTS users');
res.status(204).end();
});
const text = 'CREATE TABLE IF NOT EXISTS users (date timestamptz)';
query(text, values, (err, rows, all) => {
if (err) throw err;
console.log('CREATE TABLE IF NOT EXISTS users');
res.status(204).end();
});
});
This is what I come up with so far, but it doesn't work:
// ./sql/config/pgQuery.js
function promisePool() {
return new Promise((resolve, reject) => {
return (text, values, cb) => {
pool.connect((err, client, done) => {
if (err) { cb(err); return; }
client.query(text, values, (err, result) => {
done();
if (err) { reject(err); return; }
return resolve(cb(null, result.rows, result));
});
});
};
});
}
module.exports = promisePool;
// ./routes/pg.js
router.route('/')
.get((req, res) => {
const values = [];
query()
.then('DROP TABLE IF EXISTS users', values, (err, rows, all) => {
if (err) throw err;
console.log('DROP TABLE IF EXISTS users');
res.status(204).end();
})
.then('CREATE TABLE IF NOT EXISTS users (date timestamptz)', values, (err, rows, all) => {
if (err) throw err;
console.log('CREATE TABLE IF NOT EXISTS users');
res.status(204).end();
});
});
Thank You for your help!
Related
function Getir() {
var options =
{
host: 'example',
port: 443,
path: '/myUrl'
};
get(options, function (http_res) {
var data = "";
http_res.on("data", function (chunk) {
data += chunk;
});
http_res.on("end", function () {
writeFile('NewHtml.txt', `${data}`, 'utf8', (err) => {
if (err) console.log(err);
});
});
});
}
function DegistirDuzenle() {
if (existsSync("./DatabaseHtml.txt")) {
var DataBaseHtml = readFileSync("./DatabaseHtml.txt", 'utf-8', (err) => { if (err) console.log(err) });
var MyHtml = readFileSync("./NewHtml.txt", 'utf-8', (err) => {if (err) console.log(err) });
if (MyHtml == DataBaseHtml) {
unlink("./NewHtml.txt", (err)=>{ if(err) console.log(err)});
console.log("değişiklik yapılmadı");
} else {
//notification
console.log("değişiklik yapıldı");
//Change
unlink('./DatabaseHtml.txt', (err) => { if(err) console.log(err); });
writeFile('./DatabaseHtml.txt', `${MyHtml}`, 'utf-8', (err) => { if(err) console.log(err); });
unlink('./NewHtml.txt', (err) => { if(err) console.log(err); });
}
}
else {
writeFile('DatabaseHtml.txt', `NewDataBaseHtml`, 'utf8', (err) => {
if (err) console.log(err);
});
}
}
async function Mysystem() {
let mypromis = new Promise((resolve, reject)=>{
resolve(Getir());
});
await mypromis.then(DegistirDuzenle());
}
Mysystem();
I want to create a txt file, read it and delete it later. I have 2 function 1.(Getir()) Create txt, 2.(DegistirDuzenle()) read txt and delete but 2. function starts working first and I getting error. "Error: ENOENT: no such file or directory, open './NewHtml.txt'"
async function Mysystem() {
let mypromis = new Promise((resolve, reject)=>{
resolve(Getir());
});
await mypromis()
await DegistirDuzenle()
}
Mysystem()
You should use
async function Mysystem() {
await Getir();
await DegistirDuzenle();
}
or
function Mysystem() {
return Getir().then(DegistirDuzenle);
}
but not a mix of them. Also notice that when passing the DegistirDuzenle function to .then() as a callback, it shouldn't be invoked (passing the result of a call, not passing the function). Alternatively, you could write .then((getirResult) => DegistirDuzenle()).
Also, for this to work, you'll need to properly promisify the code in Getir and DegistirDuzenle.
So I come to this, I want to write into a DB and do other operations to work with my program logic, this is the guide that I'm following Node.js Class Creation:
//## This is my mysql_test.js file
function MySQL(){
var mysql = require('mysql');
var con = mysql.createConnection({
//data omitted
});
function AppendRecordset (req, res){
con.connect(function(err) {
if (err) throw err;
console.log("Connected!");
con.query(req, function (err, res) {
if (err) throw err;
console.log("1 record inserted");
});
});
}
function UpdateRecordset (req, res) {
con.connect(function(err) {
if (err) throw err;
con.query(req, function (err, res) {
if (err) throw err;
console.log(result.affectedRows + " record(s) updated");
});
});
}
function DeleteRecordset (req, res){
con.connect(function(err) {
if (err) throw err;
con.query(req, function (err, res) {
if (err) throw err;
console.log("Number of records deleted: " + result.affectedRows);
});
});
}
function GetRecordset (req, res) {
con.connect(function(err) {
if (err) throw err;
con.query(req, function (err, res, fields) {
if (err) throw err;
console.log(result);
});
});
}
}
I then have in a separate file(s) my app logic, and want to use what of the above as an object/class so I wrote this accordingly to that guide:
//##this is inside my main app file
//declare the sql processor
require('./mysql_test.js');
var DB = MySQL();
DB.AppendRecordset(sql_string, res); //sql_string contains a valid SQL statement
But when I try to acces it using `` I get this error message: ReferenceError: MySQL is not defined what am I doing wrong?
I think these functions handle your routes, so I didn't change them. Because I don't know how your router is desined.
Create a file dbHangler.js and write this single function:
const mysql = require('mysql');
let con;
exports.execQuery = (query) => {
return new Promise((resolve, reject) => {
if(!con) {
con = mysql.createConnection({
//data omitted
});
}
con.connect(function(err) {
if(err) {
reject(err);
}
else {
console.log("Connected!");
con.query(query, function (err, res) {
if (err) {
reject(err);
}
else {
resolve(res);
}
});
}
});
});
};
In your dedicated.js file, now you can write:
const dbObject = require('path/to/dbHandler');
function AppendRecordset (req, res){
dbObject.execQuery(req)
.then(result => {
console.log(result.affectedRows + " record(s) updated");
})
.catch(error => {
// handle error
});
}
function AppendRecordset (req, res){
dbObject.execQuery(req)
.then(result => {
console.log("Number of records deleted: " + result.affectedRows);
})
.catch(error => {
// handle error
});
}
function AppendRecordset (req, res){
dbObject.execQuery(req)
.then(result => {
console.log(result);
})
.catch(error => {
// handle error
});
}
UPDATE
I hope this one helps you.
DbHandler.js
const mysql = require('mysql');
class DbHandler {
constructor(config) {
let self = this;
self.dbConfig = config;
self.connection = mysql.createConnection({
//data omitted
});
}
queryExecuter(query) {
let self = this;
return new Promise((resolve, reject) => {
self.connection.connect(function (err) {
if (err) {
reject(err);
}
else {
console.log("Connected!");
self.connection.query(query, function (err, res) {
if (err) {
reject(err);
}
else {
resolve(res);
}
});
}
});
});
}
AppendRecordset(query) {
let self = this;
return self.queryExecuter(query)
.then(result => {
console.log("1 record inserted");
return result;
})
.catch(error => {
// handle error
throw error;
});
}
UpdateRecordset(query) {
let self = this;
return self.queryExecuter(query)
.then(result => {
console.log(result.affectedRows + " record(s) updated");
return result;
})
.catch(error => {
// handle error
throw error;
});
}
// and other functions
}
module.exports = DbHandler;
And use it like below:
let DB = require('/path/to/DbHandler');
let myDb = new DB(/* db config */);
db.UpdateRecordset('your query')
.then(res => {
console.log(res);
})
.catch(err => {
console.log(err);
});
I'm trying to translate my old mysql app to Postgresql, it was very difficult to connect to the server, but when i think it worked, this message appears on insomnia.
The message
I tried using different methods that i found on Google but they didn't work for me.
I think that the problem is how i'm connecting to the server.
I'm new using postgresql.
const { Pool, Client } = require("pg")
const config = require("../config")
const connection = new Pool({
host: config.postgresql.host,
user: config.postgresql.user,
password: config.postgresql.password,
database: config.postgresql.database,
port: "5432",
ssl: true
})
function list(table) {
return new Promise((resolve, reject) => {
connection.query(`SELECT * FROM ${table}`, (err, data) => {
if (err) return reject(err)
resolve(data)
})
})
}
function get(table, id) {
return new Promise((resolve, reject) => {
connection.query(`SELECT * FROM ${table} WHERE id=${id}`, (err, data) => {
if (err) return reject(err)
resolve(data)
})
})
}
function insert(table, data) {
return new Promise((resolve, reject) => {
connection.query(`INSERT INTO ${table} SET ${data}`, (err, result) => {
if (err) return reject(err)
resolve(result)
})
})
}
function update(table, data) {
return new Promise((resolve, reject) => {
connection.query(
`UPDATE ${table} SET ${data} WHERE id=${data.id}`,
(err, result) => {
if (err) return reject(err)
resolve(result)
}
)
})
}
const upsert = async (table, payload) =>
new Promise((resolve, reject) => {
connection.query(
`INSERT INTO ${table} SET ${payload} ON DUPLICATE KEY UPDATE ${payload}`,
(error, data) => {
console.log("UPDATE DATA: ", data)
if (error) {
return reject(error)
}
resolve(data)
}
)
})
function query(table, query, join) {
let joinQuery = ""
if (join) {
const key = Object.keys(join)[0]
const val = join[key]
joinQuery = `JOIN ${key} ON ${table}.${val} = ${key}.id`
}
return new Promise((resolve, reject) => {
connection.query(
`SELECT * FROM ${table} ${joinQuery} WHERE ${table}.${query}`,
(err, res) => {
if (err) return reject(err)
resolve(res[0] || null)
}
)
})
}
module.exports = {
list,
get,
upsert,
query
}
The insert query is wrong, Please change it to the below syntax. You cannot use SET in insert. SET should be used in update.
Wrong:
connection.query(`INSERT INTO ${table} SET ${data}`, (err, result)
Insert query syntax:
INSERT INTO TABLE_NAME (column1, column2, column3,...columnN)
VALUES (value1, value2, value3,...valueN);
I'm creating my first app using Node.js and PostgreSQL.
This app connect's to db and return record to browser in JSON format, its work perfectly till i try to use map function to formating properties.
When i use map it return an error:
TypeError: rows.map is not a function
This is my code.
app.get('/car/:id', (req, res) => {
const car_id = req.params.id;
const queryString = `SELECT * FROM cars WHERE car_id= ${car_id}`;
client.query(queryString, (err, rows, fields) => {
if (err) {
console.log(err.stack);
res.sendStatus(500);
res.end();
} else {
const car = rows.map((row) => {
return {"Car_ID": row.car_id}
});
res.json(car);
console.log(rows.rows);
}
});
It should be result.rows not just rows
According to this - https://node-postgres.com/api/result
app.get('/car/:id', (req, res) => {
const car_id = req.params.id;
const queryString = `SELECT * FROM cars WHERE car_id= ${car_id}`;
client.query(queryString, (err, result, fields) => {
if (err) {
console.log(err.stack);
res.sendStatus(500);
res.end();
} else {
const car = result.rows.map((row) => {
return {"Car_ID": row.car_id}
});
res.json(car);
console.log(result.rows);
}
});
I have three different sample.xml files which I have to convert into json output. I am trying to append all of their output into one json file. here is my code
const fs = require('fs');
const xml2js = require('xml2js');
parser = new xml2js.Parser({
explicitArray: true
})
fs.readFile('sample.xml', (err, data) => {
parser.parseString(data, (err, result) => {
let output = JSON.stringify(result.planes.plane);
fs.writeFile('output.json', output, 'utf8', (err) => {
if (err) {
throw err;
} else {
console.log('file created..')
}
})
});
});
now I know the function fs.appendfile() but I am not sure how do I do it? I have two more files named: sample2.xml and sample3.xml
this is what I have tried but the problem it is overwriting not appending.
const fs = require('fs');
const xml2js = require('xml2js');
const async = require('async');
parser = new xml2js.Parser({
explicitArray: true
})
let files = ['sample.xml', 'sample2.xml'];
async.map(files, fs.readFile, (err, files) => {
if (err) {
throw err;
} else {
files.forEach((file) => {
parser.parseString(file, (err, result) => {
let output = JSON.stringify(result.planes.plane);
fs.appendFile('output.json', output, 'utf8', (err) => {
if (err) {
throw err;
} else {
console.log('file created..')
}
})
});
})
}
})
You need to read each xml file, get the json-data from it, and then write it to the final file:
async.map(
files,
(file, cb) => {
fs.readFile(file, (err, data) => {
if (err) {
cb(err)
} else {
parser.parseString(data, (err, result) => {
cb(err, result.planes.plane)
})
}
})
},
function (err, results) {
if (err) {
throw err
} else {
let output = JSON.stringify(results)
fs.writeFile('output.json', output, 'utf8', (err) => {
if (err) {
throw err
} else {
console.log('file created...')
}
})
}
}
)