My object javascript is not fully sent to the back - javascript

I'm trying to send an object from front to back.
this is my function :
export const addComponent = (newComponent, inputFields) => (dispatch) => {
const url = process.env.REACT_APP_ADD_COMPONENT;
var componentBody = {
type: newComponent.type,
name: newComponent.name,
};
var componentTest = inputFields.map((inputField) => {
return Object.defineProperty(componentBody, inputField.property, {
value: inputField.content,
});
});
console.log(componentTest);
axios
.put(url, componentTest)
.then(dispatch({ type: ADD_COMPONENT, payload: componentTest }))
.catch((err) => {
console.log("Add failed", err);
});
};
When I log componentTest, it get the strucutre that I want, which mean :
{
description: "je décris",
environnement: "j'environne",
name: "test",
type: "Données"
}
But on the backside, in my route when I log req.body, there is only type and name which are present. Like if the defineProperty function doesn't records my object...
I presume that i need to enumerate all the properties of my object, but my knowledges stop here

I founded it,
If someone else need it.
With defineProperty you need to configure your new object by adding :
var componentTest = inputFields.map((inputField) => {
return Object.defineProperty(componentBody, inputField.property, {
value: inputField.content,
writable: true,
enumerable: true,
configurable: true,
});
});
Now i can see my object fully.

Related

Why am I unable to send a variable as URL in a Planner Task reference?

I am trying to set references for a task via the Planner Graph API, but am unable to set the URL through a variable.
I have written a separate method for encoding the url, and it returns the correct value, but still the references aren't set for the Planner task.
const updateAttachedFiles = (
links: string[],
taskId: string,
etag: string
) => {
var encodedLink: string;
links.forEach(async (link) => {
encodedLink = escapeHtml(link)
await graph.planner.tasks.getById(taskId).details.update(
{
references: {
encodedLink : {
"#odata.type": "microsoft.graph.plannerExternalReference",
"previewPriority": " !",
type: "Other",
},
},
},
etag);
}
)
};
const escapeHtml = (unsafe) => {
let temp = unsafe.replaceAll("%", "%25")
unsafe = temp
.replaceAll(".", "%2E")
.replaceAll(":", "%3A")
.replaceAll("#", "%40")
.replaceAll("#", "%23");
return unsafe
}
But if I change encodedLink to the hardcoded URL (copied from the value set in the variable encodedLink), it works.
{
references: {
"https%3A//shmafe%2Esharepoint%2Ecom/sites/PlannerTest1/Delade dokument/nedladdning%2Ejpg" : {
"#odata.type": "microsoft.graph.plannerExternalReference",
"previewPriority": " !",
type: "Other",
},
},
}
I need to be able to set the link dynamically, so how can I do it without being able to use a variable? Am I doing something else wrong?
Microsft documenttion for Update plannertaskdetails
https://learn.microsoft.com/en-us/graph/api/plannertaskdetails-update?view=graph-rest-1.0&tabs=javascript
Microsft documenttion for plannerExternalReferences resource type
https://learn.microsoft.com/en-us/graph/api/resources/plannerexternalreferences?view=graph-rest-1.0
To use a variable as an object key, you need to use the bracket syntax
For example:
const myVariable = 'hello';
const demoObject = {
[myVariable]: 'world'
};
console.log(demoObject[myVariable]);
// same as
console.log(demoObject.hello);
This should fix it:
const updateAttachedFiles = (
links: string[],
taskId: string,
etag: string
) => {
var encodedLink: string;
links.forEach(async (link) => {
encodedLink = encodeURI(link)
await graph.planner.tasks.getById(taskId).details.update(
{
references: {
[encodedLink] : {
"#odata.type": "microsoft.graph.plannerExternalReference",
"previewPriority": " !",
type: "Other",
},
},
},
etag);
}
)
};

Change Nested State Value With A Single Function? (javascript/React)

I have some react user privilege state data I need to manage. I would like the ability to change the object privileges based on their property through a dynamic function. I'm not sure how to target the specific nested privilege property to change the value. Is this possible?
Question: How can I change the value of a nested privilege property to the functions type and value parameter?
Heres an Example:
const [userPrivilages, setUserPrivilages] = useState([{
_id: "123"
privilages: {
edit: true, //before!
share: true,
del: false
}
},
{
...more users
}
])
//my attempt
const changePrivilage = (type, value) => {
const newPrivilages = userPrivilages.map(user => {
return {
...user,
privilages: {
...privilages,
//change the privilage of "type" from the functions parameter to the value parameter
}
}) setUserPrivilages(newPrivilages)
}
changePrivilage("edit", false)
Desired output:
const [userPrivilages, setUserPrivilages] = useState([{
_id: "123"
privilages: {
edit: false, //After!
share: true,
del: false
}
},
{
...more users
}
])
Thanks!
You can use [] to refer to variable as a key like below:
const changePrivilage = (type, value) => {
const newPrivilages = userPrivilages.map(user => {
return {
...user,
privilages: {
...user.privilages,
[type]: value // here it is !!!
}
}) setUserPrivilages(newPrivilages)
}
Try this :
(see comments for understanding code)
const changePrivilage = (type,value) => {
const newUserPrivilages = userPrivilages.map(user => {
let newPrivilages = user.privilages; // get old privilages of user
newPrivilages[type] = value; // update type with new value
return {
...user,
privilages: newPrivilages, // set privilages as newPrivilages
};
});
setUserPrivilages(newUserPrivilages);
};
Note : this will change properties for all users. If you want to update only for specific user, pass _id as well to changePrivilage and execute newPrivilages[type] = value; // update type with new value inside if condition comparing user _id.

Mongoose Schema method: Error - model method is not a function

I have two Mongoose model schemas as follows. The LabReport model contains an array of the referenced SoilLab model. There is a static method in the SoilLab model that I was using to select which fields to display when LabReport is retrieved.
//LabReport.js
var mongoose = require("mongoose");
var SoilLab = mongoose.model("SoilLab");
var LabReportSchema = new mongoose.Schema(
{
labFarm: { type: mongoose.Schema.Types.ObjectId, ref: "Farm" },
testName: { type: String },
soilLabs: [{ type: mongoose.Schema.Types.ObjectId, ref: "SoilLab" }],
},
{ timestamps: true, usePushEach: true }
);
LabReportSchema.methods.toLabToJSON = function () {
return {
labReport_id: this._id,
testName: this.testName,
soilLabs: this.soilLabs.SoilToLabJSON(),
};
};
mongoose.model("LabReport", LabReportSchema);
//SoilLab.js
var mongoose = require("mongoose");
var SoilLabSchema = new mongoose.Schema(
{
description: { type: String },
sampleDate: { type: Date },
source: { type: String },
},
{ timestamps: true, usePushEach: true }
);
SoilLabSchema.methods.SoilToLabJSON = function () {
return {
description: this.description,
sampleDate: this.sampleDate,
source: this.source,
};
};
mongoose.model("SoilLab", SoilLabSchema);
When I try to retrieve the LabReport, I get "this.soilLabs.SoilToLabJSON is not a function". This is how I'm trying to retrieve LabReport.
//labReports.js
...
return Promise.all([
LabReport.find()
.populate("soilLabs")
.exec(),
LabReport.count(query).exec(),
req.payload ? User.findById(req.payload.id) : null,
]).then(function (results) {
var labReports = results[0];
var labReportsCount = results[1];
var user = results[2];
return res.json({
labReports: labReports.map(function (labReport) {
return labReport.toLabToJSON(user); //This cant find SoilToLabJSON
}),
If I remove the .SoilToLabJSON in LabReport.js and just call this.soilLabs, it works but outputs all of the soilLabs data which will become an issue when I have the model completed with more data. I have dug into statics vs methods a little and tried changing it to statics but it didn't work.
I get the soilLabs to populate but not sure why the .SoilToLabJSON method is inaccessible at this point. Do I need to find() or populate the soilLab differently? Is the method incorrect?
labReport.toLabToJSON is passing an array and that was causing the error for me. I simply edited the LabReport.js to the following to take the array and map it to SoilToLabJSON properly.
myTestSoilLabOutput = function (soilLabs) {
var test = soilLabs.map(function (soilLab) {
return soilLab.SoilToLabJSON();
});
return test;
Changed the LabReportSchema.methods.toLabToJSON to:
LabReportSchema.methods.toLabToJSON = function () {
return {
labReport_id: this._id,
testName: this.testName,
soilLabs: myTestSoilLabOutput(this.soilLabs),
};
};

Add data to returned model sequelize

I have a sequelize model object that is working like expected.
const part = sequalize.define("part", {
id: {type:Sequalize.INTEGER, primaryKey: true, autoIncrement: true},
part_number: {type : Sequalize.STRING(12), unique: true, allowNull: false},
description: {type : Sequalize.STRING(255), allowNull: false}, true}
})
But I want to run an additional function when this model is called for example in a query.
I have this function now:
part.prototype.getTotalStock = function () {
let _this = this;
return new Promise(function(resolve, reject) {
part.findOne({
where: {id: _this.id},
include: [{
model: sequalize.models.location,
}]
}).then(result => {
if (result) {
var totalStock = 0;
let stockOnLocation = result.dataValues.locations
stockOnLocation.forEach(function (entry) {
totalStock += entry.stock.amount
});
_this.setDataValue('totalStock', totalStock);
return resolve(_this)
} else {
return resolve(0)
}
}).catch(err => {
return reject(err)
});
})
}
What i'm doing is that I do a query so I have 1 part object. After that I can call:
queryResult.getTotalStock().then(result => {
//data here in result
})
That is working, its retrieving the stock, calculating it, and it is adding the data to self. Now my question, is it possible to append the result of getTotalStock automatically when the model is being used? So that I don't have to call getTotalStock on the returned object?

How to push Object element to an array in Vuejs/Javascript

I'm trying to build a small application in VueJs,
Following is my data set:
data(){
return {
pusher: '',
channel:'',
notify: [],
notifications: '',
notificationsNumber: '',
}
},
where I'm having an axios call in created property of components as:
axios.get('api/notifications', {headers: getHeader()}).then(response => {
if(response.status === 200)
{
this.notify = response.data.notifications
this.notificationsNumber = this.notify.length
}
}).catch(errors => {
console.log(errors);
})
I'm having pusherJs implemented, so I'm having following code:
this.pusher = new Pusher('xxxxxxxx', {
cluster: 'ap2',
encrypted: true
});
var that = this
this.channel = this.pusher.subscribe('stellar_task');
this.channel.bind('company_info', function(data) {
console.log(data.notification);
that.notifications = data.notification
});
Once the value is being obtained from pusher I want to push this to my array notify as watch property, something like this:
watch: {
notifications(newValue) {
this.notify.push(newValue)
this.notificationsNumber = this.notificationsNumber + 1
}
}
So the problem is the data format which I'm receiving through pusher is in object form and push function is not getting implemented in this:
Screenshot:
Help me out with this.
I'm making an assumption that response.data.notifications is an Array Like Object.
So all you have to do is:
this.notify = [...response.data.notifications];

Categories

Resources