Unable to replicate couchDB contents in pouchDB in react-native - couchdb

I've created a react-native project with pouchDB set up. Have installed couchDB. Trying out the same in react native using "pouchdb-react-native". The replication is not happening. I'm getting the error 'message: "getCheckpoint rejected with", name: "unknown"'. Here is following code:
import React, {
Component,
} from 'react';
import {
View,
Image,
StyleSheet,
Text
} from 'react-native';
import PouchDB from 'pouchdb-react-native'
const localDB = new PouchDB('todo');
const remoteDB = new PouchDB('http://username:password#127.0.0.1:5984/todo');
export default class Example extends Component {
constructor(props) {
super(props);
}
componentDidMount() {
// Get records
localDB.allDocs({include_docs: true})
.then(results => {
results.rows.map(row => {
console.log(row.doc);
})
}).catch(err => alert('Err in fetching all records'));
localDB.sync(remoteDB,
function(err, response) {
if (err) {
return console.log(err);
} else {
console.log(response);
}
});
localDB.changes({
live: true,
include_docs: true
}).on('change', () => {
console.log("Event changed in localDB");
this.getAllRecords();
})
.on('complete', () => {
console.log("Event complete in localDB");
this.getAllRecords();
})
.on('error', () => alert("Error"))
}
render() {
return (
<View style={styles.container}>
<Text>Example screen</Text>
</View>
);
}
}
Please help on this. The package.json looks something like this:
"pouchdb": "^6.3.4",
"pouchdb-react-native": "^6.3.4",
"react": "16.0.0-alpha.12",
"react-native": "0.47.2",
What is wrong here? and how can this be debugged?
Also tried replacing the sync portion with below code:
const sync = localDB.sync(remoteDB, {
live: true,
retry: true,
direction: 'from'
});
sync
.on('change', pay_load => {
console.log(" changed!: ");
}).on('paused', info => {
console.log("paused");
}).on('denied', info => {
console.log("paused");
}).on('complete', info => {
console.log("paused");
}).on('active', info => {
console.log("Active");
}).on('error', err => {
console.log("error", err);
}).catch( err => {
console.log("Error: ",err)
});
sync goes only into "paused" state.

I get this same error when I disconnect from the internet. Everything works fine when I reconnect. Maybe troubleshoot your connection ? I am using react native. Also, you may not need pouchdb in your package.json. I just have pouchdb-react-native which drags in the correct pouchDB.
Plus your url has 127.0.0.1 in it. I assume you just used that address to mask the real address or does that address suppose to correspond with a couchDB server you have running on your dev machine. You may need to change that address to the actual address of your couchDB server such as 192.168.1.whatever. I think 127.0.0.1 on your device or simulator will look for a server on the device or simulator not on your dev machine. Hope this helps.
Warren Bell

Related

Asynchronous Nodejs communication with GRPC protocol

I'm trying to build a nodejs/express project that communicate between server/client with grpc protocol, in order to make simple Users CRUD action and display datas on the front-end.
Currently, the server side works fine with mysql librairy and a MariaDB database.
As far as I can see within the console, the server side send the datas as expected, but I can't manage to retrieve them on the client side.
Here is the revelent code :
In the server.js file, server side :
server.addService(customersProto.CustomerService.service, {
getAll: async(_, callback) => {
const allUsers = await sql.getAll(db);
callback(null, { allUsers });
console.log(allUsers);
},
}
The ouput of the console.log :
[{"id":"a68b823c-7ca6-44bc-b721-fb4d5312cafc","name":"David","age":33,"adress":"227th Baker Street"},{"id":"a68b823c-7ca6-44bc-b721-fb4d5312cahg","name":"Peter","age":99,"adress":"38th King Street"}
In the index.js file, client side :
async function getAll() {
return new Promise((resolve, reject) => {
client.getAll(null, (err, data) => {
if (!err) {
console.log("fonction getAll : " + JSON.stringify(data));
resolve(JSON.stringify(data));
} else {
reject(err);
}
});
});
}
app.get("/", async(req, res) => {
const data = await getAll();
console.log(data);
res.render("customers", {
results: JSON.stringify(data),
});
});
The output of the console.log :
fonction getAll : {"customers":[]}
{"customers":[]}
I don't understand why the array is empty...
Have you got an idea to retrieve my datas ?
Nevermind, I've found my problem.
Because the Proto Buffer needs an array of "customers", I didn't realise that I couldn't give any name to the variable in the callback of the getAll function (server side).
That solve the problem : In the server.js file, server side :
server.addService(customersProto.CustomerService.service, {
getAll: async(_, callback) => {
const customers = await sql.getAll(db);
callback(null, { customers });
);
},
}

Site with node js and express / ejs does not always load images

I set up a website that basically uses Nodejs to fetch the image and after that sends it to ejs to display on the page, what happens is that sometimes the image appears and sometimes it looks like the website loads before the image can be loaded by the node.
I left the two ways I tried, one commented and the other that was the last one I tried.
This is app.js
function retornaImagens(id){
let imagens= {
assPacUrl: ''
}
/*
if (fs.existsSync(`${__dirname}\\arquivos\\consultas\\${id}\\assPac.png`)) {
fs.readFile(
`${__dirname}\\arquivos\\consultas\\${id}\\assPac.png`, 'base64',
(err, base64Image) => {
if (err) {
console.log(err)
} else {
imagens.assPacUrl = `data:image/png;base64, ${base64Image}`
}
}
)
}
*/
fs.access(`${__dirname}\\arquivos\\consultas\\${id}\\assPac.png`,(err)=>{
if(err){}else{
fs.readFile(
`${__dirname}\\arquivos\\consultas\\${id}\\assPac.png`, 'base64',
(err, base64Image) => {
if (err) {
console.log(err)
} else {
imagens.assPacUrl = `data:image/png;base64, ${base64Image}`
}
}
)
}
})
return imagens;
}
app.get('/consultas/:id/termo',(req,res)=>{
var imagens = retornaImagens(req.params.id);
Consulta.findOne({link:`/consultas/${req.params.id}/login`}).populate('medico paciente').exec((err,consulta)=>{
if(err){
console.log(err)
}else{
console.log(imagens)
res.render('consulta/termo',{consulta:consulta,id:req.params.id,imagens})
}
})
})
This is the ejs file
<img src="<%= imagens.assPacUrl %>">
If you have tips to make the code cleaner and consume less memory, please send me.
The problem was in the loading time, it was taking longer to load the image so the program continued and rendered the website empty, adding a settimeOut.
function enviaTermo(data){
Consulta.findOne({link:data.link}).populate('medico paciente').exec((err, consulta) => {
if (err) {
console.log(err)
} else {
console.log(imagens)
io.to(consulta._id).emit('termo', { consulta: consulta, imagens: imagens })
}
})
}
setTimeout(() => {
enviaTermo(data)
}, 450);

Cant load protobuf message with protobuf.js

Im trying to use proto messages with protobuf.js, encode them and send them to a RabbitMQ message broker. I have the following sub-folders inside my project:
- model
- protos
- transactions.proto
- RabitMQ.js
- routes
- rmq-api.js
I added a route which does the following(Using express) in the rmq-api.js file:
const RabbitMQ = require('../model/RabbitMQ');
router.post('/api/transactions' ,function (req,res,next) {
RabbitMQ.PublishTransactionsMessage(DummyMessage).then(() => {
res.status(200).send({message: "OK :)"});
}).catch((e) => {
res.status(500).send({error:e.message});
});
});
In the RabitMQ.js file I have the following code:
module.exports = {
PublishTransactionsMessage: function(message) {
return new Promise((resolve, reject) => {
amqp.connect(RabbitMQConfig.url, function (error, connection) {
if (error) {
console.error("Could not connect to the rabbit message broker on {0} - " +
"Check connection please and try again".format(RabbitMQConfig.url));
console.error("Error message - {0}".format(error));
reject(error)
}
connection.createChannel(function(error, channel) {
if (error) {
console.error("Could Create channel - {0}".format(error.message));
reject(error)
}
const queue = RabbitMQConfig.queue;
channel.assertQueue(queue, {
durable: true
});
// Convert Message to protobuff
protobuf.load("./protos/transactions.proto").then((err, root) => {
if (err) {
reject(err);
}
let ScraperMessageResult = root.lookupType("transactions.ScraperMessageResult");
const errMsg = ScraperMessageResult.verify(message);
if (errMsg)
reject(errMsg);
let buffer = ScraperMessageResult.encode(message).finish();
channel.sendToQueue(queue, buffer);
console.log(`Sent ${message} to queue: ${queue}`);
resolve()
}).catch((err) => {
reject(err);
});
});
});
});
},
};
In the code shown above in the line:
protobuf.load("./protos/transactions.proto").then((err, root) => {
I keep catching the following error:
Inside this catch block:
}).catch((err) => {
reject(err);
});
This seems like a pretty simple problem however I havent found anything on this online so I might be missing something really simple here.
P.S. I tried using __dirname + "/protos/transaction.proto" and still couldnt get this to work.
Please help me figure this out.
The problem is that your function doesn't look at the dist directory,
await protocolBuffer.load(__dirname + '/item.proto'); should look there,
and also you need to copy the file manuly by using copy/cp command, you can add it as part of the package json script like so:
"build": "nest build && COPY src\\reading_list\\protocol_buffer\\*.proto dist\\reading_list\\protocol_buffer\\"

Sequelize transaction always returning null

I'm writing the backend for creating audit protocols. The user should be able to create criterias for the audit protocol. For this, i have the following backend-method to make sure, the protocol gets only created completely or the process of creating is canceled. It is possible to set several kinds of forms / criterias. But it could be, that only one kind of form is required. I do check that with the if-statement.
The creating works as expected. But the REST API always returns null to the clients. So i can't do further processing on the frontend regarding to the result of the creation process.
Technologies: Node.js and Sequelize. Frontend in angular / ionic. Database in mySQL.
I tried around with some transaction passing and return statements. I tried to compare it to a similiar code snippet, which works as expected.
exports.setAudit = (req, res, next) => {
trueFalseCriteria = req.body.trueFalseForms;
isShouldCriteria = req.body.isShouldForms;
generalCriteria = req.body.generalForms;
measurementCriteria = req.body.measurementForms;
toolId = req.body.toolId;
// Transaction is used to roll the whole transaction back if something wents wrong
return sequelize
.transaction(t => {
return audit
.create(
{
// Creating an audit referencing the tool
toolId: toolId
},
{ transaction: t }
)
.then(
// Getting the id of the audit that we just created
audit => {
return audit.id;
},
{ transaction: t }
)
.then(auditId => {
// Check wether the kind of form is used or not. If so, sequelize tries to do a bulk insert into the databases.
// Each bulk insert throws an error if it fails to cancel the whole transaction
if (trueFalseCriteria) {
console.log(1);
trueFalseCriteria.forEach(dataEl => {
dataEl.auditId = auditId;
});
trueFalseCriterion.bulkCreate(trueFalseCriteria).catch(err => {
// Throw error to cancel transaction
throw new Error(err);
});
}
if (isShouldCriteria) {
console.log(2);
isShouldCriteria.forEach(dataEl => {
dataEl.auditId = auditId;
});
isShouldCriterion.bulkCreate(isShouldCriteria).catch(err => {
// Throw error to cancel transaction
throw new Error(err);
});
}
if (generalCriteria) {
console.log(3);
generalCriteria.forEach(dataEl => {
dataEl.auditId = auditId;
});
generalCriterion.bulkCreate(generalCriteria).catch(err => {
// Throw error to cancel transaction
throw new Error(err);
});
}
if (measurementCriteria) {
console.log(4);
measurementCriteria.forEach(dataEl => {
dataEl.auditId = auditId;
});
measurementCriterion.bulkCreate(measurementCriteria).catch(err => {
// Throw error to cancel transaction
throw new Error(err);
});
}
}, { transaction: t });
})
.then(data => {
console.log(5);
res.status(200).json(data);
})
.catch(err => {
console.log(6);
if (!err.statusCode) {
err.statusCode = 500;
}
next(err);
});
};
Expected result: Http response with status code 200 on success
Actual result: null
I think you are missing a return for the last .then():
.then(auditId => {
// Check wether the kind of form is used or not. If so, sequelize tries to do a bulk insert into the databases.
.....
if (measurementCriteria) {
....
}
// RETURN SOMETHING HERE
}, { transaction: t });

Buildfire - bulkInsert Error

I'm trying to do a bulkInsert but I keep getting a 400 error message:
{code: "VALIDATION", message: "Invalid parameters"}
Here is my code:
import React, { Component } from 'react';
class App extends Component {
constructor(props) {
super(props);
this.testFn = this.testFn.bind(this);
}
testFn() {
const data = [{name:"John Doe", tel:"555-111-1111"},{name:"John Doe", tel:"555-222-2222"}];
buildfire.publicData.bulkInsert(data, 'testTag', function(err, res) {
if (err) {
console.log("ERROR", err);
} else {
console.log("SUCCESSFULLY BULK INSERTED", res);
}
});
}
render() {
return (
<div>
<button onClick={this.testFn}>Test Insert</button>
</div>
);
}
}
export default App;
If I change buildfire.publicData.bulkInsert to buildfire.publicData.insert the call is successful and I can find my array in res.data but I want each object to create it's own record. The example data I am trying to save is coming straight from the docs.
I had been able to reproduce the issue that you described, although it seems to no longer be a problem. Perhaps it was a temporary glitch, or something was changed in the system recently.
I'd suggest trying again, as it appears to be working fine now.

Resources