How can i create a loopback remote method for search - angularjs

In my loopback application i have a model named test. I need to search details and display the details based on multiple criteria. that is the search fields are status, priority, message and id. i want to dispalt the details based on these search fields. suppose i give status is open and priority is low the details should be satisfied with both these condition(that is "AND" operator).How should i implement this? My db is Arango Db. what i have is common/models/test.js
test.js
module.exports = function (Test) {
Test.search = function(callback){
}
};
How should i implement this? I am new to loopback and angular. Any help will really helpfull.

Implementing a remote method is documented here.
It requires two things. First, create the function that will be called remotely. Here, you've called it search.
Function parameters should include all request arguments (status priority message id) and a callback as last argument.
Then, register this function as a remote method.
In your case, it should give the following code
module.exports = function(Test){
Test.search = function(status, priority, message, id, cb) {
var results = ...// Your custom logic to find the results
if (err) return cb(err); // if something went wrong. err is returned by your custom logic
cb(null, results); // if results were found
}
Test.remoteMethod('search', {
http: {
verb: 'get'
},
accepts: [
{arg: 'status', type: 'string', http: { source: 'query' } },
{arg: 'priority', type: 'string', http: { source: 'query' } },
{arg: 'message', type: 'string', http: { source: 'query' } },
{arg: 'id', type: 'number'},
],
returns: {arg: 'results', type: 'Object'} // To return a JSON object for instance
});
};
Then, call your method with GET api/Tests/search?status=open&priority=high&...
For searching entries, you might also use the querying approach

Related

Accessing additional properties from JSON received through store's load method

I have a grid that loads data via a JSON store, however there are some additional properties beyond the records themselves that I need to access. Here's an example of what the JSON data looks like:
{
success: true,
records: [
{id: 1, name: 'bob'},
{id: 2, name: 'fred'}
],
extraProperty: 'foo'
}
I need to access that extraProperty when the grid data is loaded. So I assume I'd want to a callback, like so:
store.load({
callback: function (records, operation, success) {
//somehow access extraProperty here
}
});
I'm not sure what to do inside that callback. The operation variable, an Ext.data.operation.Operation object, has a private method called getResponse(). It returns an object in Chrome that has a responseJson property, but in IE it instead has a responseText property that needs to be decoded. So I could handle both scenarios, but since it's a private method I don't really want to rely on it in the first place. Any ideas?
Use the keepRawData config on the reader.
store.load({
callback: () => {
const { extraProperty } = store.getProxy().getReader().rawData;
}
});
Depending on your needs, you may also want to look at preserveRawData as well.
did you tried on the store level, something like below
under proxy in the reader config section
proxy: {
type: 'ajax',
actionMethods: {
read: 'GET'
},
headers: {
'Content-Type': 'application/json;charset=utf-8'
},
api: 'your url',
reader: {
extraProperty: 'extraProperty'
}
}

Angularjs strongloop custom method

I have defined a custom method in my strongloop application, which returns the right datas when I test it through the Api explorer.
I then generated the an angularjs service thanks to "lb-ng".
When I send a request with this custom method through angular I get this error :
Error in resource configuration for action `list`. Expected response to contain an object but got an array (Request: GET http://**myip**/api/Questions)
The thing is it should call this address instead :
http://**myip**/api/Questions/4/0
It used to work at some point, before a regenerated an angular service with lb-ng
Here is the method registration in strongloop :
Question.remoteMethod(
'list', {
http: {path: '/:lang/:start/', verb: 'get'},
accepts: [
{arg: 'lang', type: 'number'},
{arg: 'start', type: 'number'}
],
returns: {arg: 'questions', type: 'array'},
description: ['Returns an array obj the latest added questions filters by language and categories']
}
)
And here is the calling test in angular in my homeController :
function getQuestions(langId, start) {
Question.list(langId, start)
.$promise
.then(function(questionsList) {
$scope.questions = questionsList.questions;
}
);
}
getQuestions(4, 0);
Do you have any idea why the method is not calling the address with arguments ?
I am pretty sure that request parameters need to be on an object (as per the REST API use via explorer) as follows:
Question.list({lang:langId, start: start}).$promise.then(...)
I would also suggest generating the docular docs for the angular SDK as these help clarify things.
In the service file that was generated look for the list method and add/set the isArray parameter as true, it should be something like this:
"list": {
...
isArray: true,
...
}

ExtJS 5 load existing store with local data

I am doing unit testing and would like to add dummy data to an existing store. In the function I am testing, I am calling a store:
var tripStore = Ext.getStore('Trips');
Normally, this store would have been populated by an Ajax call at a previous point. However, since I am testing I want to use dummy data and not rely on the back end. I realize I could rewrite the function to pass in the store, but I do not want to rewrite this for the sake of testing.
Bottom line, how do I add local data to a store that already exists but has no data in it? Furthermore, the back end is not available, so when I try store.load or store.reload it throws a 404 saying it cannot find the url rest/trip. I don't want it to try and call this url, but instead I want to add local data.
The model definition:
Ext.define('app.model.Trip', {
fields:[
{name: 'someField1', type: 'string'},
{name: 'someField2', type: 'string'},
{name: 'someField3', type: 'string'},
],
proxy: {
noCache: true,
url: 'rest/trip',
reader: {
type: 'json',
rootProperty: 'trips'
}
}
});
The (attempted) test script that is calling the url when I don't want it to, but only want it to add the local data:
var tripsStore = Ext.StoreManager.lookup('Trips');
tripsStore.load({
autoLoad: false,
addRecords: true,
proxy: {
data: localData,
},
callback: function(records, operation, success) {
if (success) {
debugger
} else {
debugger
}
}
})
Use ajax.SimManager. See example (open Details on the right-hand side, click on any of the Data tabs).

extjs using jsonp,Accessing data from remote url

with extjs,i m runnig the server from one system,giving the url in another system and i m using JSONP in extjs ver:4.02,when i check in response i m getting data in json format,when i try to print in console or Store im not getting..here is my extjs code...
<script type="text/javascript">
Ext.Ajax.cors = true;
Ext.Ajax.useDefaultXhrHeader = false;
Ext.define('User', {
extend: 'Ext.data.Model',
fields: ['empid', 'name', 'email']
});
var myStore = Ext.create('Ext.data.Store', {
model: 'User',
autoLoad:true,
proxy: {
type: 'jsonp',
// url : 'data/tagfamily.json',
url:'http://192.168.7.70:8080/palamanagement/user/getAllRecords',
},
listeners:{
'load':function( store, records, successful, eOpts ){
alert(records);
console.log(records);
}
}
});
You literally have to return something like the following:
someCallback({
users: [
{
id: 1,
name: "Ed Spencer",
email: "ed#sencha.com"
}
]
});
So you already have the JSON the way you need it; you just need your server response to wrap the JSON in the callback so that the JSONP proxy can execute and load your store with data.
Therefore, when handling the JSONP request, your server's script needs to recognize the "callback" param that is sent as a part of the request. It then needs to use the value of this param to wrap your JSON response.
Be sure to read the docs that both myself and Oguz have posted: they outline the requirement pretty well. But if you don't respond with a callback, you'll never get your standard JSON response to work with the JSONP proxy.
When you request from DOMAIN-A to DOMAIN-B, you should provide a call back function in proxy definition. The callback function will use in after request complete.
For instance, in Flickr REST service, there is jsoncallback parameter which we should give our function name in order to complete our request. In this way, our request url will be:
.../?jsoncallback=ourFunction
To be able to provide our function name, there is a property in ExtJS which is callbackKey.
Like so:
Ext.define('User', {
extend: 'Ext.data.Model',
fields: ['empid', 'name', 'email']
});
Ext.data.JsonP.request('http://api.flickr.com/services/feeds/photos_public.gne', {
callbackKey: 'jsoncallback',
callback: ourFunctionName
});
or
Ext.data.JsonP.request('http://api.flickr.com/services/feeds/photos_public.gne', {
callbackKey: 'jsoncallback',
callback: function(data) {
...
}
});
PS: I know, you will not find callback property in doc but just to be sure there is. Check ext-all-debug-w-comments.js file, line 108486
Flickr Callback Function
JsonP callbackKey

Model without a Store

I created a model which contains a proxy to load a single record and its takes no params. I don't want to use a store since I'll never have more then one record. I create an instance of the Model but can't figure out how to tell it to call and load the record from the server. This is the only example I could find, but I don't have an id to pass.
User.load(123, {
success: function(user) {
console.log("Loaded user 123: " + user.get('name'));
}
});
Also I'm making and ajax call and not a rest call in case that matters.
The load(id, [config]) is static and will return provide you with a new record instance. It uses the proxy that was set via setProxy(proxy) (also static). Per default it will send a read request with the params id: 123. The static method allows you to set some default callbacks within the optional config object. These callbacks are needed to get the instance of the loaded record (or the error).
How it works
// create a Model class
Ext.define('MyApp.User', {
extend: 'Ext.data.Model',
fields: [
{name: 'id', type: 'int'},
{name: 'name', type: 'string'}
]
});
// apply a proxy instance
MyApp.User.setProxy(/*YourAjaxProxy*/);
// prepare a handler
var cb = function(model, op) {
// log the new model instance
console.log(model);
};
// get a instance
MyApp.User.load(123, {
scope: this, // should be the scope of the callback (cb)
success: cb
});
Not what you need? Just comment...
Just make an Ajax request and store the result in a variable.
Ext.Ajax.request({
url: '/data/get',
method: 'GET',
params: {
requestID: 'XXXX',
connName: 'yyyy'
},
success: function (responseData) {
var countResult = Ext.decode(responseData.responseText); }
});

Resources