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);
};
Related
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,
I create a little NFT marketplace using solidity and hardhat. I have a JSON file with the NFT details and I wrote a hardhat task for automating the process.
task("populate-market", "populate market with nfts").setAction(async function (
taskArguments,
hre
) {
const [owner] = await hre.ethers.getSigners();
const Market = await hre.ethers.getContractFactory("NFTMarket");
const market = await Market.deploy(owner.address);
await market.deployed();
const marketAddress = market.address;
/* deploy the NFT contract */
const Item = await hre.ethers.getContractFactory("Item");
const nft = await Item.deploy(marketAddress);
await nft.deployed();
for (const item of nfts) {
const transaction = await nft.createToken(item.url);
const tx = await transaction.wait();
const event = tx.events[0];
const tokenId = event.args[2].toNumber();
const price = hre.ethers.utils.parseUnits(item.price.toString(), "ether");
await market.createMarketItem(nft.address, tokenId, price, item.supply);
}
console.log(await market.fetchMarketItems());
console.log("done!");
});
the problem it's when I load the data in my react app; I created an function getNfts() like this:
useEffect(() => getNfts(), []);
const getNfts = async () => {
const provider = new ethers.providers.JsonRpcProvider();
const nftContract = new ethers.Contract(NFT_ADDRESS, NFT.abi, provider);
const marketContract = new ethers.Contract(
MARKET_ADDRESS,
Market.abi,
provider
);
const data = await marketContract.fetchMarketItems();
console.log(data);
};
in this function data it returns empty array but, in task the console.log(await market.fetchMarketItems()); it returns all nfts. I don't understand why in the task it returns data but, in react it shows me an empty array. How to fix this?
Try to do this:
async function getNfts() {
// The rest of the code goes here
}
Basically use a function instead a variable asigned to a function. Sometimes there are errors with the this keyword that are not being passed correctly and it breaks the functionality of the library.
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
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')
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);