react-native audio sending issue - file

I am trying to send an audio file but I think I am not selecting the file correctly.
I am using react-native-audio-toolkit and I was trying to use the rec object where it records, but that does not seem to work, how could I get the file to send it?
code:
let rec = new Recorder("filename.mp4").record();
// Stop recording after approximately 3 seconds
setTimeout(() => {
rec.stop(err => {
// NOTE: In a real situation, handle possible errors here
let data = new FormData();
data.append("recording[path_to_recording]", rec);
data.append("recording[challenge_id]", 1);
data.append("recording[user_id]", 1);
console.log(data);
axios
.post(config.API_URL + "recordings", data, {
headers: {
Authorization: "Bearer " + this.props.auth.token
}
})
.then(res => res.data);
the log of the recording file looks like this:
Recorder {_path: "filename.mp4", _options: {…}, _recorderId: 0, _state: -2, _duration: -1, …}
_duration
:
-1
_fsPath
:
"/data/user/0/com.cobrn/files/filename.mp4"
_lastSync
:
-1
_options
:
autoDestroy
:
(...)
get autoDestroy
:
ƒ ()
set autoDestroy
:
ƒ ()
proto
:
Object
_path
:
"filename.mp4"
_position
:
-1
_recorderId
:
0
_state
:
-2
canPrepare
:
(...)
canRecord
:
(...)
fsPath
:
(...)
isPrepared
:
(...)
isRecording
:
(...)
state
:
(...)
proto
:
EventEmitter

figured it out, you need the specify the type
data.append("recording[path_to_recording]", {
uri: "file://" + rec._fsPath,
name: "filename.mp4",
type: "audio/mp4"
});

Related

Showing Err For correct Code:'Cypress detected that you returned a promise from a command while also invoking one or more cy commands in that promise'

I have entered the code right, and it worked too. But now i dont know why i am getting same error on different lines of code each time i test. The error comes at the chained commands.
Sometimes its a chained Cy.find commands while sometimes its some other chained command.
::EDIT::
I have changed the code a bit tried doing different methods etc, but still getting the same error. So the code below(Code-1) is the cypress commands to execute the integration test. Since this particular test values might change so I made another file to pass all those values as a single object(Code-2).
FYI the code worked first time, when i didn't have Code-2, ie: when i manually inserted all those values.
Code-1:
/* eslint-disable no-undef */
import { cropFileName, testData } from '../test_case/quoteGen'
describe('waste-Quote-Generation-for-Permanant-Client', () => {
beforeEach(() => {
cy.visit('/login');
});
it('user login', () => {
// login
cy.findByPlaceholderText(/username/i).type(testData.username)
cy.findByPlaceholderText(/password/i).type(testData.pass)
cy.get('.newLoginPanelBtn').click();
// navigate to 'Sales' tab.
cy.findByRole('link', {
name: /sales/i,
timeout: 5000
})
.should('be.visible')
.click({ force : true });
// Click on 'Generate Quote'
cy.findByRole('link', {
name: /generate quote/i,
timeout: 5000
}).click({ force : true })
// cy.wait(3000)
// Select Template
cy.findByRole('link', {
name: /template/i,
timeout: 5000
})
.should('be.visible')
.click({ force : true })
// Select Client
if(testData.clientType!=='create')
cy.findByText(testData.client).click()
else{
cy.get('#newSiteName').click();
cy.get('#newSiteName').type(testData.client);
cy.get('#newSiteEmail').click();
cy.get('#newSiteEmail').type(testData.clientEmail);
cy.get('#createNewSite').click();
cy.wait(200);
cy.findByText(testData.client).click()
}
// Choose Type of Waste
if(testData.wasteTypeOpt.newName!==null){
cy.findByText(testData.wasteTypeOpt.name).click()
cy.get('#towAddNewBtn').click();
}else{
cy.findByText(testData.wasteTypeOpt.name).click()
cy.get('#towContinueBtn').click();
}
// Check if Job Card Exist
if(testData.jobCard.new){
cy.findByText(/create job card/i).click();
// Add Job Card and Verify Job Card
cy.get('.jobCardDiv1 .jobCardDivInpContentDiv:nth-child(6) .jobCardDivInp').click();
cy.get('.jobCardDiv1 .jobCardDivInpContentDiv:nth-child(6) .jobCardDivInp').type('1234');
cy.get('#jobCardDate > span:nth-child(2)').click();
cy.get('.MuiButton-textPrimary:nth-child(2) > .MuiButton-label').click();
cy.get('.newJobCardBtnActive').click({ force : true });
}
cy.get('#job-cards-list > div:first').click();
cy.get('.newJobCardBtnActive').click({ force : true })
// Select Attachments
cy.get('#attach-file-list').children().each((_,index, collection) => {
if(index!==3 && testData.attachments.includes(index))
collection.eq(index).click()
})
cy.get('#attach-file-list').children().findByText(cropFileName('safety attachments',25,5,5)).click()
setTimeout(() => {
cy.findByText(/add to attachment/i).click();
}, 3000);
cy.get('#quoteEditorButton').click();
// Click on 'Quote'
cy.get('#updateScopeOfWorkButton').click();
cy.get('#editTableEditorModal').find('tr').eq(0).then(tbrow => {
testData.scopeofWork.map((el, k) => {
cy.wrap(tbrow).findAllByPlaceholderText('Description').dblclick()
cy.wrap(tbrow).findAllByPlaceholderText('Description').type(el.descp)
cy.wrap(tbrow).find('.navbar-button').click();
cy.findAllByText(el.tow).click()
cy.wrap(tbrow).findByPlaceholderText('volume').dblclick()
cy.wrap(tbrow).findByPlaceholderText('volume').type(el.vol)
cy.wrap(tbrow).findByPlaceholderText('Unit').dblclick()
cy.wrap(tbrow).findByPlaceholderText('Unit').type(el.unit)
cy.wrap(tbrow).findByPlaceholderText('pricing').dblclick()
cy.wrap(tbrow).findByPlaceholderText('pricing').type(el.pricing)
if(k<testData.scopeofWork.length-1)
cy.get('#addNewRowScopeOfWork').click()
return 0
})
})
cy.get('#updateTableModalButton').click();
cy.get('#continueGNRTQT').click()
// Insert mail id, Click on Generate Quote.
cy.get('.quote-cnrf-to-layout:nth-child(2) .quote-cnrf-emails-input').click();
cy.get('.quote-cnrf-to-layout:nth-child(2) .quote-cnrf-emails-input').type(testData.email);
cy.get('.quote-cnrf-to-layout:nth-child(3) .quote-cnrf-emails-input').click();
cy.get('.quote-cnrf-emails-input:nth-child(2)').click();
cy.get('.quote-cnrf-emails-input:nth-child(2)').type('asdf');
cy.get('.quote-cnrf-emails-textarea').click();
cy.get('.quote-cnrf-emails-textarea').type('asdf');
if(testData.sendType)
cy.get('#generateandsend').click();
else
cy.get('#approvedQuote').click();
cy.get('.swal2-confirm').click();
})
})
Code 2:
export const testData = {
username : 'Tester',
pass : '##tester001',
tabType : "",
template : /template/i,
clientType : 'permanent', // permanent, temporary, create
client : /geolocated site/i,
clientEmail : null,
wasteTypeOpt: {
name : /dilution pit/i,
newName : null, },
jobCard : {
new : false,
},
attachments : [],
scopeofWork : [
{ descp : 'asdf',
tow : /grease/i,
vol : '10',
unit : '5',
pricing : '2'
}
],
email : 'asdf#asdf.com',
sendType : true // true => 'Generate and send', false => 'Approved Quote'
}
export const cropFileName = (str, len, frnt, lst) => {
RegExp.escape = function(string) {
return string.replace(/[-\\^$*+?.()|[\]{}]/g, '\\$&')
};
let lastIndx = str ? str.length : 0
if(lastIndx <= len){
return new RegExp(str, "i")
}
else{
console.log('NewREgExp=>',new RegExp(RegExp.escape(str.substring(0,frnt)+'...'+str.substring(lastIndx-lst,lastIndx))))
return new RegExp(RegExp.escape(str.substring(0,frnt)+'...'+str.substring(lastIndx-lst,lastIndx)))
}
}
// ENCASE STRING in CASE INSENSITIVE \i
The 'cropFileName' function is used to manage all those long names. The long names will be snipped in CSS or JS by frontend, 'cropFileName' helps to determine the length of the string and decide whether to add '.' in between the string for RegEx conversion.

Nativescript Class constructor Observable cannot be invoked without 'new'

I'm trying to upload a multipart form in nativescript and I'm using http-background. I keep getting the error Class constructor Observable cannot be invoked without 'new'. I've tried changing the compilerOptions target to es5 and es2017, but nothing changed.
Here's all my code from the component.
onSave(){
console.log("clicked")
this.proccessImageUpload(this.file);
}
public onSelectSingleTap() {
this.isSingleMode = true;
let context = imagepicker.create({
mode: "single"
});
this.startSelection(context);
}
private startSelection(context) {
let that = this;
context
.authorize()
.then(() => {
that.imageAssets = [];
that.imageSrc = null;
return context.present();
})
.then((selection) => {
console.log("Selection done: " + JSON.stringify(selection));
this.file = selection[0]._android;
that.imageSrc = that.isSingleMode && selection.length > 0 ? selection[0] : null;
// set the images to be loaded from the assets with optimal sizes (optimize memory usage)
selection.forEach(function (element) {
element.options.width = that.isSingleMode ? that.previewSize : that.thumbSize;
element.options.height = that.isSingleMode ? that.previewSize : that.thumbSize;
});
that.imageAssets = selection;
}).catch(function (e) {
console.log(e);
});
}
// proccess image function
proccessImageUpload(fileUri) {
var backgroundHttp = require("nativescript-background-http");
return new Promise((resolve, reject) => {
// body...
var request = {
url: 'http://192.168.0.2:4000/api/posts',
method: "POST",
headers: {
"Content-Type": "application/octet-stream",
"user_id": "<user_id>"
},
description: 'Uploading profile image..',
androidAutoDeleteAfterUpload: false,
androidNotificationTitle: 'Profile image'
}
var params = [
{ name: "title", value: "test" },
{ name: "content", value: "test" },
{ name: "fileToUpload", filename: fileUri, mimeType: "image/jpeg" }
];
var backgroundSession = backgroundHttp.session('image-upload');
var task = backgroundSession.uploadFile(fileUri, request);
task.on("progress", (e) => {
// console log data
console.log(`uploading... ${e.currentBytes} / ${e.totalBytes}`);
});
task.on("error", (e) => {
// console log data
console.log(`Error processing upload ${e.responseCode} code.`);
reject(`Error uploading image!`);
});
task.on("responded", (e) => {
// console log data
console.log(`received ${e.responseCode} code. Server sent: ${e.data}`);
// var uploaded_response = JSON.parse(e.data);
});
task.on("complete", (e) => {
// console log data
console.log(`upload complete!`);
console.log(`received ${e.responseCode} code`);
// console.log(e.data);
})
resolve(task);
});
}
I know the issue is coming from this line.
var task = backgroundSession.uploadFile(fileUri, request);
Any help would be greatly appreciated!
You use old version if nativescript-background-http plugin
You have to install latest version
tns plugin add #nativescript/background-http
I was able to get this working by installing tns version 6.
I had exactly the same problem. I got this from slack.com, compliments Chris Vietor
"tns plugin add nativescript-background-http" works with nativescript 6.
"tns plugin add #nativescript/background-http" works with nativescript 7.

`node` api getting error on `post` - body param being as labels how to solve this?

I am posting the data to back-end using postman, which works fine. Using the same api I am trying to post the data through angular gives me the issue. But I understand that something going on wrongly between my form data with post process which i am not able to understand.
here is the post function:
.post(function( req, res ){
console.log(' called ', req.body ); 1. //getting all properties
var family = new Family();
family.username = req.body.username,
family.password = req.body.password,
family.familyLeader = req.body.familyLeader,
family.husband = req.body.husband,
family.wife = req.body.wife,
family.kids = req.body.kids;
console.log( 'family username', req.body.username ); 2.//undefined? not getting
family.save(function( err, newFamily ) {
if( err ) {
if ( err.code == 11000) {
return res.json({ success: false, message: 'A user with that username already exists. '});
}
else {
return res.send( err );
}
}
res.json({ message: 'Family created!', newFamily: newFamily });
});
})
There is 2 console I have in above call, in the first console I am getting the properties like this: ( I guess here is the issue, properties being as lable!? )
called { '{"username":"arif","password":"sadfdsa","familyLeader":"sadffsa","husband":"sadfsad","wife":"sadfsad","kids":2}': '' }
and the next console give the value like this:
family username undefined
I have removed header from $http request, and it works fine.
my code with issue is : with header
vm.createNewFamily = function() {
$http({
method : 'POST',
url : '/api/family',
data : vm.form,
headers : {'Content-Type': 'application/x-www-form-urlencoded'}
}).success( function ( data ) {
console.log('retured!', data );
})
}
and the solution is : ( header removed )
vm.createNewFamily = function() {
$http({
method : 'POST',
url : '/api/family',
data : vm.form
}).success( function ( data ) {
console.log('retured!', data );
})
}
Experts - Please confirm the solution!

How to insert a document with a subdocument array element in MongoDB with Monk

when i want to insert a document in my mongodb with monk wich has an array element of subdocuments, the funcion insert it wrong in the db.
I'm calling the insert function this way:
var OrderItem = [];
OrderItem[0] = {
'model': asd1,
'size' : M,
'color' : Black
};
OrderItem[1] = {
'model': bsa2,
'size' : S,
'color' : Black
};
var newOrdenCompra = {
'fechaCompra' : d,
'items' : OrderItem
};
$.ajax({
type: 'POST',
data: newOrdenCompra,
url: '/order/addordercompra',
dataType: 'JSON'
}).done(function( response )
{
if (response.msg !== '') {
alert('Error: ' + response.msg);
}
});
and then:
/*
* POST to add orden de compra.
*/
router.post('/addordercompra', function(req, res) {
var db = req.db;
var collection = db.get('ordercompra');
collection.insert(req.body, function(err, result){
res.send(
(err === null) ? { msg: '' } : { msg: err }
);
});
});
But what i get into the BD is something like this (the example that i wrote above have less atributes in the item subdocuments):
> db.ordercompra.find().pretty()
{
"_id" : ObjectId("5601b2181430470c1266d415"),
"fechaCompra" : "2015-09-22T16:54:59Z",
"items[0][model]" : "CLUB DE LA PELEA",
"items[0][size]" : "XXXS",
"items[0][color]" : "CHOCOLATE",
"items[0][sena]" : "1200",
"items[0][precio]" : "2600",
"items[0][ordOT]" : "2",
"items[0][id]" : "55f9e402ebfcd9b414339f8f",
"items[1][model]" : "302",
"items[1][size]" : "M",
"items[1][color]" : "NEGRO",
"items[1][sena]" : "0",
"items[1][precio]" : "2100",
"items[1][ordOT]" : "",
"items[1][id]" : "55e76c0d497c742019bbb5f3"
}
>
What can i do to get the structure of an element with an array of subdocuments? am i doing it wrong or is the insert what's failing?
Thanks for the help! and sorry for my bad english.
Nicolas.
I've solved the problem sending the data transformed with JSON.stringify and changed the ajax parameters to dataType : 'text' and adding contentType: 'application/json'. Doing that the insert works perfect.
Thanks for the help!
Example Imgs:
And the BD looks like this:

Ext.data.HttpProxy callback on failure

I've the following ExtJS. The listener "write" is called when the response is a success (the response is JSON like: {"success":true,"message":"......"}). But how do I attach a callback when the response is not a success? ({"success":false,"message":"......"})
tableStructure.proxy = new Ext.data.HttpProxy({
api: {
read: '/controller/tables/' + screenName + '/getstructure/' + table,
create: '/controller/tables/' + screenName + '/createcolumn/' + table,
update: '/controller/tables/' + screenName + '/updatecolumn/' + table,
destroy: '/controller/tables/' + screenName + '/destroycolumn/' + table
},
listeners: {
write: tableStructure.onWrite
}
});
You want to catch the HttpProxy's exception event.
listeners: {
write: tableStructure.onWrite
exception: function(proxy, type, action, options, response, arg) {
if(type === 'remote') { // success is false
// do your error handling here
console.log( response ); // the response object sent from the server
}
}
}
You can find the full documentation in the Ext docs for Ext.data.HttpProxy down in the events section.
You should be able to make use of the write event itself. The write event's signature is:
write(dataproxy,action,data,response,record,options).
You can access the success variable from the action object and check if the value is true or false. You should be able to access the success variable as:
action.result.success
You can do:
if(action.result.success != true ) {
// If success is not true
} else {
// If success is true
}
You can also set an exception handler on the Ext.data.Store wrapping the HttpProxy, provided that you send a response code other than 200.
var store = new CQ.Ext.data.Store({
proxy : new CQ.Ext.data.HttpProxy({
method : "GET",
url : '/some_url'
}),
reader : new CQ.Ext.data.JsonReader(),
baseParams : {
param : 'some value'
}
});
store.on("beforeload", function() {
CQ.Ext.getBody().mask("Please wait...", false);
});
store.on("exception", function() {
CQ.Ext.getBody().unmask();
CQ.Ext.Msg.show({
title: 'Error',
msg: '<span style="color:red">Bad request.</span><br/>',
icon: CQ.Ext.Msg.ERROR,
buttons: CQ.Ext.Msg.OK
});
});

Resources