parse dirty object is not working after migration - node.js

I have a question regarding parse cloud code. The following cloud code was working before migration written in cloud code but after migration its not returning desired output.
var streamClass = Parse.Object.extend("Streams");
streamObj = new streamClass({
objectId: "dummy",
streamerId: usersArr[i]
});
streamObj.dirty = function() {return false;};
There are two entities i.e. streams and users. Every user has streams. So there is users pointer(streamerId) in stream table. If user do not have any stream created then i am creating a stream dummy object and setting user(streamerId) as a pointer in stream object. When this code was called as a API, it was returning stream dummy object with user(streamerId) information before parse server migration. After migration the above code gives the following output.
{
"result": [
{
"__type": "Pointer",
"className": "Streams",
"objectId": "dummy"
}
]
}
It can noticed that there is no user(streamerId) information in the output. Can anyone please help me in this regard.
I am not saving this streamObj. I am returning this streamObj to IOS app. I also tested it through postman in google chrome. The following is a complete function which takes array of users object and array of streams objects and return one object contains user and its related streams.
function getUsersAndRecentStreams(usersArr, streamsArr) {
var responseObj = [];
var moment = require('moment');
var now = moment();
var currentDate = new Date();
for( var i=0; i<usersArr.length; i++ ) {
var streamObj = null;
for( j=0; j<streamsArr.length; j++ ) {
var streamerObj = streamsArr[j].get('streamerId');
if( streamerObj.id === usersArr[i].id ) {
if( moment(streamsArr[j].get('showTimeStart')) <= now && moment(streamsArr[j].get('showTimeEnd')) >= now ) {
streamObj = streamsArr[j];
break;
}
if( streamObj == null) {
streamObj = streamsArr[j];
}
else {
if( moment(streamsArr[j].get('showTimeStart')) <= now ) {
streamObj = streamsArr[j];
}
}
}
}
if( streamObj == null ) {
var streamClass = Parse.Object.extend("Streams");
streamObj = new streamClass({
objectId: "dummy",
streamerId: usersArr[i]
});
streamObj.dirty = function() {return false;};
var streamObj = new streamObj();
}
responseObj.push(streamObj);
}
return responseObj;
}
There are two cases.
1) When streamObj is not null. In this case the output is correct.
2) The second case when streamObj is null. In this case the following output is return which is not desired.
{
"result": [
{
"__type": "Pointer",
"className": "Streams",
"objectId": "dummy"
}
]
}
When streamObj is null, The following desired output should return this function.
{
"result": [
{
"__type": "Pointer",
"className": "Streams",
"objectId": "dummy",
"StreamerId": userObject
}
]
}

Related

How to validate the key and value not to be empty in array?

Parameter validation
I want to ensure that the array must not be empty in any cost so that i want to validate the array
imgList= [
{
"fileType": "png",
"fileContent": "base64"
},
{
"fileType": "png",
"fileContent": "base64"
}
]
I want to validate both key and value is present or not (it should not be empty)
eg: filetype is missing
{
"fileContent": "base64"
},
eg2: value is missing
{
"fileType": "",
"fileContent": "base64"
},
Code which i have tired is
body.imgList.forEach((item) => {
var key,
count = 0;
for (let [key, value] of Object.entries(item)) {
if (item.hasOwnProperty(key) && !!value) {
count++;
}
}
var objectLenght = count;
if (objectLenght != 2) {
return cb({"status_code":400,"status":"Pass all the required fields"});
}
});
When I try this worked is died and image are uploaded with out type in s3
I hope this works, you can use isOkay function to verify if the array is valid
const isOkay = (arr)=> {
let okay = true;
for(let entry of arr){
if(!entry.hasOwnProperty('fileType') || !entry['fileType'] || !entry.hasOwnProperty('fileContent') || !entry['fileContent']){
okay = false;
break;
}
}
return okay;
}
Javascript's truthy / falsy system takes care of this for you. If the key does not exist you will get undefined when attempting to access it, which is falsy. An empty string is also a falsy value.
function validate(data) {
if (!data || !data.length) return false;
for (const item of data) {
if (!item || !item.fileType || !item.fileContent) return false;
}
return true;
}
if (validate(body.imgList)) return cb({ status_code: 400, status: 'Pass all the required fields' });;
More info on falsy: https://developer.mozilla.org/en-US/docs/Glossary/Falsy

creating nested json file in node js

Here I want to create a nested json file. I have a variable loggedPerson1 as string which takes username of the person who have logged in and that person selects the courses. I want to create the json file in such a manner that registered courses would come under that name of that user.
var exists = fs.existsSync('RegisteredCourses.json');
if(exists) {
console.log("Loading");
var data = fs.readFileSync('RegisteredCourses.json', 'utf-8');
objRegister = JSON.parse(data);
}
else {
console.log('created new ')
var objRegister = {loggedPerson1:[]};
}
app.get('/RegisteredCourses',(req,res) =>{
res.send(loggedPerson)
})
app.post('/RegisteredCourses',(req,res) =>{
var declaredCourse =
{
key: Date.now().toString(),
CourseName : req.body.CourseName,
CourseCode: req.body.CourseCode,
StartDate:req.body.StartDate,
EndDate:req.body.EndDate,
Total_Fee: req.body.Fees,
Delivery_Mode : req.body.Delivery_Mode,
Description : req.body.Description,
CourseType: req.body.CourseType
}
if(!declaredCourse.CourseName ){
reply ={
msg:"Please enter data correctly"
}
res.send(reply)
}
else{
objRegister.loggedPerson1.push(declaredCourse)
let data = JSON.stringify(objRegister, null, 2);
fs.writeFile('RegisteredCourses.json',data,finished);
console.log('RegisteredCourses updated')
function finished(err){
reply = {
status:"Success",
}
res.send(reply)
console.log(reply)
}
}
})
It's not clear whether you're looking for the structure of the JSON here or something else. The JSON structure could be something like:
{
"students": {
"studentName": "Person 1",
"Courses": {
"one": "one",
"two": "two"
}
}
}
your code to read it out with:
var data = fs.readFileSync('RegisteredCourses.json', 'utf-8');
objRegister = JSON.parse(data);
should work fine, i've used the same in my projects.

Parsing a nested api response in Node

An API request like this: const response = await this.publicGetMarkets (params); is giving me a response that contains a list of markets in the following format:
{
"markets": {
"LINK-USD": {
"market": "LINK-USD",
"status": "ONLINE"
},
...
}
As in the example here, my problem is that LINK-USD is changing for every market.
How do I fix my code so that I can variables such as market, status in my code.
I have written the following code snippet:
const market = this.safeValue (response, 'markets');
const result = [];
for (let i = 0; i < markets.length; i++) {
const markets = this.safeString (markets, {}, {});
const market = this.safeString (markets, 'market');
const status = this.safeString (markets, 'status');
result.push({
'market': market,
'status': status,
});
}
return result;
You can get an array of all the inner objects using Object.values(data.markets).
If you need to filter out unwanted properties that is a fairly simple mapping addition to this also
const data = {
"markets": {
"LINK-USD": {
"market": "LINK-USD",
"status": "ONLINE"
},
"LINK-EURO": {
"market": "LINK-EURO",
"status": "TBD"
}
}
}
const res = Object.values(data.markets)
console.log(res)
const responses = this.safeValue (response, 'markets');
const result = [];
for (let response of responses) {
const market = responses.markets["LINK-USD"].market,
status = responses.markets["LINK-USD"].status;
result.push({market, status});
}
return result;
I hope this is what you asked for.

async.waterfall randomly sorts results

I was writing a nest code, tried using async.waterfall or async.series but I am getting random results every time I refresh. it seems to be because of the queries of the first 2 functions randomly finishing.
first query was sorting to committed_date DESC. but when I add the 2 sub queries. the sort gets distorted.
Step1: Loop landingpages
Step1.1 - fetch details1 repositories
Step1.2 - fetch details2 versions
Step2: build array
db.collection('landingpages').find({is_deleted:{$ne:1}}).sort({committed_date:-1}).limit(10).toArray(function(err, db_results) {
var data_array = [];
var x=1;
if(db_results.length == 0) {
return_data.lps = data_array;
parallel_done();
}else{
async.each(db_results, function (db_results1, cb) {
async.watefall(
[
function(callback) {
//if this is removed or passed as callback(null, ""); the sort is fixed from committed - 1
var data_repo = {};
db.collection('repositories').find({repository_id: repository_id}).toArray(function(err, db_results1) {
if(db_results1.length == 0){
var data_repo = {};
callback(null, data_repo);
}else{
var data_repo = db_results1[0];
callback(null, data_repo);
}
});
},
function(callback) {
//if this is removed or passed as callback(null, ""); the sort is fixed from committed - 1
var data_version = {};
db.collection('versions').find({landingpage_id: landingpage_id}).sort({_id:-1}).limit(1).toArray(function(err, db_results1) {
if(db_results1.length == 0){
var data_version = {};
callback(null, data_version);
}else{
var data_version = db_results1[0];
callback(null, data_version);
}
});
}
],
function (err, data_repo,data_version) {
var document = {
"x": x++,
"landingpage_id": db_results1.landingpage_id,
"repository_id": db_results1.repository_id,
"version_id": data_version.version_id,
"val": db_results1,
"data_repo": data_repo,
"data_version": data_version,
};
data_array.push(document);
if(data_array.length == db_results.length) {
return_data.lps = data_array;
}
}
);
});
}
});

Find document looking inside an object

I have this document:
{
"_id": ObjectId("xxx"),
"props": {
"a": "a1",
"b": "b2"
}
}
My query looks like this:
db.collection.find({"$and": [ {"props.a" : "a1"}, {"props.b": "b2"} ]}
I get the elements of the query from GET values:
/api/search?a=a1&b=b1
So, I need a way to generate dinamically my query starting from the GET object...
I thought about something like this:
// Little helper to get the object key name by index
Object.prototype.key = function key(int) { var j = -1; for(var i in this) { j++; if(j==int) { return i; } else { continue; } } }
// My attempt
var query = [],
i = 0;
_.each(req.query, function(prop) {
var key = req.query.key(i);
query.push({"props." + key: prop});
i = i + 1;
});
But it does not work...
if I do:
_.each(req.query, function(prop) {
var key = {};
key.properties = {};
key.properties[req.query.key(i)] = prop ;
props.push(key);
i = i + 1;
});
I get this:
[{ props: { a: 'a1' } }, { props: { b: 'b1' } } ]
but in this way I could get only this query:
db.collection.find({"$and": [ { props: { a: 'a1' } }, { props: { b: 'b1' } } ]}
which is completely different from the one I've written above (this one search for a props which is exactly like the ones I've provided, instead the original looks for one which contains one of the values)
how can I do?
Ok I've found a solution, searching on google did not returned any solutions...
var query = {"$and": []},
props = [],
i = 0;
_.each(req.query, function(prop) {
var key = {};
key["properties." + req.query.key(i)] = prop ;
props.push(key);
i = i + 1;
});
query.$and = props;
In this way the query generated is exactly like I need it.

Resources