How get get previous node value in mustache - templates

I have a object, which has multiple objects
fields:[
{
safeName: 'status',
accessorName: 'Status',
type: {name: 'String', doc: 'String', code: '\'String\''},
field: {type: 'string', description: 'pet status in the store', enum: ['available', 'pending', 'sold']}
},
{
safeName: 'code',
accessorName: 'Code',
type: {name: 'NSInteger', doc: 'NSInteger', code: '\'NSInteger\'' },
field: {type: 'integer', format: 'int32'}
},
...
]
I need to check with enum value
Output should be
When enum is present in field
instance.status = Order.Status(rawValue: (sourceDictionary["status"] as? String) ?? "")
And when enum is not present in field object
instance.code = Decoders.decodeOptional(clazz: NSInteger.self, source: sourceDictionary["code"])

Did like this
{{#fields}}{{#field}}
{{#description}}
instance.{{safeName}} = Order.Status(rawValue: (sourceDictionary["{{safeName}}"] as? String) ?? "")
{{/description}}
{{^description}}
instance.{{safeName}} = Decoders.decodeOptional(clazz: {{#type}}{{type.name}}{{/type}}.self, source: sourceDictionary["code"])
{{/description}
{{/field}}{{/fields}}

Related

GraphQL save self relation in custom resolver in amplify

I have the following models:
type Field #model {
id: ID!
fieldID: ID #index(name: "byField", sortKeyFields: ["name"])
name: String!
type: String!
required: Boolean
fields: [Field] #hasMany(indexName: "byField", fields: ["id"])
}
type Mutation {
batchCreateField(fields: [BatchCreateField]): [Field]
}
input BatchCreateField {
id: ID
fieldID: ID
name: String!
type: String!
required: Boolean
fields: [BatchCreateField]
}
And wrote a custom resolver:
$util.log.info($util.toJson($context))
#set($isAuthorized = false)
#set( $createdAt = $util.time.nowISO8601() )
#set($fieldsArray = [])
#foreach($item in \${ctx.args.fields})
$util.qr($item.put("id", $util.defaultIfNullOrBlank($item.id, $util.autoId())))
$util.qr($item.put("createdAt", $util.defaultIfNull($item.createdAt, $createdAt)))
$util.qr($item.put("updatedAt", $util.defaultIfNull($item.updatedAt, $createdAt)))
$util.qr($item.put("__typename", "Field"))
$util.qr($fieldsArray.add($util.dynamodb.toMapValues($item)))
#end
## [End] Initialization default values. **
$util.toJson( {
"version": "2018-05-29",
"operation": "BatchPutItem",
"tables": {
"Field-INSERT_APIID-INSERT_PROJECT_ENV": $fieldsArray
}
} )
Saving in batch works fine, the self relation is not working. Is there any way i can save this self relation like below in a batch and the resolver autofilling the sub fields with the fieldID of the previously inserted field?
let fieldInput: CreateFieldInput = {
name: field.name,
type: field.type,
required: field.required,
fields: field.fields
};
batchFieldsInput.push(fieldInput)
API.graphql(graphqlOperation(batchCreateField, {fields: batchFieldsInput}))

how to parse false values in mustache

I am new to mustache. Have an object like
object = [{
name: 'A',
fields: { type: "string" }
},
{
name: 'B',
fields: { type: "boolean", default: false }
}]
I am passing that object to mustache template and I want generated code where default values are also shown.
Code:
{{#object}}
var {{name}}: {{#fields}} {{type}} {{^default}} = {{default}} {{/default}}{{/fields}}
{{/object}}
But I am not able to get the expected output from above code.
Expected Output:
var A: string
var B: boolean = false
If default were the string "false" it would (almost) work. You've currently got the equivalent to:
default = false
if (!default) {
" = " + default
}
… but you need:
default = "false"
if (default) {
" = " + default
}
So this would do it for you:
object = [{
name: 'A',
fields: { type: "string" }
},
{
name: 'B',
fields: { type: "boolean", default: "false" }
}]
… and change the {{^default}} block to {{#default}}:
{{#object}}
var {{name}}: {{#fields}} {{type}} {{#default}} = {{default}} {{/default}}{{/fields}}
{{/object}}
this work for me:
object : [
{
name: 'A',
fields: { type: "string" }
},
{
name: 'B',
fields: { type: "boolean", default: "false"}
}
]
with
{{#object}}
var {{name}}: {{#fields}} {{type}} {{#default}} = {{default}} {{/default}}{{^default}}{{/default}}{{/fields}}
{{/object}}
if the false cannot change to "false" and you want a result like you show above,you may try:
object : [
{
name: 'A',
fields: { type: "string", default: true}
},
{
name: 'B',
fields: { type: "boolean", default: false}
}
]
with
{{#object}}
var {{name}}: {{#fields}} {{type}} {{#default}}{{/default}}{{^default}}= false{{/default}}{{/fields}}
{{/object}}

Django Nested Json of Multiple Foreign Key Models

I've 4 model that has relationship through FK.
class Journal(models.Model):
name = models.CharField(max_length=255)
class Volume(models.Model):
journal = models.ForeignKey(Journal, related_name='volumes')
number = models.IntegerField()
class Issue(models.Model):
volume = models.ForeignKey(Volume, related_name='issues')
number = models.IntegerField()
class Article(models.Model):
issue = models.ForeignKey(Issue, related_name='articles')
title = models.CharField(max_length=255)
I need a JSON format like follow structure.
journal: [
{ name: 'Volume number goes here', type: 'folder', id: 'F1',
data: [
{ name: 'Issue number goes here', type: 'folder', id: 'F1F1',
data: [
{ name: 'Article name goes here>', type: 'item', id: 'F1F1I1' },
{ name: 'Article name goes here>', type: 'item', id: 'F1F1I2' },
{ name: 'Article name goes here>', type: 'item', id: 'F1F1I3' },
]},
{ name: 'Issue number goes here', type: 'folder', id: 'F1F2',
data: [
{ name: 'Article name goes here>', type: 'item', id: 'F1F2I1' },
{ name: 'Article name goes here>', type: 'item', id: 'F1F2I2' },
{ name: 'Article name goes here>', type: 'item', id: 'F1F2I3' },
]},
]
},
{ name: 'Volume number goes here', type: 'folder', id: 'F2',
data: [
{ name: 'Issue number goes here', type: 'folder', id: 'F1F1',
data: [
{ name: 'Article name goes here>', type: 'item', id: 'F2F1I1' },
{ name: 'Article name goes here>', type: 'item', id: 'F2F1I2' },
{ name: 'Article name goes here>', type: 'item', id: 'F2F1I3' },
]},
{ name: 'Issue number goes here', type: 'folder', id: 'F1F2',
data: [
{ name: 'Article name goes here>', type: 'item', id: 'F2F2I1' },
{ name: 'Article name goes here>', type: 'item', id: 'F2F2I2' },
{ name: 'Article name goes here>', type: 'item', id: 'F2F2I3' },
]},
]
}
],
I've tried several stuff but it will cause hundred of sql queries ( because of for loops )
Any ideas ?
You can create that JSON file using exactly 4 queries. You just have to use prefetch_related.
Here is some proof of concept (for queries counter to work, you must have DEBUG=True):
from django.db import connection
journals = Journal.objects.all().prefetch_related('volumes', 'volumes__issues', 'volumes__issues__articles')
for journal in journals:
print "%s" % journal.name
for volume in journal.volumes.all():
print " %d" % volume.number
for issue in volume.issues.all():
print " %d" % issue.number
for article in issue.articles.all():
print " %s" % article.title
print len(connection.queries)
That will print simple tree of your objects and number of queries at the end, which will equal 4 (if there wasn't any queries done before in that connection). From that there is not far to create your JSON output.
In creating that exact JSON, Django REST Framework can be helpful. Assuming that you have all your serializers done and nested, feeding JournalSerializer With above queryset, will create exactly 4 queries to database.
Use select_related and prefetch_related. These methods are used in the Django ORM to do SQL JOINs, so you won't be duplicating queries.

Sencha Touch change itemTpl on specific items in list

I'd like to be able to add class in the Itemtpl where the Item has it's field "Answered" set to "true"
It sound's easy to me, but I don't know where to start..
I know I have to check if Answered is true in the tpl, but I don't know how to write in the template.. o.O
//model
Ext.define('User', {
extend: 'Ext.data.Model',
config: {
idProperty: 'Name',
fields: [
{name: 'Name', type: 'string'},
{name: 'Address', type: 'string'},
{name: 'ID', type: 'int'},
{name: 'WebUrl', type: 'string'},
{name: 'InfoUrl', type: 'string'},
{name: 'Answered', type: 'boolean'},
]
}
});
//store
aStore = Ext.create('Ext.data.Store', {
model: 'User',
sorters: 'Name',
grouper: {
groupFn: function(record) {
return record.get('Name')[0];
}
}
});
//full store
store = Ext.create('Ext.data.Store', {
model: 'User',
sorters: 'Name',
grouper: {
groupFn: function(record) {
return record.get('Name')[0];
}
},
proxy: {
type: 'ajax',
url: '/Services/RestaurantList.ashx',
reader: {
type: 'json',
rootProperty: 'users'
}
},
listeners:{
load: function(){
var all = store.data.all;
aStore.setData(all.slice(0,30));
}
},
autoLoad: true
});
//the list
list = Ext.create('Ext.List', {
flex: 8,
itemTpl: ['<div class="contact">{Name}</div>'],
store: aStore,
listeners: {
itemtap: function(list, index, target, record) {
mainContainer.setActiveItem(1);
detailsPanel.setRecord(record);
},
plugins: [
{
xclass: 'Ext.plugin.PullRefreshFn',
refreshFn: function(){
store.clearData();
aStore.clearData();
store.clearFilter();
aStore.clearFilter();
store.load();
list.refresh();
}
}
],
grouped: true
});
Have you looked at the docs for XTemplate? http://docs.sencha.com/touch/2.2.1/#!/api/Ext.XTemplate. In particular, look at the "Conditional processing with basic comparison operators" section.
If you don't want to use the <tpl if=""> notation, you can also use the ternary operator:
itemTpl: new Ext.XTemplate(
'<div class="{[values.Answered ? \'answered\' : \'\']}">{Name}</div>'
),
...

ExtJS 4.1.0 proxy returns update api instead of create

I was working on a code which was about integrating ExtJS 4 and Django. The link is:
https://github.com/diegocmsantos/extjs4-tdc2011-django
It works fine on ExtJS 4.0.0. But when I upgrade to 4.1.0 it's proxy returns update api instead of create.
I have added the 'idProperty' parameter to the Model, but still gives me the same result.
Model class:
Ext.define('TDC2011.model.Contact', {
extend: 'Ext.data.Model',
idProperty: 'id',
fields : [
{ name : "id", type : "int", mapping : "#id" },
{ name : "name", type : "string"},
{ name : "phone", type : "string"},
{ name : "email", type : "string"}]
});
Store Class:
Ext.define('TDC2011.store.Contacts', {
extend: 'Ext.data.Store',
model: 'TDC2011.model.Contact',
autoLoad: true,
pageSize: 35,
autoLoad: {start: 0, limit: 35},
proxy: {
type: 'ajax',
api: {
read : 'contact/view.action',
create : 'contact/create.action/',
update: 'contact/update.action/',
destroy: 'contact/delete.action/'
},
reader: {
type: 'json',
root: 'data',
successProperty: 'success'
},
writer: {
type: 'json',
writeAllFields: true,
encode: false,
root: 'data'
},
listeners: {
exception: function(proxy, response, operation){
Ext.MessageBox.show({
title: 'REMOTE EXCEPTION',
msg: operation.getError(),
icon: Ext.MessageBox.ERROR,
buttons: Ext.Msg.OK
});
}
}
}
});
Is there anyone who knows the main cause of problem?