why is node-postgres only working with routes - node.js

I am currently trying to query some data from AWS RDS using postgresql and pg for node.js. For some reason, I found out I can only query data when I am using a route handler.
for example:
const data = require('../data/rand.json');
const db = require('../db');
const Router = require('express-promise-router');
const router = new Router();
module.exports = router;
router.get('/', (req,res) => {
db.query(`SELECT * FROM rooms WHERE id < 10`)
.then((val) => console.log(val))
.catch(err => console.log(err))
})
However, when I try to query data like this:
const db = require('../db');
db.query(`SELECT * FROM rooms WHERE id < 10`)
.then((val) => console.log(val))
.catch(err => console.log(err))
I get this error - TypeError [ERR_INVALID_ARG_TYPE]: The "key" argument must be of type string or an instance of Buffer, TypedArray, DataView, or KeyObject. Received null
I am fine to continue using routes to query, but was wondering why this is occurring and if it is normal. I couldn't find much info on the node-postgres docs. I am still new to this, thanks for any help.
edit: db file looks like this
const { Pool } = require('pg');
//don't need to add obj w/ env var inside Pool
const pool = new Pool();
//value - cb f(x)
module.exports = {
query: (text, params) => pool.query(text, params),
}

Related

When connect firebase to node project it show db is not defined

When connect firebase to node project it show db is not defined.
Progress.js
const Progress = require("../models/progress");
//add new Progress
exports.addProgress = async (req, res) => {
//constant variables for the attributes
const {name, description, type, date,imgUrl} = req.body;
//object
const newProgress= new Progress({
//initializing properties
name,
description,
type,
date,
imgUrl
})
//saving the object to the db
newProgress.save().then(() => {
res.status(200).json({ status: "New Progress Added" });
}).catch((error) => {
res.status(500).json({message:"Fail to Progress Item",error:error.message})
})
}
model
I think you missed to initialize DB, Try This -
const firestore = require("firebase-admin");
const db = firestore.firestore();

Why console.log is executing before promise is fulfilled in node.js

I'm trying to pull data from an external API, then create an array of bitcoin bid prices, then console log the output. The problem is that the console log function is executing before the data is returned from the server. This creates an empty array. Please advise on how I can fix this.
const express = require('express')
const app = express()
const port = 6800
app.listen(port, () => {
port
})
const GateApi = require('gate-api');
const client = new GateApi.ApiClient();
var _array = [] // store data returned from server
const api = new GateApi.SpotApi(client); //gate-io api
const currencyPair = "BTC_USDT"; // string | Currency pair
const opts = {
'limit': 10 // limit records returned
};
api.listOrderBook(currencyPair, opts).then(value => {
return value.body.bids.forEach(function(data) {
_array.push(data);
});
}, error => console.error(error)).then(console.log(_array))
The argument to then should be a function. That function will get executed once the promise fulfills.
You are not passing a function, you are passing the result of console.log().
Instead of:
.then(console.log(foo))
You'll want:
.then(() => console.log(foo))

How to create a async function and export it?

Using node + express. I want to create a module that use several querys.
how can I export this asynchronous function to app.js?
This is the function that im trying to make it work:
app.js (where io are socketio instance)
const users = require('./sockets/users')(io)
users.js
const Users = require('../models/Users.model')
const users = async function(client){
client.on('connection', socket =>{
socket.on('userAdd',(data) =>{
console.log(data);
})
const users = await Users.find()
console.log(users[0]);
})
}
module.exports = users
Error: SyntaxError: await is only valid in async function
First create two files. you can create functions into one and can export it and in another file you can import that functions. check the code below.
> server.js
const addition = require('./addition.js') // path to your another file
const result = addition.add(5, 8) // calling function of another file
console.log(result)
another file
> addition.js
const add = (x, y) => x + y;
module.exports = { add } // export this function
output:
13
I was typing the async keyword in the incorrect function. Its in the connection function
const Users = require('../models/Users.model')
const users = function(client){
client.on('connection', async socket =>{
socket.on('userAdd',(data) =>{
console.log(data);
})
const users = await Users.find()
console.log(users[0]); //user 1
})
}
module.exports = users
You can try to use a class for that and export that class and use it

Not able to retrieve data from datastore using node

I have a simple get request built using node, express to retrieve data from datastore. I am not able to get back the results. 'get' request async call is stuck. Not sure what is happening.
const express = require('express');
const {Datastore} = require('#google-cloud/datastore');
const app = express();
// Your Google Cloud Platform project ID
const projectId = 'xxx';
// Creates a client
const datastore = new Datastore({
projectId: projectId,
keyFilename: '/Masters-LUC/spring-2019/internship/service-keys/xxx.json'
});
const query = datastore
.createQuery('approvals')
.filter('status', '=', 'yes');
app.get("/api/get", (req, res, next) => {
query.run().then(([documents]) => {
documents.forEach(doc => console.log(doc));
});
});
module.exports = app;
I re-wrote the same using async function. The below is working. Why not the above?
// Retrieve data from datastore
async function quickStart() {
// Your Google Cloud Platform project ID
const projectId = 'xxx';
// Creates a client
const datastore = new Datastore({
projectId: projectId,
keyFilename: '/Masters-LUC/spring-2019/internship/service-
keys/xxx.json'
});
const query = datastore
.createQuery('approvals')
.filter('status', '=', 'yes');
const [approvals] = await datastore.runQuery(query);
console.log('Tasks:');
approvals.forEach(task => console.log(task));
}
quickStart().catch(console.error);
The two things I notice that is different between your two functions. In the first you reuse the query object across function invocations. Query objects should not be reused.
The second thing I notice is that you don't use res that's passed into your function parameter to app.get().
Modified working code -
app.get("/api/approvals/", (req, res, next) => {
const query = datastore
.createQuery('approvals');
query.run().then((approvals) => {
approvals.forEach(appr => console.log(appr)); // This is used to log results on console for verification
// loading results on the response object to be used later by client
res.status(200).json(
{
message: "Request was processed successfully!",
approvals : approvals
}
);
})
})

How to setup postgis extension for knex?

I am new to node and are building a simple API to handle geographic data.
For this I am trying to implement knex-postgis
I have a connection file that I require in my queries.js like so:
const knex = require('./knex');
and use it
update(id, poi) {
return knex('poi').where('id', id).update(poi, '*');
The doc say to implement the extension like this:
const knex = require('knex');
const knexPostgis = require('knex-postgis');
const db = knex({
dialect: 'postgres'
});
// install postgis functions in knex.postgis;
const st = knexPostgis(db);
/* or:
* knexPostgis(db);
* const st = db.postgis;
*/
Can someone please explain where in my structure I implement the code, this is the first time I am using an extension. Do i put it in my knex.js file?
My knex.js look like this:
const environment = process.env.NODE_ENV || 'development';
const config = require('../knexfile');
const environmentConfig = config[environment];
const knex = require('knex');
const connection = knex(environmentConfig);
module.exports = connection;
EDIT:
I tried putting this in my queries.js file
const knex = require('./knex');
const knexPostgis = require('knex-postgis');
const st = knexPostgis(knex);
const db = knex({
dialect: 'postgres'
});
My create function:
create() {
const sql = knex.insert({
geom: st.geomFromText('Point(-71.064544 44.28787)', 4326)
}).into('poi').toString();
console.log(sql);
return sql
It console.log a valid sql that works in pgadmin but in postman I get
"message": "queries.create(...).then is not a function",
And finally my route
router.post('/', (req, res, next) => {
queries.create(req.body).then(poi => {
res.json(poi[0]);
});
});
You are returning string from your create method, but expect a promise interface in your route handler.
And you are using knex instead of db for query building.
Try this
const builder = db.insert(/*same as above*/).into('tablename');
const sql = builder.toString();
console.log(sql);
// Return builder instance itself (promise) instead of string
return builder;
You're calling knex.insert. You should be calling db.insert.

Resources