Connecrint to Mongodb - database

I just can't connect to a mongodb. Here's what I tried
in node.js
console.log("001");
dotenv = require('dotenv');
dotenv.config();
const mongodb = require('mongodb').MongoClient;
const { MongoClient } = require("mongodb");
console.log("002");
const uri = process.env.CONNECTIONSTRING;
const client = new MongoClient(uri);
console.log("003");
async function run() {
console.log("004");
client.connect();
const db = client.db("blah");
console.log("005");
await const results = db.student.find();
console.log("006")
console.log(results)
console.log("007")
client.close()
};
//call function
run();
and I get this error
SyntaxError: Unexpected token 'const'
the CONNECTIONSTRING is in .env beside the original file node.js
The database is called 'blah' and the collection 'student'.
The error is on line 18,
await const results = db.student.find();
Thanks,

Related

Cannot PubSub from Mongo Db Atlas function

I am using the following Code to do a simple pubsub from a MongoDB function to Google Pubsub.
But when I instantiate PubSub : const pubSubClient = new PubSub(); I get TypeError: Value is not an object: undefined. Any hint on how to solve this issue?
exports = function(changeEvent) {
const topicName = 'topicname';
const data = JSON.stringify({foo: 'bar'});
const {PubSub} = require('pubsub');
const pubSubClient = new PubSub();
async function publishMessageWithCustomAttributes() {
// Publishes the message as a string, e.g. "Hello, world!" or JSON.stringify(someObject)
const dataBuffer = Buffer.from(data);
// Add two custom attributes, origin and username, to the message
const customAttributes = {
origin: 'nodejs-sample',
username: 'gcp',
};
const messageId = await pubSubClient
.topic(topicName)
.publish(dataBuffer, customAttributes);
console.log(`Message ${messageId} published.`);
}
publishMessageWithCustomAttributes().catch(console.error);
};

ReactJS Failed to construct 'WebSocket': The subprotocol '[object Object]' is invalid

I'm getting the following error in my react application using enigma.js (https://qlik.dev/apis/javascript/enigmajs) . I'm trying to initialize a WebSocket connection and im getting the error. "Failed to construct 'WebSocket': The subprotocol '[object Object]' is invalid".
The WebSocket connection URL is correct as it can be tested with https://catwalk.core.qlik.com/?engine_url=wss://sense-demo.qlik.com/app/133dab5d-8f56-4d40-b3e0-a6b401391bde which returns the data. You can try by editing the URL which will return an error.
the code is
async init() {
const appId = "133dab5d-8f56-4d40-b3e0-a6b401391bde";
const url =
"wss://sense-demo.qlik.com/app/133dab5d-8f56-4d40-b3e0-a6b401391bde";
const session = enigma.create({
schema,
createSocket: () =>
new WebSocket(url, {
}),
});
const global = await session.open();
const app = await global.openDoc(appId);
const appLayout = await app.getAppLayout();
console.log(appLayout);
}
I found the solution:
qDoc.config.js
const enigma = require('enigma.js');
const schema = require('enigma.js/schemas/12.20.0.json');
const SenseUtilities = require('enigma.js/sense-utilities');
const config = {
host: 'sense-demo.qlik.com',
secure: true,
port: 443,
prefix: '',
appId: '133dab5d-8f56-4d40-b3e0-a6b401391bde',
};
const url = SenseUtilities.buildUrl(config);
async function init() {
const session = enigma.create({
schema,
url,
suspendOnClose: true,
});
const global = await session.open();
const app = await global.openDoc(config.appId);
const appLayout = await app.getAppLayout();
console.log(appLayout);
}
init();
const session = enigma.create({ schema, url, suspendOnClose: true });
// open doc and return promise which will resolve to doc
export const openDoc = () => (
session.open().then((global) => global.openDoc(config.appId))
);
// close session
export const closeSession = () => (
session.close()
);
INSTURCTION
downoad this project
delete package-lock.json file
npm i
npm run-script dev
This is the direvtory view:
This is result log:
The solution is explained here
https://github.com/qlik-oss/enigma.js/issues/889

I keep getting an error when using the clarifai 'Demographics" model

TypeError: Cannot read property 'language' of undefined
The demographics model was working few months ago when I used it as 'Clarifai.DEMOGRAPHICS_MODEL' but now it gives a 404 error for the same. I think now I am supposed to use it as 'Clarifai.Demographics' but it gives the error shown in picture.
Am I doing something wrong or is it some Clarifai issue? I am relatively new to react programming and just noticed the app that I had made before using 'Clarifai.DEMOGRAPHICS_MODEL' started showing errors suddenly.
For now, I am just trying to make this work
const onSubmit = () => {
app.models.predict(Clarifai.Demographics, "https://static.independent.co.uk/s3fs-public/thumbnails/image/2015/06/06/15/Chris-Pratt.jpg")
.then(res => console.log(res))
}
NEW EDIT :
Finally, now I can retrieve data from clarifai and send it to frontend. Keeping the backend code here for reference if anyone needs.
--------server.js---------
const express = require('express')
const cors = require('cors')
const posts = require('./demographics.js')
const app = express()
app.use(cors())
app.use(express.json())
const PORT = process.env.PORT || 5000
app.post('/data', posts.demographics)
app.listen(PORT, ()=> {
console.log('Working at port ',PORT)
})
--------demographics.js---------
const {ClarifaiStub, grpc} = require("clarifai-nodejs-grpc");
const stringify = require('json-stringify-safe');
const demographics = (req,res) => {
const stub = ClarifaiStub.grpc()
const metadata = new grpc.Metadata();
metadata.set("authorization", "Key {My_Key}");
stub.PostWorkflowResults(
{
workflow_id: "Demographics",
inputs: [
{data: {image: {url: req.body.input}}}
]
},
metadata,
(err, response) => {
if(response){
const data = stringify(response.results[0].outputs[4].data.regions, null, 2)
res.send(data)
}
else {
console.log(err)
res.status(400)
}
}
)
}
You have to call the request either from the front end or from the backend.
And the demographics now only support requests from the backend.
const {ClarifaiStub} = require("clarifai-nodejs-grpc");
const grpc = require("#grpc/grpc-js");
const metadata = new grpc.Metadata();
metadata.set("authorization", "{My key}");
const stub = ClarifaiStub.json()
stub.PostWorkflowResults(
{
workflow_id: "Demographics",
inputs: [
{data: {image: {url: "https://static.independent.co.uk/s3fs-public/thumbnails/image/2015/06/06/15/Chris-Pratt.jpg"}}}
]
},
metadata,
(err, response) => {
if(response){
console.log(response.results[0].outputs[2].data.regions[0].data.concepts
)
}else {
console.log(err)
}
use this for returning results
// response.results[0].outputs[2].data.regions[0].data.concepts, muliticulture,
// response.results[0].outputs[3].data.regions[0].data.concepts, gender,
//response.results[0].outputs[4].data.regions[0].data.concepts, age,
The Clarifai JS Rest client is now depreciated, the model IDs are not updated and this specific Demographics model is also on the course of depreciation. You can replace it with the new gRPC NodeJS API: https://docs.clarifai.com/api-guide/api-overview/api-clients
You can then get a demographics prediction by calling the new Demographics workflow: https://docs.clarifai.com/api-guide/workflows/workflow-predict (replace 'YOUR_WORKFLOW_ID' by 'Demographics')

Issue connecting to token server with Firebase hosting

I am trying to deploy the Twilio video app to Firebase hosting. Everything works great, except when I try to connect to video conference it tells me the Twilio tokens are invalid.
I found that I need to set up google cloud functions to resolve this. How do you go about converting a server.js file to a cloud function?
Here is my code server.js code:
const express = require('express');
const app = express();
const path = require('path');
const AccessToken = require('twilio').jwt.AccessToken;
const VideoGrant = AccessToken.VideoGrant;
require('dotenv').config();
const MAX_ALLOWED_SESSION_DURATION = 14400;
const twilioAccountSid = process.env.TWILIO_ACCOUNT_SID;
const twilioApiKeySID = process.env.TWILIO_API_KEY_SID;
const twilioApiKeySecret = process.env.TWILIO_API_KEY_SECRET;
app.use(express.static(path.join(__dirname, 'build')));
app.get('/token', (req, res) => {
const { identity, roomName } = req.query;
const token = new AccessToken(twilioAccountSid, twilioApiKeySID, twilioApiKeySecret, {
ttl: MAX_ALLOWED_SESSION_DURATION,
});
token.identity = identity;
const videoGrant = new VideoGrant({ room: roomName });
token.addGrant(videoGrant);
res.send(token.toJwt());
console.log(`issued token for ${identity} in room ${roomName}`);
});
app.get('*', (_, res) => res.sendFile(path.join(__dirname, 'build/index.html')));
app.listen(8081, () => console.log('token server running on 8081'));
I'm thinking I can move that to the cloud functions index.js file and add the following to still connect to my .env file variables if I put the express function in here:
const functions = require('firebase-functions');
const config = functions.config();
// Porting envs from firebase config
for (const key in config.envs){
process.env[key.toUpperCase()] = config.envs[key];
}
To convert this to a Firebase cloud function, you need to remove server listeners and you have to setup a local Firebase environment to deploy and develop
Steps to convert cloud function
# Install firebase-tools
npm install -g firebase-tools
# Login and initialize project
firebase login
firebase init functions
# For local dev
firebase serve
# Deploy the function to cloud
firebase deploy
Your current code will look something like this after converting to cloud function
You can also make each routes into separate modules
const functions = require('firebase-functions');
const express = require('express');
const app = express();
const path = require('path');
const AccessToken = require('twilio').jwt.AccessToken;
const VideoGrant = AccessToken.VideoGrant;
require('dotenv').config();
const router = express.Router();
const MAX_ALLOWED_SESSION_DURATION = 14400;
const twilioAccountSid = process.env.TWILIO_ACCOUNT_SID;
const twilioApiKeySID = process.env.TWILIO_API_KEY_SID;
const twilioApiKeySecret = process.env.TWILIO_API_KEY_SECRET;
app.use(express.static(path.join(__dirname, 'build')));
router.get('/token', (req, res) => {
const { identity, roomName } = req.query;
const token = new AccessToken(twilioAccountSid, twilioApiKeySID, twilioApiKeySecret, {
ttl: MAX_ALLOWED_SESSION_DURATION,
});
token.identity = identity;
const videoGrant = new VideoGrant({ room: roomName });
token.addGrant(videoGrant);
res.send(token.toJwt());
console.log(`issued token for ${identity} in room ${roomName}`);
});
router.get('*', (_, res) => res.sendFile(path.join(__dirname, 'build/index.html')));
// Your cloud function will be like : https://<region>-<appname>.cloudfunctions.net/twilioApp
exports.twilioApp = functions.https.onRequest(router);
Please read the official documentation here

OPTIONS net::ERR_CONNECTION_REFUSED...but server is working as intended?! react/express

I see there are a lot of posts on this subject already, so I apologize if this is a repeat.
What is strange and possibly unique (I don't know) is that the server seems to be functioning and executing the API call properly.
I have a react front end with an express backend being hosted on an AWS EC2 instance. As said above, when my front end makes a axios.post request, the server does everything it is supposed to, but I'm am returned two errors. One is
OPTIONS http://us-west-1.compute.amazonaws.com:3000 net::ERR_CONNECTION_REFUSED
The other is
Error: Network Error
at createError (createError.js:17)
at XMLHttpRequest.handleError (xhr.js:87)
react code is:
import React from "react";
import PaypalExpressBtn from "react-paypal-express-checkout";
import axios from "axios";
export default class Pay extends React.Component {
constructor(props) {
super(props);
this.state = {
items: {}
};
}
render() {
const onSuccess = payment => {
axios
.post("http://compute.amazonaws.com:3000/", {
value: this.props.value,
fileName: this.props.fileName,
hash: this.props.hash
})
.then(response => console.log(response.data))
.catch(function(error) {
console.log(error);
});
console.log(payment);
};
let env = "sandbox"; // you can set here to 'production' for production
let currency = "USD"; // or you can set this value from your props or state
let total = 3.33; // same as above, this is the total amount (based on
const client = {
sandbox:
"...key...",
production: "YOUR-PRODUCTION-APP-ID"
};
return (
<div>
<PaypalExpressBtn
onSuccess={onSuccess}
/>
</div>
);
}
}
express code is:
const express = require("express");
const app = express();
const Tx = require("ethereumjs-tx");
var cors = require('cors')
const Web3 = require("web3");
const web3 = new Web3(
"https://ropsten.infura.io/v3/d55489f8ea264a1484c293b05ed7eb85"
);
app.use(cors());
const abi = [...]
const contractAddress = "0x15E1ff7d97CB0D7C054D19bCF579e3147FC9009b";
const myAccount = "0x59f568176e21EF86017EfED3660625F4397A2ecE";
const privateKey1 = new Buffer(
"...privateKey...",
"hex"
);
app.post("/", function(req, res, next) {
var hashValue = req.body.hash,
fileName = req.body.fileName,
value = req.body.value;
const contract = new web3.eth.Contract(abi, contractAddress, {
from: myAccount
// gas: '50000'
});
web3.eth.getTransactionCount(myAccount, (err, txCount) => {
//Smart contract data
const data = contract.methods
.setHashValue(value + " " + fileName + " " + hashValue)
.encodeABI();
// Build the transaction
const txObject = {
nonce: web3.utils.toHex(txCount),
gasLimit: web3.utils.toHex(1000000),
gasPrice: 20000000000,
data: data,
from: myAccount,
to: contractAddress
};
// Sign the transaction
const tx = new Tx(txObject);
const serializedTx = tx.serialize();
// const raw = '0x' + serializedTx.toString('hex')
// Broadcast the transaction
web3.eth
.sendSignedTransaction("0x" + serializedTx.toString("hex"))
.on("receipt", console.log);
next();
});
});
app.listen(3000, () => console.log("listening on 3000"));
I would reiterate that the server is broadcasting the Ethereum transaction as intended. The reason that I am asking is because I do not want errors, and am checking to see if this is part of a larger issue I'm having with a json return call.
Any help is appreciated. Thanks!
I resolved this by adding a res.json()
web3.eth
.sendSignedTransaction("0x" + serializedTx.toString("hex"))
.on("receipt", console.log, res.json);

Resources