I have some code thats works Ok in PHP.
From the postgres CLI I issue a
NOTIFY job;
The notification is correctly raised by Postgres ( I can see it in the PHP client),
but can't read it in node.
JS:
var pg = require('pg');
var conString = "your postgres information";
var client = new pg.Client(conString);
client.connect();
client.query('LISTEN job');
client.on('notification', function(msg) {
console.log('data');
});
I would prefer to keep it simple. Is the only way to make a
procedure in postgres like this?
Ok, the problem was in the conString parameter.
var conString = "tcp://user:pass#localhost/db";
Is important to check that you are using the correct database to reach the notification messages.
Related
Following this tutorial where a node.js app connects to Azure cosmos - GraphDB and query the GraphDB using gremlin https://learn.microsoft.com/en-us/azure/cosmos-db/create-graph-nodejs
Created an app.js as below. This is working fine. I can submit a gremlin query and get the result. Can I set a connection pool using this gremlin library? I couldn't find any source on how to set up a fixed number of the connection pool and use a connection from the pool and send the connection to the pool back after getting a result or after a fixed time out delay.
package.json
"gremlin": "^3.3.4"
app.js
const gremlin = require('gremlin');
const endpoint = 'endpoint';
const port = 'port';
const username = 'username';
const password = 'password';
const url = `wss://${endpoint}:${port}/gremlin`;
const authenticator = new gremlin.driver.auth.PlainTextSaslAuthenticator(
username,
password
);
graphDBClient = new GremlinClient(url, {
authenticator,
traversalsource: 'g',
rejectUnauthorized: true,
mimeType: 'application/vnd.gremlin-v2.0+json'
});
graphDBClient.submit(gremlinQuery);
I want to get the data from PostgreSQL using Node.js.
So I use 'pg-promise' package.
But I can't get anything.
var pgp = require("pg-promise")( /*options*/ );
var db = pgp("postgres://username:password#localhost:5432/database");
db
.any('SELECT * FROM mytable')
.then(function(data) {
console.log("ABC");
});
I can't see the output ("ABC") on console(cmd).
I am using PostgreSQL 12.0 now.
What did I wrong?
I decided to try Webstorm, mainly for the autocomplete feature, but I've got an issue with it.
I require a .js file of my project(Which in this case is a driver to communicate with my Database) but the autocomplete is not working properly:
var db = require('../../config/database');
var Validator = {};
Validator.isAKnownUserId = function (user_id) {
var query = 'SELECT * FROM users WHERE id = ?';
db.
};
The databse.js file :
var cassandra = require('cassandra-driver');
// Client connecting to the keyspace used by the application
var client = new cassandra.Client ({
keyspace: keyspace,
contactPoints: ['127.0.0.1']
});
module.exports = client;
As you can see nothing special. But for example the "execute" function that is available with the cassandra.Client is not autocompletes in my validator.js file when it is in the database.js file.
Furthermore, if I replace
var db = require('../../config/database');
with
var db;
db = require('../../config/database');
or
var db = new require('../../config/database');
then the autocomplete is working correctly in my file.
Can someone help me figure out this behavior and how to get a proper autocomplete ?
Thanks in advance
Question on Servicestack ServerEvents using Azure Redis cache..
Server Code:
I have these lines under Configure method of Global.asax file
Plugins.Add(new ServerEventsFeature {
OnConnect = (res,httpReq) => res.Publish("cmd.onConnect","Message on connect") ,
OnCreated = (res,httpReq) => res.Publish("cmd.onConnect","Message on create"),
...I have custom message for OnSubscription and OnPublish as well
})
**var redisHost = AppSettings.GetString("RedisHost");
container.Register<IRedisClientsManager>(
new RedisManagerPool(redisHost));
container.Register<IServerEvents>(c =>
new RedisServerEvents(c.Resolve<IRedisClientsManager>()));
container.Resolve<IServerEvents>().Start();**
Following is the value format I have in my web.config, for the redis connection
add key="RedisHost" value="passKey#Hostname:6380?ssl=true"
Client Code:
ServerEventConnect connectMsg = null;
var msgs = new List<ServerEventMessage>();
var commands = new List<ServerEventMessage>();
var errors = new List<Exception>();
var client = new ServerEventsClient(baseUri,"home") {
OnConnect = e => connectMsg = e,
OnCommand = commands.Add,
OnMessage = msgs.Add,
OnException = errors.Add,
}.Start();
var connectMsg = client.Connect();
var joinMsg = client.WaitForNextCommand();
connectMsg.Wait();//It gets connnected
joinMsg.Wait(); //When I debug, it is getting lost on this line. I don't get any error message!
When I remove Redis registration marked above in Global.asax (that is default option MemoryServerEvents) works well. Any suggestion, ideas would be very helpful. Thank you
oh God.. Finally I found what the issue is.. It had nothing to do with server events code or its confguration!!! But I have the following line used in my application for a different purpose and which had impact on server events!
// Set the default reuse scope for the container to per request
container.DefaultReuse = ReuseScope.Request;
I guess onConnect is first request and OnJoin or other events are separate requests. As reuse scope was set in my app, it couldn't proceed?! Please share your thoughts if am wrong. Thank you
I am using socket.io in node.js to implement chat functionality in my azure cloud project. In it i have been adding the user chat history to tables using node.js. It works fine when i run it on my local emulator, but strangely when i deploy to my azure cloud it doesnt work and it doesnt throw up any error either so its really mind boggling. Below is my code.
var app = require('express')()
, server = require('http').createServer(app)
, sio = require('socket.io')
, redis = require('redis');
var client = redis.createClient();
var io = sio.listen(server,{origins: '*:*'});
io.set("store", new sio.RedisStore);
process.env.AZURE_STORAGE_ACCOUNT = "account";
process.env.AZURE_STORAGE_ACCESS_KEY = "key";
var azure = require('azure');
var chatTableService = azure.createTableService();
createTable("ChatUser");
server.listen(4002);
socket.on('privateChat', function (data) {
var receiver = data.Receiver;
console.log(data.Username);
var chatGUID1 = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
var r = Math.random()*16|0, v = c == 'x' ? r : (r&0x3|0x8);
return v.toString(16);
});
var chatRecord1 = {
PartitionKey: data.Receiver,
RowKey: data.Username,
ChatID: chatGUID2,
Username: data.Receiver,
ChattedWithUsername: data.Username,
Timestamp: new Date(new Date().getTime())
};
console.log(chatRecord1.Timestamp);
queryEntity(chatRecord1);
}
function queryEntity(record1) {
chatTableService.queryEntity('ChatUser'
, record1.PartitionKey
, record1.RowKey
, function (error, entity) {
if (!error) {
console.log("Entity already exists")
}
else {
insertEntity(record1);
}
})
}
function insertEntity(record) {
chatTableService.insertEntity('ChatUser', record, function (error) {
if (!error) {
console.log("Entity inserted");
}
});
}
Its working on my local emulator but not on cloud and I came across a reading that DateTime variable of an entity should not be null when creating a record on cloud table. But am pretty sure the way am passing timestamp is fine, it is right? any other ideas why it might be working on local but not on cloud?
EDIT:
I hav also been getting this error when am running the socket.io server, but in spite of this error the socket.io functionality is working fine so i didnt bother to care about it. I have no idea what the error means in the first place.
{ [Error: connect ECONNREFUSED]
code: 'ECONNREFUSED',
errno: 'ECONNREFUSED',
syscall: 'connect' }
Couple things:
You shouldn't need to set Timestamp, the service should be populating that automatically when you insert a record.
When running it locally you can set the environment variables to the Windows Azure storage account settings and see if it will successfully write to the table when running on your developer box. Instead of running in the emulator, just set the environment variables and run the app directly with node.exe.
Are you running in a web role or worker role? I'm assuming it's a cloud service since you mentioned the emulator. If it's a worker role, maybe add some instrumentation to log to file to assist in debugging. If it's a web role you can add an iisnode.yml file in the root of the application, with the following line in the file to enable logging of stdout/stderr:
loggingEnabled: true
This will capture stdout/stderr to an iislog folder under the approot folder on e: or f: of the web role instance. You can remote desktop to the instance and look at the logs to see if the logs you have for successful insertion are occurring.
Otherwise, it's not obvious from the code above what's going on. Similar code worked fine for me. Relevant bits for my test code can be found at https://gist.github.com/Blackmist/5326756.
Hope this helps.