CameraPreview capture not returning result.value - capacitor

I am using Capacitor.Capture(CameraPreviewPictureOptions) but it's result.value is not valid, it is returning
value: "data:," [[Prototype]]: Object
I am implementing as
const cameraPreviewPictureOptions: CameraPreviewPictureOptions = { quality: 90 }; const result = await CameraPreview.capture(cameraPreviewPictureOptions);
Here output
result.value is 'data:,'
"#angular/core": "~13.2.2", "#capacitor/core": "^3.5.1", #ionic-native/core": "^5.36.0" , #capacitor-community/camera-preview": "^3.0.0"

Try to use CameraPreview.captureSample instead of CameraPreview.capture

Related

Monday.com create board item JSON layout

I have a Monday.com board (table). I want to add a new item (row) including the column values. Columns are of type:
email
color
timeline
date
hour
text
I want to create the GraphQL API call in JavaScript on the browser.
The issue is that you need to JSON encode the column_values attribute value and escape it since it is within the query value.
Example
The msg function logs the message.
The following was tested as JavaScript running in a browser. The Monday.com API supports CORS.
let colValues = {
to: {text: "Larry K",
email: "larry#example.com"},
status: {index:1},
timeline: {to: "2022-12-28", from: "2022-12-02"},
date: {date: "2022-12-01"},
hour: {hour:12, minute:0},
text6: "12345-67890-ABCD"
};
let req = {query:
`mutation {create_item (
board_id: ${mon_boardId},
group_id: ${mon_groupId},
item_name: "New from JS",
column_values: ${JSON.stringify(JSON.stringify(colValues))}
) {
id
}}`};
const r = await callMondayApi(req);
....
/*
* Makes a Monday.com API call with JSON request/results
*/
async function callMondayApi(req) {
let body = JSON.stringify(req, null, 4);
try {
let headers = new Headers({
Accept: `application/json`,
Authorization: `${mon_token}`,
"Content-Type": "application/json",
});
let results = await fetch("https://api.monday.com/v2", {
method: "POST",
mode: "cors",
headers: headers,
body: body
});
if (results && results.ok) {
return await results.json();
} else {
const res = await results.text();
errMsg(
`Problem while making Monday API call. ` +
`Error: ${results ? results.statusText : "no response"}.` +
res
);
return false;
}
} catch (e) {
errMsg(`Problem while making Monday API call. ` + `Error: ${e.toString()}.`);
return false;
}
}
Some details
Per the GraphQL docs, the POST JSON structure is
{
"query": "...",
"operationName": "...",
"variables": { "myVariable": "someValue", ... }
}
In other words, the query/mutation is sent as a string. But within that string, the Monday.com column_values value is a JSON string!

Typesense OR query on multiple fields

In Flutter, I'm trying to query my Typesense messages collection. I'd like to return all the messages that have message_from="abc" OR message_to="abc". Instead, in the example below, it only returns messages with message_from="abc". Could you please help? Thanks
The query below only returns
params = {
'searches': [
{
"query_by": "message_from",
'filter_by': 'message_from:abc',
},
{
"query_by": "message_to",
'filter_by': 'message_to:abc',
}
],
};
final commonSearchParams = {
'q': '*',
'collection': 'messages',
'page': page.toString(),
'per_page': perPage.toString(),
'group_by': 'thread',
'sort_by': 'date:desc',
};
return typesenseClient.multiSearch
.perform(params!, queryParams: commonSearchParams)
.then((docs) {
return docs["results"][0]["grouped_hits"];
});
You can accomplish this with comma-separated fields instead of using multi-search. I.e. {query_by: "message_from,message_to", ...}.

"cannot read property 'replace' of undefined" for mongodb client

I'm attempting to connect to a MongoDB Atlas cluster and am having an issue in my react app.
on await client.connect(), I get TypeError: Cannot read property 'replace' of undefined.
I have verified that the connection string works via MongoDB Compass.
My mongo.ts file
import { MongoClient } from 'mongodb';
const username = encodeURIComponent(process.env.REACT_APP_MONGO_READ_USERID as string);
const userpass = encodeURIComponent(process.env.REACT_APP_MONGO_READ_USERPASS as string);
const uri = `mongodb+srv://${username}:${userpass}#cluster0.xup6s.mongodb.net/database?w=majority`;
const client = new MongoClient(uri, { useNewUrlParser: true, useUnifiedTopology: true });
export const getItemsfromMongo = async <T>(collection: string): Promise<T[]> => {
try {
console.log(client);
try {
await client.connect(); // Fails here
console.log(client);
} catch (error) {
console.error('Failed to connect to MongoDB server');
throw error;
}
const mongoCollection = client.db("database").collection<T>(collection);
const cursor = mongoCollection.find()
const items = await cursor.toArray();
console.log(items);
await client.close();
return items;
} catch (err) {
console.error(err);
return [];
}
}
package.json dependencies
"dependencies": {
"#material-ui/core": "^4.10.1",
"#material-ui/icons": "^4.9.1",
"#types/mongodb": "^3.5.26",
"bootstrap": "^4.5.0",
"firebase": "^7.19.0",
"mongodb": "^3.6.0",
"mongodb-client-encryption": "^1.1.0",
"node-sass": "^4.14.1",
"react": "^16.13.1",
"react-bootstrap": "^1.0.1",
"react-dom": "^16.13.1",
"react-router-dom": "^5.2.0",
"react-scripts": "3.4.3",
"realm": "^10.0.0-beta.6",
"require_optional": "^1.0.1",
"typescript": "^4.0.2"
},
I ran into the same error today doing roughly the same thing. After doing some digging I found that this error tends to occur when you try to use a front-end application to execute a backend function which in this case appears to be a NodeJS driver. Therefore, I’m assuming you’re calling the exported function somewhere in your front-end application. This is problematic for a variety of reasons but besides best practices this will never work. My recommendation would be to use REST API, GraphQL, or MongoDB Stitch Browser SDK. I used the ladder and it worked great for me.

How can i send the Map Object in multipart request in flutter

Here I am trying to send the Object Map in the multipart request but my request is going as a string, not in JSON format please suggest me to do correct request. Thanks in advance.
I have tried the multipart request but my request should be in correct form..
var getApiUrl = 'http://malik-env-test.ap-south-1.elasticbeanstalk.com/webapi/post/create';
Map userData = {
"creator": {
"creatorId": "298",
"createDate": "2018-12-21 20:44:45.8"
},
"info": "$campusInfo",
"title": "$eventName",
"postCampusId": "5642"
};
Uri uri = Uri.parse(getApiUrl);
http.MultipartRequest request = new http.MultipartRequest('POST', uri);
request.fields['creator'] = userData['creator'];
request.fields['info'] = '$campusInfo';
request.fields['title'] = '$eventName';
request.fields['postCampusId'] = '5642';
request.files.add(await http.MultipartFile.fromPath('image_file1', imagePath, contentType: new MediaType('application', 'x-tar')));
// var body = json.encode(request);
print(request);
http.StreamedResponse response = await request.send();
String jsonData = response.toString();
print(jsonData);ddd
Try:
request.fields['userData'] = json.encode(userData);
You need to find out from the API spec or server owner what field name to use for the json. I've assumed userData.
If you want control over the media type, encoding, etc, add it as a file like this:
request.files.add(
http.MultipartFile.fromBytes(
'the_form_field name',
utf8.encode(json.encode(userData)),
contentType: MediaType(
'application',
'json',
{'charset': 'utf-8'},
),
),
);
I think, the easiest way to add object fields is using brackets like this ;
request.fields['creator[creatorId]'] = '$creatorId';
request.fields['creator[createDate]'] = '$createDate';
request.fields['title'] = '$eventName';
request.fields['postCampusId'] = '5642';
So, for the fields inside another you need to put the object name first then add to fields name inside brackets.
this should work just fine.
var userData = json.encode({
"creator": {
"creatorId": "298",
"createDate": "2018-12-21 20:44:45.8"
},
"info": "$campusInfo",
"title": "$eventName",
"postCampusId": "5642"
});
var client = http.Client();
client
.post('https://'+ url ,
headers: {
'content-type': 'application/json',
},
body: userData )

Erro when using File Transfer Plugin - Ionic 3

I am trying to upload images to my server using
"cordova-plugin-file-transfer": "^1.7.1",
"#ionic-native/file-transfer": "^5.0.0",
component.ts
takePicture() {
const options: CameraOptions = {
quality: 50,
destinationType: this.camera.DestinationType.FILE_URI,
encodingType: this.camera.EncodingType.JPEG,
mediaType: this.camera.MediaType.PICTURE,
sourceType: this.camera.PictureSourceType.PHOTOLIBRARY,
targetWidth: 500,
targetHeight: 500,
saveToPhotoAlbum: false
};
this.camera.getPicture(options)
.then((imageData) => this._img.uploadImage(imageData))
.catch(err => console.log(err));
}
imageProvider.ts
import { FileTransfer, FileUploadOptions, FileTransferObject } from "#ionic-native/file-transfer/ngx";
...
uploadImage(img) {
const url = `${this.apiURL}/images/upload`;
// File for Upload
var targetPath = img;
var options: FileUploadOptions = {
fileKey: 'image',
chunkedMode: false,
mimeType: 'multipart/form-data'
};
const fileTransfer: FileTransferObject = this.transfer.create();
fileTransfer.upload(targetPath, url, options)
.then(() => {
console.log('good');
}, (err) => {
console.log('bad');
})
}
I get this error in logcat Android Studio:
"TypeError: Cannot read property 'constructor' of undefined"
I have found that the code works well till it reaches this line
const fileTransfer: FileTransferObject = this.transfer.create();
You are using the wrong native plugin version, For Ionic 3, you should use version 4.
ionic cordova plugin add cordova-plugin-file-transfer
npm install --save #ionic-native/file-transfer#4
And also, don't append ngx at the end of the import.
import { FileTransfer, FileUploadOptions, FileTransferObject } from '#ionic-native/file-transfer';
For your future reference, If you are using Ionic 3, follow Ionic v3 docs instead of latest docs.
V3 docs: https://ionicframework.com/docs/v3/native/file-transfer/
you might be missing this line after the imports:
constructor(private transfer: FileTransfer, private file: File) { }
that's at least what the documentation suggests.