What is the easiest way to connect to Memgraph using Node.js? - memgraphdb

I want to test the creation of an application that uses Node.js and Memgraph. What is the fastest and easiest way for me to test this type of setup?

The easiest way is to use Express.js. Here are the exact steps:
Create a new directory for your application, /MyApp and position yourself in it.
Create a package.json file using npm init
Install Express.js using npm install express --save and the Bolt driver using npm install neo4j-driver --save in the /MyApp directory. Both packages will be added to the dependencies list.
To make the actual program, create a program.js file with the following code:
const express = require("express");
const app = express();
const port = 3000;
var neo4j = require("neo4j-driver");
app.get("/", async (req, res) => {
const driver = neo4j.driver("bolt://localhost:7687");
const session = driver.session();
try {
const result = await session.writeTransaction((tx) =>
tx.run(
'CREATE (a:Greeting) SET a.message = $message RETURN "Node " + id(a) + ": " + a.message',
{
message: "Hello, World!",
}
)
);
const singleRecord = result.records[0];
const greeting = singleRecord.get(0);
console.log(greeting);
} finally {
await session.close();
}
// on application exit:
await driver.close();
});
app.listen(port, () => {
console.log(`Example app listening at http://localhost:${port}`);
});
Once you save the file, you can run your program using node program.js.
For additional details check the official Memgraph documentation.

Related

add API key to url

Hi I'm build a wildfire app tracker with react using the nasa API it works in development by using the url directly witch is https://eonet.sci.gsfc.nasa.gov/api/v2.1/events
But when I deploy it. It does not get the data. I obviously need a api key witch I have, but how do I implement it in the url above ?
here is my code..
useEffect(() => {
const fetchEvents = async () => {
setLoading(true)
const res = await fetch('https://eonet.sci.gsfc.nasa.gov/api/v2.1/events')
const {events} = await res.json()
setEventData(events)
setLoading(false)
}
fetchEvents()
// eslint-disable-next-line
}, [])
You could try to create a .env file in which you can set URLS as
REACT_APP_PUBLIC_URL=https://eonet.sci.gsfc.nasa.gov/api/v2.1/events
and then in your app component import as
fetch(process.env.REACT_APP_PUBLIC_URL)

Why nexus dev command runs app twice, and how to fix it?

I created super simple application using nexus graphql framework.
First step like this:
https://www.nexusjs.org/#/tutorial/chapter-1-setup-and-first-query
I api/app.ts i typed code:
const uid = require('uid')
let i = 0;
const sleep = async (ms: number) => {
return new Promise((resolve, reject) => {
setTimeout(resolve, ms)
})
}
const recurrenceFunction = async (id:string): Promise<void> => {
i++;
console.log(id, i);
await sleep(2000);
return recurrenceFunction(id)
}
const startQueue = () => {
const id:string = uid();
return recurrenceFunction(id)
}
(async () => {
return startQueue()
})()
Only dependency is uid that generates unique keys.
When I run it with ts-node I can see:
So we can see:
Once queue started.
There is single queue.
It works as it should work.
But when I run this code with nexus by command nexus dev I have seen:
So:
Two queues started.
They are running at the same time.
They have independently created variables i.
Questions:
Is anyone meet with this problem?
How should I change my code to get single queue like in ts-node?
Or maybe it is bug of nexus?
Update:
I checked that this problem exists for verions >= 0.21.1-next.2
In 0.21.1-next.1 application runs single time.
Steps to reproduce:
nexus dev
npm i nexus#0.21.1-next.1
nexus dev
npm i nexus#0.21.1-next.2
there is commit that introduced this behavior:
https://github.com/graphql-nexus/nexus/commit/ce1d45359e33af81169b7ebdc7bee6718fe313a8
There is variables like onMainThread and REFLECTION_ENV_VAR but without references to documentation. I can't understand what this code is doing?
This probably will be documented in future in this place:
https://www.nexusjs.org/#/architecture?id=build-flow
but now there is:
Update 2
I found woraround:
const xid = uid();
let limit=10;
const onApplicationStart = async (cb: () => any):Promise<any> => {
console.log("can i start?", xid, limit, app.private.state.running);
if(app.private.state.running) {
await cb()
return;
}
limit--;
if(limit <= 0) return ;
await sleep(100);
return onApplicationStart(cb);
}
(async () => {
return onApplicationStart(async () => {
return startQueue()
})
})()
but this is rather temporary hack than solution. Full example:
https://github.com/graphql-nexus/nexus/discussions/983
Eager module code relying on side-effects is not supported by Nexus.
See:
https://www.nexusjs.org/#/tutorial/chapter-2-writing-your-first-schema?id=reflection
https://github.com/graphql-nexus/nexus/issues/758
For a workaround for now wrap your code like this:
// app.ts
if (!process.env.NEXUS_REFLECTION) {
yourHeavyAsyncCode()
}
Reference https://github.com/graphql-nexus/nexus/issues/732#issuecomment-626586244

Unable to issue identity card using Hyperledger Composer Javascript API

I am trying to create an identity card using the javascript API of Hyperledger Composer. Here is the code:
const BusinessNetworkConnection = require('composer-
client').BusinessNetworkConnection;
async function identityIssue() {
let businessNetworkConnection = new BusinessNetworkConnection();
try {
await businessNetworkConnection.connect('admin#demoNetwork');
let result = await businessNetworkConnection.issueIdentity('org.acme.demoNetwork.Participant#testUser', 'test');
console.log(`userID = ${result.userID}`);
console.log(`userSecret = ${result.userSecret}`);
await businessNetworkConnection.disconnect();
} catch(error) {
console.log(error);
process.exit(1);
}
}
identityIssue();
I already have a participant testUser.
Although the code succeeds and I get the userID and userSecret, no card is created.
Does anyone have an idea how to do it instead of using the cli?
You haven't imported the card.
eg,
async function importCardForIdentity(cardName, identity) {
const metadata = {
userName: identity.userID,
version: 1,
enrollmentSecret: identity.userSecret,
businessNetwork: businessNetworkName
};
const card = new IdCard(metadata, connectionProfile);
await adminConnection.importCard(cardName, card);
}
See also nodejs test hyperledger composer v0.15 fails with Error: Card not found: PeerAdmin#hlfv1 (answer) it has an example too.
After importing, you should connect with your card to download the cert/key to the wallet eg await businessNetworkConnection.connect(cardName);

how to install mqtt library on AWS lambda function

i want to publish a mqtt message from AWS lambda function, i tried this
`exports.handler = function(event, context) {
// TODO implement
context.done(null, 'Hello from Lambda');
const mqtt = require('mqtt');
const client = mqtt.connect('mqtt://broker.hivemq.com');
var state = 'closed';
client.on('connect', () => {
console.log("connected to broker");
// Inform controllers that garage is connected
client.publish('garage/connected', 'true')
})
};
`
You need to create a zip file with the node_modules directory and the source file for your lambda.
e.g.
lamdba.js
node_modules/mqtt
node_modules/mqtt/package.json
...
You should use npm to install the package locally.
The details are described in the Lambda documentation here

react-native unable to resolve module 'events'

I have created an empty project with the following command:
react-native init demoProject
after installing
npm install -g react-native-cli
then I have installed mongoDB with the following command:
npm install mongodb --save
In the package.json file I have the following:
"dependencies": {
"events": "^1.1.1",
"mongodb": "^2.2.31",
"react": "16.0.0-alpha.12",
"react-native": "0.47.1"
},
In the index.ios.js file I am trying to import the mongodb as the following:
var MongoClient = require('mongodb').MongoClient;
After building the project in Xcode I have this error:
bundling failed: "Unable to resolve module `events` from `/Users/rzilahi/work/demo01/node_modules/mongodb/lib/apm.js`: Module does not exist in the module map
what am i doing wrong?
Why are you importing MongoClient to index.ios.js ? It shouldn't be imported in the index or any other file of your app. Database queries should be done in a webservice. So in your app, you can use fetch to retrieve data from a webservice and render that with a FlatList or component of choice. You can create a NodeJS project on port 1337 (example port) and run the Node Server. In that Node Project you need to import MongoClient and query the DB for data and use res.send or res.json to send the data back as a response. So if you're able to access your webservice at http://localhost:1337/getdata , you're all set.
You may need to use your actual IP address of the computer in fetch, like:
fetchData(){
fetch('http://192.168.0.4:1337/getdata')
.then((response) => response.json())
.then((responseJson) => {
this.setState({data: responseJson})
})
.catch((error) => {
alert(error);
});
}
And your node server would look something like:
var express = require('express'),
bodyParser = require('body-parser'),
mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/mydb');
var db = mongoose.connection;
mongoose.Promise = global.Promise;
var app = express();
//create the Posts Schema or import it.
app.get("/getdata", function(req, res){
Posts.find({}, function(e,doc){
if(doc==null){
res.send("NO POSTS");
}
else{
res.json(doc);
}
});
});
app.set('port', (process.env.PORT || 1337));
app.listen(app.get('port'), function(){
console.log("Server started on port: " + app.get('port'));
});

Resources