How do catch error on React Native SQLite - sqlite

I have the code:
let dirs = RNFetchBlob.fs.dirs
RNFetchBlob
.config({
fileCache : false,
})
//pega o arquivo da internet
.fetch('GET', 'https://URL_WITH_QUERY_TEXT')
.then((res) => {
//lĂȘ o arquivo salvo anteriormente
db.transaction((tx) => {
var sql = res
tx.executeSql(sql, [], (tx, results) => {
alert('OK!')
})
.catch((error) => alert(error));
});
})
I not receive none alert.
Can I catch the error correctly?

Please try using the following way after the response use comma(,) and console error callback.
dbConnection.transaction(function (tx) {
tx.executeSql(query, values, async (tx1) => {
dispatch(clearTodos());
const data = await getTodosFromDbMethod(dbConnection, 1);
}, (error) => {
console.log("error: " + JSON.stringify(error))
reject(error);
});
});

Related

How to correctly return the result from Cloud Function?

I am trying to implement verification using Cloud Function and Twilio. Twilio works correctly and SMS with the code is sent, but in the Flutter application I get the error [firebase_functions / deadline-exceeded] DEADLINE_EXCEEDE. What am I doing wrong?
Cloud Function:
const accountSid = process.env.TWILIO_ACCOUNT_SID;
const authToken = process.env.TWILIO_AUTH_TOKEN;
const client = require('twilio')(accountSid, authToken);
exports.sendSms = (req, res) => {
console.log('start sendSms');
var func = client.verify.services('xxxxx')
.verifications
.create({to: req.body.data.phone, channel: 'sms'})
.then(verification => {return verification})
.then(result => {
if (result.status === 'pending')
return {status: 'success', result: "pending"};
else
return {status: 'error', error_code: -1, error_msg: result.status};
})
.catch(e => {
return {status: 'error', error_code: e.code, error_msg: e.message};
});
return Promise.all([func]).then(result => {
console.log(result); // console output [ { status: 'success', result: 'pending' } ]
return result[0];
});
};
Flutter:
HttpsCallable callable = FirebaseFunctions.instanceFor(region: 'europe-west3').httpsCallable(
'send-sms',
options: HttpsCallableOptions(timeout: const Duration(seconds: 10))
);
dynamic results = await callable.call(<String, dynamic>{'phone': phoneNumber});
The create method returns promise too so you must add the return keyword there as well.
Instead of:
var func = client.verify.services('xxxxx')
Try this:
exports.sendSms = functions.https.onCall((data, context) => {
//^^^^^^^^^^^^^^^^^^^^^^
console.log('start sendSms');
return client.verify.services('xxxxx')
.verifications
.create({to: data.phone, channel: 'sms'})
.then(verification => {return verification})
.then(result => {
if (result.status === 'pending')
return {status: 'success', result: "pending"};
else
return {status: 'error', error_code: -1, error_msg: result.status};
})
.catch(e => {
return {status: 'error', error_code: e.code, error_msg: e.message};
});
});
That being said you don't need this part:
return Promise.all([func]).then(result => {
console.log(result); // console output [ { status: 'success', result: 'pending' } ]
return result[0];
});

cy.task does not perform update

I'm trying to get Cypress to perform an update on the database before running the test. I did it as follows but it doesn't work
/cypress/plugins/index.js
module.exports = (on, config) => {
on('task', {
sybaseQuery() {
var Sybase = require('sybase'),
db = new Sybase('host', '4400', 'dbname', 'user', 'pass');
db.connect(function (err) {
if (err) return console.log(err);
db.query('', function (err, data) {
if (err) console.log(err);
console.log(data);
db.disconnect();
});
});
return null
}
})
}
test
it('Dado que esteja preenchido a data de ultima consulta e numero de prazo de entrega', () => {
cy.task('sybaseQuery',"update dbo.CARTAO_USU_CARTAO_COMPLEMENTO set nr_prazo_entrega_cartao = '25' where nr_cartao = '6035740409054753'")
See previous answer, you should use
sybaseQuery(queryString) {
not
sybaseQuery() {
and
db.query('', function (err, data) {
will do nothing.
It should be
db.query(querystring, function (err, data) {

Angular filtering problem when using pipe and map response

shop.service.ts code
getProducts(brandId?: number, typeId?: number) {
let params = new HttpParams();
if (brandId){
params = params.append('brandId', brandId.toString());
}
if (typeId){
params = params.append('typeId', typeId.toString());
}
return this.http.get<IPagination>(this.baseUrl + 'products', {observe: 'response', params})
.pipe(
map(response => {
return response.body;
})
);
}
and shop.component.ts code here
getProducts(){
this.shopService.getProducts(this.brandIdSelected, this.typeIdSelected).subscribe(response => {
this.products = response.data;
}, error => {
console.log(error);
});
}
Please see those code and give me a suggestion Why response.data is showing error in shop.component.ts?
Note: Object is possiblly 'null' : ts(2531) error message showing.
It's because http.get() might return no value.
this.http.get<IPagination>(this.baseUrl + 'products', {observe: 'response', params}).pipe(map(response => {
// response can be null or undefined and so can response.body
return response.body;
})
);
But here you do not take this possibility into account and directly try to access response.data.
getProducts(){
this.shopService.getProducts(this.brandIdSelected, this.typeIdSelected).subscribe(response => {
this.products = response.data;
}, error => {
console.log(error);
});
Do it with an if-condition. Then the compiler won't throw this error.
getProducts(){
this.shopService.getProducts(this.brandIdSelected, this.typeIdSelected).subscribe(response => {
// only if response is not null or undefined, access the data-field
if (response) {
this.products = response.data;
}
}, error => {
console.log(error);
});

Firebase get request querying multiple tables

I'm trying to send get request to get the information of a row and that of its comments and options (rows, comments, options are all different tables). Currently, the request returns the row and comment info, but an empty array for the options, like so:
{
"categoryId": "Category1",
"dataType": "Text",
"approveCount": 0,
"createdAt": "10:00",
"body": "testneww",
"disapproveCount": 0,
"index": 1,
"visit": "Both",
"rowId": "ID",
"comments": [
{
"rowId": "ID",
"createdAt": "2021-02-28T21:32:52.841Z",
"body": "test comment"
}
],
"options": []
}
code:
exports.getOneRow = (req, res) => {
let rowData = {};
db.doc(`/rows/${req.params.rowId}`)
.get()
.then((doc) => {
if (!doc.exists) {
return res.status(404).json({ error: 'Row not found' });
}
rowData = doc.data();
rowData.rowId = doc.id;
return db
.collection('comments')
.orderBy('createdAt', 'desc')
.where('rowId', '==', req.params.rowId)
.get();
})
.then((data) => {
rowData.comments = [];
data.forEach((doc) => {
rowData.comments.push(doc.data());
})
return db
.collection('options')
.orderBy('index', 'asc')
.where('rowId', '==', req.params.rowId)
.get();
})
.then((newData)=>{
rowData.options = [];
newData.forEach((newDoc) => {
rowData.options.push(newDoc.data());
})
return res.json(rowData);
})
.catch((err) => {
console.error(err);
res.status(500).json({ error: err.code });
});
};
I presume I'm making a silly mistake somwhere, or is it not possible to do a request like this? Any help appreciated!
The following code worked, I cant see any differences besides adding the parameters individually in 'rowData.options.push' near the end, however ive been staring at the same code for quite a while so please do let me know if im missing something else.
exports.getOneRow = (req, res) => {
let rowData = {};
db.doc(`/rows/${req.params.rowId}`)
.get()
.then((doc) => {
if (doc.exists) {
rowData = doc.data();
rowData.rowId = doc.id
return db
.collection("comments")
.where("rowId", "==", req.params.rowId)
.get();
} else{
return res.status(500).json({ error: err.code });
}
})
.then((data) => {
rowData.comments = [];
data.forEach((doc) => {
rowData.comments.push(doc.data());
});
return db
.collection("options")
.where("rowId", "==", req.params.rowId)
.orderBy("index", "asc")
.get();
})
.then((data) => {
rowData.options = [];
data.forEach((doc) => {
rowData.options.push({
index: doc.data().index,
body: doc.data().body,
rowId: doc.data().rowId,
});
});
return res.json(rowData);
})
.catch((err) => {
console.error(err);
return res.status(500).json({ error: err.code });
});
};

Cordova SQLite: database already open: data.db

I am trying to implement a chat app in Ionic 2 and I use SQLite.
I am however, getting the following error when I execute a executeSql on the database.
TypeError {stack: (...), message: "Cannot read property 'executeSql'
of undefined"}
But when I open the databse each transaction, I don't get the above error, but get the following warning:
database already open: data.db
I have been reading the Ionic and Cordova documentation, but cannot seem to understand what I am doing incorrect. If anyone can advise, I would appreciate it.
chatsStorageService.ts
public openDatabase(): Promise<Array<Message>> {
let promise: Promise<Array<Message>> = new Promise<Array<Message>>(resolve => {
console.log('openDatabase: ', this.database);
if (this.database && this.database != null) {
return Promise.all([this.refreshChats(this.database), this.refreshMessages(this.database)]).then(() => {
resolve(this.messages);
});
} else {
this.database = new SQLite();
this.database.openDatabase({
name: "data.db",
location: "default"
}).then(() => {
return Promise.all([this.refreshChats(this.database), this.refreshMessages(this.database)]).then(() => {
resolve(this.messages);
});
}, (error) => {
console.log("OPEN ERROR: ", error);
});
}
});
return promise;
}
public refreshChats(db: any): Promise<Array<Chat>> {
let promise: Promise<Array<Chat>> = new Promise<Array<Chat>>(resolve => {
return db.executeSql("SELECT * FROM chats", [])
.then((chatData) => {
let promises: Array<any> = [];
this.chats = [];
if (chatData.rows.length > 0) {
for (var i = 0; i < chatData.rows.length; i++) {
promises.push(this.populateChat(db, chatData.rows.item(i)));
}
}
return Promise.all(promises).then(() => {
resolve(this.chats);
});
})
.catch(error => {
console.log("ERROR REFRESHING CHATS: " + JSON.stringify(error));
console.log(error);
});
});
return promise;
}

Resources