Associate File in Parse.Cloud - parse-platform

I am uploading an image through REST API and getting an answer as below
{
"url": "http://files.parsetfss.com/346a0978-68c7-4d08-a446-62f7422469e7/tfss-8b131ff0-5fd0-4dce-92e8-b7b94da5db9e-pic.jpg",
"name": "tfss-8b131ff0-5fd0-4dce-92e8-b7b94da5db9e-pic.jpg"
}
I want to associate this image to a Promotion object. I also have a Location object which has an array of Promotions. Here is my code:
function promiseToAddPromotionToLocation (locationID, promotion) {
var query = new Parse.Query("Location");
return query.get(locationID).then(function (location) {
var promotionObject = promotionObjectFromJSON(promotion);
location.add("promotions", promotionObject);
return location.save();
}, function (error) {
return Parse.Promise.error(error);
});
}
function promotionObjectFromJSON (promotion) {
var Promotion = Parse.Object.extend("Promotion");
var promotionObject = new Promotion();
if ("message" in promotion) {
promotionObject.set("message", promotion.message);
}
//This causes an error: Uncaught Tried to save an object containing an unsaved file.
if ("photo") {
promotionObject.set("photo", promotion.photo);
}
return promotionObject;
}
When I comment out the part of setting photo, it saves the promotion properly, but when I try to set the file, it gives an error saying Uncaught Tried to save an object containing an unsaved file. How can I solve this problem?
By the way promiseToAddPromotionToLocation is called with the parameters below:
{
"locationID": "fvOiAsoogc",
"promotion":{
"message":"Some text",
"photo":{"name": "tfss-8b131ff0-5fd0-4dce-92e8-b7b94da5db9e-pic.jpg", "__type": "File"}
}
}

The reason was that I was passing the file info without url. Associating file docs show that it only needs name and type. However, this is wrong. It also needs the url. This question in Parse forum reveals it.

Related

How to modify just a property from a dexie store without deleting the rest?

I'm having the dexie stores showed in the print screen below:
Dexie stores print screen
My goal is to update a dexie field row from a store without losing the rest of the data.
For example: when I edit and save the field "com_name" from the second row (key={2}) I want to update "com_name" only and not lose the rest of the properties, see first and the third row.
I already tried with collection.modify and table.update but both deleted the rest of the properties when used the code below:
dexieDB.table('company').where('dexieKey').equals('{1}')
//USING table.update
//.update(dexieRecord.dexiekey, {
// company: {
// com_name: "TOP SERVE 2"
// }
//})
.modify(
{
company:
{
com_name: TOP SERVE 2
}
}
)
.then(function (updated) {
if (updated)
console.log("Success.");
else
console.log("Nothing was updated.");
})
.catch(function (err) { console.log(err); });
Any idea how can I accomplish that?
Thanks
Alex
You where right to use Table.update or Collection.modify. They should never delete other properties than the ones specified. Can you paste a jsitor.com or jsfiddle repro of that and someone may help you pinpoint why the code doesn't work as expected.
Now that you are saying I realised that company and contact stores are created dynamically and editedRecords store has the indexes explicitly declared therefore when update company or contact store, since dexie doesn't see the indexes will overwrite. I haven't tested it yet but I suspect this is the behaviour.
See the print screen below:
Dexie stores overview
Basically I have json raw data from db and in the browser I create the stores and stores data based on it, see code below:
function createDexieTables(jsonData) { //jsonData - array, is the json from db
const stores = {};
const editedRecordsTable = 'editedRecords';
jsonData.forEach((jsonPackage) => {
for (table in jsonPackage) {
if (_.find(dexieDB.tables, { 'name': table }) == undefined) {
stores[table] = 'dexieKey';
}
}
});
stores[editedRecordsTable] = 'dexieKey, table';
addDataToDexie(stores, jsonData);
}
function addDataToDexie(stores, jsonData) {
dbv1 = dexieDB.version(1);
if (jsonData.length > 0) {
dbv1.stores(stores);
jsonData.forEach((jsonPackage) => {
for (table in jsonPackage) {
jsonPackage[table].forEach((tableRow) => {
dexieDB.table(table).add(tableRow)
.then(function () {
console.log(tableRow, ' added to dexie db.');
})
.catch(function () {
console.log(tableRow, ' already exists.');
});
});
}
});
}
}
This is the json, which I convert to object and save to dexie in the value column and the key si "dexieKey":
[
{
"company": [
{
"dexieKey": "{1}",
"company": {
"com_pk": 1,
"com_name": "CloudFire",
"com_city": "Round Rock",
"serverLastEdit": [
{
"com_pk": "2021-06-02T11:30:24.774Z"
},
{
"com_name": "2021-06-02T11:30:24.774Z"
},
{
"com_city": "2021-06-02T11:30:24.774Z"
}
],
"userLastEdit": []
}
}
]
}
]
Any idea why indexes were not populated when generating them dynamically?
Given the JSON data, i understand what's going wrong.
Instead of passing the following to update():
{
company:
{
com_name: "TOP SERVE 2"
}
}
You probably meant to pass this:
{
"company.com_name": "TOP SERVE 2"
}
Another hint is to do the add within an rw transaction, or even better if you can use bulkAdd() instead to optimize the performance.

What happens if you do a get item in DynamoDb using a projection expression, if the attribute in the expression may not exist

Inside a lambda, I'm calling getItem on a a table with a projection expression for a single field. This is working fine.
const usersTableParams = {
TableName: 'users',
Key: {
'user-name': { S: userID }
},
ProjectionExpression: 'notificationEndpointARN'
};
ddb.getItem(usersTableParams, function (err, data) {
if (err) {
console.log('error getting user info', err);
}
else {
// success
// code...
}
});
Now I want to add another attribute to the projection expression, but that attribute might not exist yet on the item. (If it doesn't exist I will add it at the end of the function).
Does the function fail, does it return null for that attribute, does it not return that attribute at all?
I can't find the answer in the documentation or in any google searches.
If Projection-Expression contains an attribute that doesn't exist in the table, it doesn't throw any error or return null.
It will simply not appear in the result and return the remaining found attributes .
cli> aws dynamodb get-item --table-name my-DynamoDBTable-I3BL7EX05JQR --key file://test.json --projection-expression "data_type,ts,username"
{
"Item": {
"ts": {
"N": "1600755209826"
},
"data_type": {
"S": "Int32"
}
}
}
You can refer this for details: https://docs.aws.amazon.com/cli/latest/reference/dynamodb/get-item.html

Graphql, return result only if record not null

Totally new in Gatsby (my app is build in here). Also new in Graphql but I go this project from a colleague and now I need to find a way to sort it out.
I have a query in graphql that looks as follow:
query MediasQuery {
allStrapiMedias(sort: { fields: [date], order: DESC }) {
edges {
node {
id
name
description
date(formatString: "Do MMMM, YYYY")
link
poster {
childImageSharp {
fluid {
src
}
}
}
file {
url
}
}
}
}
}
The issue I am facing is that the file record can exist or not, to be more accurate, if link record is empty, then I should find a file (this is how it's been build in Strapi).
If I have at least one record with file then the query run normally, but as soon as I deleted this record from database all the app crash.
How can I make that query to only return file if url is empty or null?
You are querying an object that will have one property (file) filled or not with an url. You just need to add that logic to your JavaScript and React code. When you will print the file, add the new logic, something like:
if (data.allStrapiMedias.edges.node.file) return <ComponentA/>
else return <ComponentB/>
I think that what you are looking for is something that the previous snippet. However, answering your question, you achieve it by adding filters to your query:
query MediasQuery {
allStrapiMedias(
sort: { fields: [date], order: DESC }
filter: { file: {url: {ne: null }}}
) {
edges {
node {
id
name
description
date(formatString: "Do MMMM, YYYY")
link
poster {
childImageSharp {
fluid {
src
}
}
}
file {
url
}
}
}
}
}
More details in GraphQL Query Options Reference.

Extjs validate in separate files

I'm trying to validate fields in my form, but I keep getting an error message.
Here is my code:
Ext.define('ExtDoc.views.extfields.FieldsValidator',{
valEng: function(val) {
var engTest = /^[a-zA-Z0-9\s]+$/;
Ext.apply(Ext.form.field.VTypes, {
eng: function(val, field) {
return engTest.test(val);
},
engText: 'Write it in English Please',
// vtype Mask property: The keystroke filter mask
engMask: /[a-zA-Z0-9_\u0600-\u06FF\s]/i
});
}
});
And I define my field as follow:
{
"name": "tik_moed_chasifa",
"type": "ExtDoc.views.extfields.ExtDocTextField",
"label": "moed_hasifa",
"vtype": "eng",
"msgTarget": "under"
}
The first snippet is in a separate js file, and I have it in my fields js file as required.
When I start typing text in the text field, I keep seeing the following error msg in the explorer debugger:
"SCRIPT438: Object doesn't support property or method 'eng' "
What could it be? Have I declared something wrong?
You have defined your own class with a function valEng(val), but you don't instantiate it, neither do you call the function anywhere.
Furthermore, your function valEng(val) does not require a parameter, because you are not using that parameter anywhere.
It would be far easier and more readable, would you remove the Ext.define part and create the validators right where you need them. For instance if you need them inside an initComponent function:
initComponent:function() {
var me = this;
Ext.apply(Ext.form.field.VTypes, {
mobileNumber:function(val, field) {
var numeric = /^[0-9]+$/
if(!Ext.String.startsWith(val,'+')) return false;
if(!numeric.test(val.substring(1))) return false;
return true;
},
mobileNumberText:'This is not a valid mobile number'
});
Ext.apply(me,{
....
items: [{
xtype:'fieldcontainer',
items:[{
xtype: 'combobox',
vtype: 'mobileNumber',
Or, you could add to your Application.js, in the init method, if you need it quite often at different levels of your application:
Ext.define('MyApp.Application', {
extend: 'Ext.app.Application',
views: [
],
controllers: [
],
stores: [
],
init:function() {
Ext.apply(Ext.form.field.VTypes, {
mobileNumber:function(val, field) {
var numeric = /^[0-9]+$/
if(!Ext.String.startsWith(val,'+')) return false;
if(!numeric.test(val.substring(1))) return false;
return true;
},
mobileNumberText:'This is not a valid mobile number'
});
}

Parse Cloud Code - Missing attributes from response object

Firstly, sorry if this is already answered, but I couldn't find it.
I'm having some trouble retrieving all attributes from a Parse response.
I found this select() method on the documentation, which would do exactly what I need, pointing out which columns should be returned, but it seem to
take no effect.
The bit of code
var answersQuery = new Parse.Query("answer");
answersQuery.select(["objectId", "description", "category_id", "sale_id", "image_url"]);
answersQuery.equalTo("previous_question_id", {
__type: "Pointer",
className: "question",
objectId: questionId
});
answersQuery.find().then(function(answersData) {
if (typeof(answersData) != "undefined") {
var answers = [];
for (var i in answersData) {
answers.push({
id : answersData[i].id,
sale_id : answersData[i].get("sale_id"),
image_url : answersData[i].get("image_url"),
category_id: answersData[i].get("category_id"),
description: answersData[i].get("description")
});
}
response.success({
answers : answers
});
} else {
response.error("answers not found");
}
});
But the return I get always contains just the "id" and the "description" attributes
{"result":{"answers":[{"description":"COMPRAS","id":"x3pS8sadDS"},{"description":"CINEMA","id":"MVHwJqifzE"}]}}
If I change the "id" to something like "asdf" it will reflect in the response, so I'm sure I'm dealing iwth the same object I can see in the response.
Any ideas would be much appreciated.
Does the answers table has too many fields? Have you tried not specifying fields (I mean, to using the select statement)?

Resources