How can I make struct in go for object having array of object inside it? - vue.js

I am using Vuejs on the frontend and Go language on the backend. My data variable has data in the following format.
var data = {
software_type: this.$props.selected,
selected_solutions: this.fromChildChecked,
};
By doing console.log(data)in frontend, I get following output.
On the backend side, I have struct on this format :
type Technology struct {
ID primitive.ObjectID `json:"_id,omitempty" bson:"_id,omitempty"`
SoftwareType string `json:"software_type" bson:"software_type"`
SelectedSolutions struct {
selectedSolutions []string
} `json:"selected_solutions" bson:"selected_solutions"`
}
I am quite sure about the problem that I am having and it might be due to the difference with the format of data that I am sending and the struct that I have made.
I am using MongoDB as a database.
By submitting the form, data comes to DB in the following format, which means, I am getting an empty object for selected_solutions.
{
"_id":{"$oid":"5f5a1fa8885112e153b5a890"},
"software_type":"Cross-channel Campain Mangment Software",
"selected_solutions":{}
}
This is the format that I expect to be on DB or something similar to below.
{
"_id":{"$oid":"5f5a1fa8885112e153b5a890"},
"software_type":"Cross-channel Campain Mangment Software",
"selected_solutions":{
Adobe Campaign: ["Business to Customer (B2C)", "Business to Business (B2B)"],
Marin Software: ["E-Government", "M-Commerce"],
}
}
How can I change struct to make it compatible with the data that I am trying to send? Thank you in advance for any help.
EDIT: This is how I am submitting data.
postUserDetails() {
var data = {
software_type: this.$props.selected,
selected_solutions: this.fromChildChecked,
};
console.log(data);
const requestOptions = {
method: "POST",
headers: { "Content-Type": "application/x-www-form-urlencoded" },
body: JSON.stringify(data),
};
fetch("http://localhost:8080/technology", requestOptions)
.then((response) => {
response.json().then((data) => {
if (data.result === "success") {
//this.response_message = "Registration Successfull";
console.log("data posted successfully");
} else if (data.result === "er") {
// this.response_message = "Reagestraion failed please try again";
console.log("failed to post data");
}
});
})
.catch((error) => {
console.error("error is", error);
});
},
mounted() {
this.postUserDetails();
},
This is the function for backend controller.
//TechnologyHandler handles checkbox selection for technology section
func TechnologyHandler(w http.ResponseWriter, r *http.Request) {
w.Header().Set("content-type", "application/json")
w.Header().Add("Access-Control-Allow-Credentials", "true")
var technologyChoices model.Technology
//var selectedSolution model.Selected
//reads request body and and stores it inside body
body, _ := ioutil.ReadAll(r.Body)
//body is a json object, to convert it into go variable json.Unmarshal()is used ,
//which converts json object to User object of go.
err := json.Unmarshal(body, &technologyChoices)
var res model.TechnologyResponseResult
if err != nil {
res.Error = err.Error()
json.NewEncoder(w).Encode(res)
return
}
collection, err := db.TechnologyDBCollection()
if err != nil {
res.Error = err.Error()
json.NewEncoder(w).Encode(res)
return
}
_, err = collection.InsertOne(context.TODO(), technologyChoices)
if err != nil {
res.Error = "Error While Creating Technology choices, Try Again"
res.Result = "er"
json.NewEncoder(w).Encode(res)
return
}
res.Result = "success"
json.NewEncoder(w).Encode(res)
return
}

Based on your database structure, selected_solutions is an object containing string arrays:
type Technology struct {
ID primitive.ObjectID `json:"_id,omitempty" bson:"_id,omitempty"`
SoftwareType string `json:"software_type" bson:"software_type"`
SelectedSolutions map[string][]string `json:"selected_solutions" bson:"selected_solutions"`
}

Related

error: A value of type 'LocationModel' can't be returned from method 'getLocation' because it has a return type of 'List<dynamic>'

Future<List> getLocation(String city,DateTime date) async {
try {
http.Response hasil = await http.get(
Uri.encodeFull(
"https://api.pray.zone/v2/times/day.json?city=${city}&date=${date}"),
headers: {"Accept": "Application/json"});
if (hasil.statusCode == 200) {
print("Location Successfully Gathered");
final data = locationModelFromJson(hasil.body);
return data;
} else {
print("Error Status ${hasil.statusCode.toString()}");
}
} catch (e) {
print("error catch $e");
return null;
}
}
why cant i return the data variable? it says that because the model has a return type List<dynamic>
edit:
my Model is https://textuploader.com/1pmb6
As you can see, the data you are fetching and parsing is LocationModel.fromJson and you are returning it. But the return type of your method is Future<List> so clearly you are not returning the type that you mentioned the method would.
The correct implementation would be this,
Future<LocationModel> getLocation(String city,DateTime date) async {
...
}
if your API is returning a List of LocationModel which is why I assume you mentioned list,
then you will have to do this,
Future<List<LocationModel> getLocation(String city,DateTime date) async {
try {
http.Response hasil = await http.get(
Uri.encodeFull(
"https://api.pray.zone/v2/times/day.json?city=${city}&date=${date}"),
headers: {"Accept": "Application/json"});
if (hasil.statusCode == 200) {
print("Location Successfully Gathered");
List<LocationModel> locs =[];
hasil.forEach((d){
final l = locationModelFromJson(d.body);
locs.add(l);
});
return locs;
} else {
print("Error Status ${hasil.statusCode.toString()}");
}
} catch (e) {
print("error catch $e");
return null;
}
}
Dart is a very strictly typed language, so if you do not mention a type, Dart assumes that it is dynamic by default and hence you get that error.

How to get data using Add-in program from Office document without metadata(i.e. creation time)?

There's a function which retrieves document of PDF format byte by byte:
Office.initialize = function (reason) {
$(document).ready(function () {
// If not using Word 2016
if (!Office.context.requirements.isSetSupported('WordApi', '1.1')) {
$('#hash-button-text').text("Not supported!");
return;
}
//$('#hash-button').click(calculate_hash);
$('#btn').click(getFile);
});
};
function getFile() {
Office.context.document.getFileAsync(Office.FileType.Pdf, { sliceSize: 99 },
function (result) {
if (result.status == "succeeded") {
var file = result.value;
var sliceCount = file.sliceCount;
var slicesReceived = 0, gotAllSlices = true, docdataSlices = [];
getSliceAsync(file, 0, sliceCount, gotAllSlices, docdataSlices, slicesReceived);
}
else {
console.log("Error");
}
}
);
}
function getSliceAsync(file, nextSlice, sliceCount, gotAllSlices, docdataSlices, slicesReceived) {
file.getSliceAsync(nextSlice, function (sliceResult) {
if (sliceResult.status == "succeeded") {
if (!gotAllSlices) { // Failed to get all slices, no need to continue.
return;
}
docdataSlices[sliceResult.value.index] = sliceResult.value.data;
if (++slicesReceived == sliceCount) {
file.closeAsync();
console.log("Done: ", docdataSlices);
}
else {
getSliceAsync(file, ++nextSlice, sliceCount, gotAllSlices, docdataSlices, slicesReceived);
}
}
else {
gotAllSlices = false;
file.closeAsync();
console.log("getSliceAsync Error:", sliceResult.error.message);
}
});
}
So, close to ~1800 byte there are bytes like "CreationDate(D:20190218150353+02'00..." which are unnecessary in our case.
It retrieves the whole PDF file which consists meta, but is it possible to get it without it?
Best regards
The document.getFileAsync method will always return the entire document (including metadata); it's not possible to make it return anything less than the entire document.

Load XMLHttpRequest from facebook Instant game returns empty result, even though I have just saved the data before getting it from server

The response from server returns empty result despite just saving data earlier in that contextID with success. Most time it returns the json data but sometimes in between it returns empty string leading to createNewGameAsync() function instead of going directly to populateFromBackend() function. I am creating backend from https://glitch.com/edit/#!/panoramic-tendency project on glitch.
loadData: function () {
var contextID = FBInstant.context.getID();
console.log('loadData from ' + contextID);
FBInstant.player.getSignedPlayerInfoAsync(contextID)
.then(function (signedPlayerInfo) {
var url = 'https://panoramic-tendency.glitch.me' + '/get-match'
var sig = signedPlayerInfo.getSignature();
var method = 'POST'
var payload = { 'signature': sig };
return req(url, method, payload);
})
.then(function (result) {
if (result.empty) {
return this.createNewGameAsync();
} else {
return Promise.resolve(result.data);
}
}.bind(this)).then(function (backendData){
this.populateFromBackend(backendData);
}.bind(this))
.catch(function (error) {
this.displayError(error);
}.bind(this));
Solved. I was saving the FbInstant.Player.getPhoto() url as well in database. During encoding with getSignedPlayerInfoAsync() the signature generated was not valid format, and server couldn't decode it resulting in null value.

Display backend error message after Create call

In my controller I have the following code - The problem is when it is error, I want to display exact error that is being passed from backend. But in my error handling function I never get any data. What is wrong here?
Controller.js
var token = null;
$.ajax({
url: sServiceURl,
type: "GET",
async: true,
beforeSend: function(xhr) {
sap.ui.core.BusyIndicator.show(0);
xhr.setRequestHeader("X-CSRF-Token", "Fetch");
},
complete: function(xhr) {
token = xhr.getResponseHeader("X-CSRF-Token");
oContext.OdataModel.create("/materialsSet", oContext.Data, null, oContext.submitSuccess.bind(oContext), oContext.submitError.bind(oContext));
}
});
submitSuccess: function(data, response, oContext) {
// works fine
},
submitError: function(oError) {
// I never get anything in oError, so the below code is useless.
try {
if (oError.responseText) {
obj = JSON.parse(oError.responseText);
message = obj.error.message.value;
} else if (oError.response.body) {
var errorModel = new sap.ui.model.xml.XMLModel();
errorModel.setXML(oError.response.body);
//Read message node
if (errorModel.getProperty("/0/message") !== "") {
message = errorModel.getProperty("/0/message");
} else {
message = message1;
}
} else {
message = message1;
}
} catch (error) {
message = message1;
}
sap.m.MessageToast.show(message);
},
Hope this will help you, first of all check backend response. I have use the below code for error handling.
submitError: function(responseBody) {
try {
var body = JSON.parse(responseBody);
var errorDetails = body.error.innererror.errordetails;
if (errorDetails) {
if (errorDetails.length > 0) {
for (i = 0; i < errorDetails.length; i++) {
console.log(errorDetails[i].message);
}
} else
console.log(body.error.message.value);
} else
console.log(body.error.message.value);
} catch (err) {
try {
//the error is in xml format. Technical error by framework
switch (typeof responseBody) {
case "string": // XML or simple text
if (responseBody.indexOf("<?xml") > -1) {
var oXML = jQuery.parseXML(responseBody);
var oXMLMsg = oXML.querySelector("message");
if (oXMLMsg)
console.log(oXMLMsg.textContent);
} else
console.log(responseBody);
break;
case "object": // Exception
console.log(responseBody.toString());
break;
}
} catch (err) {
console.log("common error message");
}
}
}

Modify Kurento group call example to support only audio

I need to modify the Kurento group call example from Link
to send only audio if one participant has no camera. Right now only audio is received when a camera is used. When only a microphone is available I receive a DeviceMediaError.
I managed to filter whether a camera device is connected or not and then send only audio, but this doesn't work. Maybe the participant should've an audio tag instead of a video tag?
EDIT: It's only working on Firefox and not in Chrome. Any ideas?
in file - https://github.com/Kurento/kurento-tutorial-java/blob/master/kurento-group-call/src/main/java/org/kurento/tutorial/groupcall/UserSession.java.
change following line -
sender.getOutgoingWebRtcPeer().connect(incoming, MediaType.AUDIO);
and set offer media constraints to video:false in browser js file.
updated code -
let constraints = {
audio: true,
video: false
};
let localParticipant = new Participant(sessionId);
participants[sessionId] = localParticipant;
localVideo = document.getElementById('local_video');
let video = localVideo;
let options = {
localVideo: video,
mediaConstraints: constraints,
onicecandidate: localParticipant.onIceCandidate.bind(localParticipant),
configuration : { iceServers : [
{"url":"stun:74.125.200.127:19302"},
] }
};
localParticipant.rtcPeer = new kurentoUtils.WebRtcPeer.WebRtcPeerSendonly(options, function(error) {
if (error) {
return console.error(error);
}
localVideoCurrentId = sessionId;
localVideo = document.getElementById('local_video');
localVideo.src = localParticipant.rtcPeer.localVideo.src;
localVideo.muted = true;
this.generateOffer(localParticipant.offerToReceiveVideo.bind(localParticipant));
});
server.js code
function join(socket, room, callback) {
let userSession = userRegister.getById(socket.id);
userSession.setRoomName(room.name);
room.pipeline.create('WebRtcEndpoint', {mediaProfile : 'WEBM_AUDIO_ONLY'}, (error, outgoingMedia) => {
if (error) {
console.error('no participant in room');
if (Object.keys(room.participants).length === 0) {
room.pipeline.release();
}
return callback(error);
}
// else
outgoingMedia.setMaxAudioRecvBandwidth(100);
add media profile parameter on server side while joining room.
function getEndpointForUser(userSession, sender, callback) {
if (userSession.id === sender.id) {
return callback(null, userSession.outgoingMedia);
}
let incoming = userSession.incomingMedia[sender.id];
if (incoming == null) {
console.log(`user : ${userSession.id} create endpoint to receive video from : ${sender.id}`);
getRoom(userSession.roomName, (error, room) => {
if (error) {
return callback(error);
}
room.pipeline.create('WebRtcEndpoint', {mediaProfile : 'WEBM_AUDIO_ONLY'}, (error, incomingMedia) => {
if (error) {
if (Object.keys(room.participants).length === 0) {
room.pipeline.release();
}
return callback(error);
}
console.log(`user: ${userSession.id} successfully create pipeline`);
incomingMedia.setMaxAudioRecvBandwidth(0);
incomingMedia.getMaxAudioRecvBandwidth(0);
add media profile parameter when accepting call.
hope this helps.