bloodhound multiple dataset cause typeahead template issue - templates

I've local elastic search server, install and running.
I instanciate 2 bloodhound object followig examples (can't post link because of reputation limitations)
If I use output as is, I have my results from my 2 datasource, no trouble.
When I want to use, remote: transform or filter option, to format the data, for using a custom template, I've trouble, the 2 template never get call.
Here's my code :
First bloodhound :
var nameSuggest = new Bloodhound({
datumTokenizer: Bloodhound.tokenizers.obj.whitespace,
queryTokenizer: Bloodhound.tokenizers.obj.whitespace,
identify: 'nameSuggest',
sufficient: 50,
remote: {
url: 'http://localhost:9200/test2/_suggest?pretty',
prepare: function (query, settings) {
settings.type = "POST";
settings.contentType = "application/json; charset=UTF-8";
search_payload = {
"suggest": {
"text": query,
"completion": {
"field": "suggest"
}
}
};
settings.data = JSON.stringify(search_payload);
return settings;
},
transform: function(response) {
return $.map(response.suggest[0].options, function (option) {
return {
optionText: option.text,
optionId:option.payload.id
};
});
}
}
});
Second dataset:
var mailSuggest = new Bloodhound({
datumTokenizer: Bloodhound.tokenizers.obj.whitespace,
queryTokenizer: Bloodhound.tokenizers.obj.whitespace,
identify: 'mailSuggest',
sufficient: 50,
remote: {
url: 'http://localhost:9200/test2/_suggest?pretty',
prepare: function (query, settings) {
settings.type = "POST";
settings.contentType = "application/json; charset=UTF-8";
search_payload = {
"suggestMail": {
"text": query,
"completion": {
"field": "suggest2"
}
}
};
settings.data = JSON.stringify(search_payload);
return settings;
},
transform: function(response) {
return $.map(response.suggestMail[0].options, function (option) {
return {
optionText2: option.text,
optionId2:option.payload.id
};
});
}
}
});
And typeahead:
jQuery('#topSearch').typeahead({
name:'topSearch',
hint: true,
highlight: true,
limit: 20
},
{
name: 'nameSuggest',
display: 'data',
source: nameSuggest,
templates: {
header: '<div><h3 class="">Noms</h3></div>',
suggestion: function (data) {
console.log("Name");
return '<div>'+data.optionId+' - '+data.optionText+'</div>';
}
}
},
{
name: 'mailSuggest',
display: 'data',
source: mailSuggest,
templates: {
header: '<div><h3 class="">Mails</h3></div>',
suggestion: function (data) {
console.log("Mail");
return '<div>'+data.optionText2+'</div>';
}
}
}
);
When I do :
console.log(nameSuggest);
console.log(mailSuggest);
I've two separate object, with unique names (the identify option) :
Bloodhound { identify="nameSuggest", sufficient=50, local=[0], plus...}
Bloodhound { identify="mailSuggest", sufficient=50, local=[0], plus...}
but, in the remote part of each object I can see the transform and prepare section with the two object names (there are screenshot) :
first object
seconde object
If I remove transform option from both bloodhound instances, and templates for typeahead, it works, and I'v suggestions.
If I remove transform of the second bloodhound instance and template associated, first results are displayed, withing the template, and second result are displayed raw, but it works.
If I let the second template in typeahead init, without bloodhound associated transform, the second template header is displayed, but the data undefined (normal behavior I suppose).
So, somehow, transform of the second bloodhound break something, but I can't figure out what, and how.
Do I miss something, or did something wrong ?

Solved:
I have to add the size option to the query, to tell elastic to send more result:
var mailSuggest = new Bloodhound({
datumTokenizer: Bloodhound.tokenizers.obj.whitespace,
queryTokenizer: Bloodhound.tokenizers.obj.whitespace,
identify: 'mailSuggest',
sufficient: 50,
remote: {
url: 'http://localhost:9200/test2/_suggest?pretty',
prepare: function (query, settings) {
settings.type = "POST";
settings.contentType = "application/json; charset=UTF-8";
search_payload = {
"suggestMail": {
"text": query,
"completion": {
"field": "suggest2",
"size": 20
}
}
};
settings.data = JSON.stringify(search_payload);
return settings;
},
transform: function(response) {
return $.map(response.suggestMail[0].options, function (option) {
return {
optionText2: option.text,
optionId2:option.payload.id
};
});
}
}
});
I tried with 20 for testing prupose.

Related

AWS AppSync merging, sorting and pagination of data from multiple REST calls

I'm trying to set a GraphQL endpoint using AWS AppSync that consumes from 2 HTTP data sources, merges the responses, orders them by date and implements pagination.
So far I've accomplished to make both requests and merge them using union
Schema
type Event1 {
id: ID!
name: String
type: String
order_date: String
}
type Event2 {
id: ID!
name: String
type: String
order_date: String
}
union Events = Event1 | Event2
listEvents(): [Events!]
Resolver 1
export function request(ctx) {
return {
"method": "GET",
"resourcePath": "/event1",
"params": {
"headers": {
"Content-Type" : "application/json"
},
}
}
}
export function response(ctx) {
if (ctx.result.statusCode !== 200) {
return util.appendError(ctx.result.body, `${ctx.result.statusCode}`);
}
var responseBody = JSON.parse(ctx.result.body);
/*for (var i in responseBody) {
responseBody[i].__typename = "Event1";
}*/
return responseBody;
}
Resolver 2
export function request(ctx) {
return {
"method": "GET",
"resourcePath": "/event2",
"params": {
"headers": {
"Content-Type" : "application/json"
},
}
}
}
export function response(ctx) {
if (ctx.result.statusCode !== 200) {
return util.appendError(ctx.result.body, `${ctx.result.statusCode}`);
}
var responseBody = JSON.parse(ctx.result.body);
/*for (var i in responseBody) {
responseBody[i].__typename = "Event2";
}*/
return [...ctx.prev.result, ...responseBody];
}
I made each service return the __typename so AppSync knows which type is in the union, but now I've looking for ways to sort by "order_date" and then get the first page, but I don't know if I'm thinking it correctly or this not the purpose GraphQL was intended to fulfill.
Any guide will be very much appreciated.

options.scales.yAxes[0].ticks.callback not getting updated dynamically in ember-cli-chart

I have embedded ember-cli-chart in my hbs file as
<div class="chart">
{{ember-chart type='line' data=data options=options}}
</div>
In my component file I have created an options property as
options: computed('metric', function() {
let opts = defaultOptions;
if (this.metric === 'height') {
opts.scales.yAxes = [{
ticks: {
callback: function(value, index, values) {
// code to return labels
}
}
}]
} else {
opts.scales.yAxes = [{
ticks: {
callback: function(item, index, items) {
// code to return labels
}
}
}]
}
return opts;
});
I want to display Y-Axis labels based on the current selected metric.
When first time chart loads it renders correct labels on y-Axis and if I change the metric then the same callback is getting used instead of the other one (in else part) and renders same labels but with updated data values.
Can anyone help on this?
Hmmm I don't know the addon or chart.js for the matter, but when looking at the source code for the ember-chart component, I see
didUpdateAttrs() {
this._super(...arguments);
this.updateChart();
},
updateChart() {
let chart = this.get('chart');
let data = this.get('data');
let options = this.get('options');
let animate = this.get('animate');
if (chart) {
chart.config.data = data;
chart.config.options = options;
if (animate) {
chart.update();
} else {
chart.update(0);
}
}
}
So, in order for chart.js to update, you need didUpdateAttrs to fire, which means in your case here that options itself needs to change. I don't know how you're creating defaultOptions, but assuming this reference never changes, there's no reason that didUpdateAttrs would fire since you aren't changing the reference to options (you're only changing child props of defaultOptions in the computed). I would suppose that:
import { assign } from '#ember/polyfills';
...
options: computed('metric', function() {
let opts = assign({}, defaultOptions);
if (this.metric === 'height') {
opts.scales.yAxes = [{
ticks: {
callback: function(value, index, values) {
// code to return labels
}
}
}]
} else {
opts.scales.yAxes = [{
ticks: {
callback: function(item, index, items) {
// code to return labels
}
}
}]
}
return opts;
})
would be enough to trigger the behavior you want since we always return a new object when a recomputation of options occurs.

Typeahead 0.10 prevent caching

I use twitter's typeahead 0.10 with remote url to retrieve JSON results from server.
I would like to prevent tthe client caching so that the search takes place always on the
server. How can I do that?
Please see below my code:
// instantiate the bloodhound suggestion engine
var dataSource = new Bloodhound({
datumTokenizer: function (d) {
return Bloodhound.tokenizers.whitespace(d.value);
},
queryTokenizer: Bloodhound.tokenizers.whitespace,
remote: {
url: "../" + autocompleteInfo.ControllerName + "/" + autocompleteInfo.MethodName + "?term=%QUERY&ts=" + (new Date().getTime()),
filter: function (res) {
var data = [];
data = $.map(res, function (item) {
return { label: item.Name, id: item.Id, autocompleteInfo: autocompleteInfo, cssClass: item.Class };
});
return data;
}
},
limit: 15,
name: 'typeaheadSourceCache',
ttl: 0,
ajax: {
cache: false
}
});
dataSource.initialize();
$("#" + autocompleteInfo.AutocompleteId).typeahead({
minLength: 3,
highlight: true,
autoselect: true
},
{
displayKey: 'label',
source: dataSource.ttAdapter(),
templates: {
suggestion: Handlebars.compile(
'<div class="searchItem {{cssClass}}">{{label}}</div>'
)
}
});
Just add cache field to remote object:
remote: {
'cache': false
...
}
Look at version 10.0.2. There is now a means to clear cache via Bloodhound.js (used in association with Typeahead.js):
engine.clearRemoteCache();
Here is the documentation from twitter typeahead:
https://github.com/twitter/typeahead.js/blob/master/doc/bloodhound.md#bloodhoundclearremotecache
Try to use typeahead destroy utils, i think in your case are:
$("#" + autocompleteInfo.AutocompleteId).typeahead('destroy');
The you reinizialize $("#" + autocompleteInfo.AutocompleteId)
To fix IE issues I've came to:
remote: {
url: '/myurl?par=%QUERY',
wildcard: '%QUERY',
prepare: function (q, o) {
o.url = o.url.replace('%QUERY', encodeURIComponent(q));
o.cache = false;
return o;
}
}
prefetch: {
url: '/myurl2',
ttl: 300000, //5min
thumbprint: userName,
prepare: function(o) {
o.cache = false;
return o;
}

Sencha Touch list store disable sorting

I have my list which is getting data from php service, the data received is in the order I need. But sencha automatically sort my list alphabetically.
Below is my code:
Ext.define('MyList', {
extend: 'Ext.dataview.List',
config: {
grouped: true,
plugins: [
{
xclass: 'Ext.plugin.PullRefresh',
pullRefreshText: 'Pull down to refresh'
},
{
xclass: 'Ext.plugin.ListPaging',
autoPaging: true,
noMoreRecordsText: 'No More Records'
}
]
},
initialize: function () {
this.callParent(arguments);
var store = Ext.create('Ext.data.Store', {
pageParam: 'page',
grouper: {
groupFn: function (record) {
return record.data.group_label;
}
},
model: 'ListItem',
proxy: {
type: 'ajax',
url: '/m/services/activity_list_items.php',
reader: {
type: 'json',
rootProperty: 'root.results'
}
}
});
var template = Ext.create('GenericListItem', {
hascounts: true,
hasicon: true,
varmap: {
descr: 'subtext',
count: 'sub_item_cnt',
itemid: 'itemid',
uniqid: 'uniqid'
}
});
var emptyText = 'Recent Activity Items';
this.setStore(store);
this.setItemTpl(template);
this.setEmptyText(emptyText);
}
});
How can I avoid the auto sorting of list?
Add the following to your store config.
remoteSort : true,
remoteSort defaults to false in sencha. So sencha automatically sorts in the client side. Check the link for more details http://docs.sencha.com/touch/2-0/#!/api/Ext.data.Store-cfg-remoteSort
Just remove this:
grouped: true
from your list config if you don't want a header for each item and compulsory to remove this:
grouper: {
groupFn: function (record) {
return record.data.group_label;
}
}
from your store because basically in your situation grouper property are using for grouping your item alphabetically based on your group_label field. Hope it helps :)

How to jsonify "Add" post/parameters for jqGrid

This one's killing me. I've read through a lot of Oleg's comments, and through the documentation, but I think I'm overlooking something really simple.
I have a jqGrid populated by calling a webmethod that returns JSON. We're good there. I'm using the Navigator for my "Add" button, and using onSelectRow w/ jqGrid.editRow() for my editing.
I get the dialog box when clicking the "Add" button, and can fill everything in. However, I get a error Status: 'Internal Server Error'. Error code: 500 return message after clicking the Submit button. Using Firebug, the Response is {"Message":"Invalid JSON primitive: FileType.","StackTrace":..... and the Post is FileType=3&ExportDate=12%2F29%2F2010&oper=add&id=_empty.
Obviously, my post is not getting "jsonified". I have tried using serializeEditData, and beforeSubmit in an attempt to manually return JSON.stringify(eparams);, but nothing has worked. Please see my code below.
Webmethod
<WebMethod()> _
<ScriptMethod()> _
Public Sub ModifyFileLog(ByVal FileType As String, _
ByVal ExportDate As Nullable(Of Date), _
ByVal oper As String, ByVal id As String)
Try
' blah
Catch ex As Exception
Throw New Exception(ex.Message)
End Try
End Sub
JS - Globals
jQuery.extend(
jQuery.jgrid.defaults, {
type: "POST",
mtype: "POST",
datatype: "json",
ajaxGridOptions: { contentType: "application/json" },
ajaxRowOptions: { contentType: "application/json" },
rowNum: 10,
rowList: [10, 20, 30],
serializeGridData: function(data) {
return JSON.stringify(data);
},
gridview: true,
viewrecords: true,
sortorder: "asc"
},
jQuery.jgrid.edit, {
ajaxEditOptions: { contentType: "application/json" },
recreateForm: true,
serializeEditData: function(postData) {
return JSON.stringify(postData);
}
}
);
JS - jqGrid
var tblName = "tblFiles";
var pager1 = '#pagerFiles';
var grid = $("#" + tblName);
grid.jqGrid({
url: 'WebService.asmx/GetFileLog',
colNames: ['ID', 'File Type', 'Report Date', 'Export Date', 'EE Count'],
ajaxGridOptions: {
success: function(data, textStatus) {
if (textStatus == "success") {
ReceivedClientData(JSON.parse(getMain(data)).rows, grid); // populates grid
endGridRequest(tblName); // hides the loading panel
}
},
error: function(data, textStatus) {
alert(textStatus);
alert('An error has occured retrieving data!');
}
},
editurl: "WebService.asmx/ModifyFileLog",
serializeEditData: function(postData) {
return JSON.stringify(postData);
},
recreateForm: true,
pager: pager1,
...
}); // end .jqGrid()
grid.jqGrid('navGrid', pager1, { add: true, del: false, edit: true, view: false, refresh: true, search: false },
{}, // use default settings for edit
{
//beforeSubmit: submitAddFileLog,
closeAfterAdd: false,
closeAfterEdit: true
}, // use default settings for add
{}, // delete instead that del:false we need this
{multipleSearch: false }, // enable the advanced searching
{closeOnEscape: true} /* allow the view dialog to be closed when user press ESC key*/
); // end grid/jqGrid('navGrid')
NOTE: I started out populating by using $.ajax() by way of datatype: function(data), but thought I would return to the simplest example to get this to work. If you care to offer your thoughts on the advantages of using $.ajax() over simply using grid.jqGrid({ url: blah });, I'd love to learn more. Otherwise, please let me know if it would be more appropriate to post it as a separate question.
Also, please let me know if I'm just flat out doing this the wrong way. I'm not locked in to any one way of getting this done. I would prefer to be wrong and to learn how to do this the right way, than to be "right" in my own mind and continue to hack my way through it.
Any help, along w/ examples, would be hugely appreciated.
In my opinion your main problem is in JS - Globals. You use jQuery.extend function in a wrong way. You should replace one call
jQuery.extend(
jQuery.jgrid.defaults, {
// ...
},
jQuery.jgrid.edit, {
// ...
}
);
to two separate calls:
jQuery.extend(
jQuery.jgrid.defaults, {
// ...
}
);
jQuery.extend(
jQuery.jgrid.edit, {
// ...
}
);
After that the edit request to the server will be {"FileType":3,"ExportDate"="12/29/2010","oper":"add","id":"_empty"} instead of FileType=3&ExportDate=12%2F29%2F2010&oper=add&id=_empty.
Next, I am not sure that you can use ExportDate as a Date (DateTime ???) type. Probably you should start with String type and then convert the input data to the datatype which you need.
Next remark. Be sure that ModifyFileLog return JSON data. For example you can use <ScriptMethod(ResponseFormat:=ResponseFormat.Xml)> instead of <ScriptMethod()>. If you use .NET 4.0 you can achieve the same in many other ways.
One more thing. The ModifyFileLog should be Function instead of Sub and return the Id of new added object. In case of edit or del operations the return value will be ignored.
Because ModifyFileLog Function will be returned JSON data you have to decode/parse it. You can do this almost in the same way which I described here. In case of ASMX web service you can do about following:
jQuery.extend(
jQuery.jgrid.edit, {
ajaxEditOptions: { contentType: "application/json" },
recreateForm: true,
serializeEditData: function(postData) {
return JSON.stringify(postData);
},
afterSubmit: function (response, postdata) {
var res = jQuery.parseJSON(response.responseText);
return [true, "", res.d];
}
}
);