Loopback - Custom Api not getting displayed in explorer - node.js

I have created a remote method in my model named "FreeEmailProviders" that contains fields "id" and "domainname".
The code for creating the remote method is as follows:
FreeEmailProviders.checkEmailDomain = function(email, cb) {
cb(null, email);
};
FreeEmailProviders.remoteMethod(
'checkEmailDomain',
{
http: {path: '/checkEmailDomain', verb: 'get'},
accepts: {arg: 'email', type: 'string'},
returns: {arg: 'isEmailFreeProvider', type: 'string'}
}
);
Now when i am running the application, this method is not displaying in the list of APIs for this method.
When i am running the api directly in the browser, that is when i am calling the url:
http://localhost:4000/api/FreeEmailProviders/checkEmailDomain?email=test#gmail.com
I am getting the below error:
{"error":{"name":"Error","status":404,"message":"Unknown \"FreeEmailProviders\" id \"checkEmailDomain\".","statusCode":404,"code":"MODEL_NOT_FOUND","stack":"Error: Unknown \"FreeEmailProviders\" id \"checkEmailDomain\".\n at Function.convertNullToNotFoundError }}
Can anyone help me with this ?

I ran into the same problem. After 3 hours I figured I had a typo in the *.js file.
If you used the model generator you should not run into this issue. If you created the files yourself make sure the .json and .js file in common/models have exact the same name except for the extension.
It would be nice if Loopback throws an error in such cases.

Related

Stripe warning - Unrecognized token creation parameter

I'm just starting with stripe, and I noticed I get a warning in chrome saying:
Unrecognized token creation parameter parameter: company is not a
recognized parameter. This may cause issues with your integration in
the future.
This is the code.
stripe.createToken("account", {
company: {
name: "bbb",
address: {
line1: "77",
city: "abc",
state: "aa",
postal_code: "e2e"
}
},
tos_shown_and_accepted: true
}).then(function(result) {
debugger;
console.log(result);
});
I'm pretty much following the docs here (step 2)
https://stripe.com/docs/connect/account-tokens
It creates a token OK though.
The docs in the API reference suggest company is an object it should know:
https://stripe.com/docs/api/tokens/create_account
It basically tells you what is wrong.
It says that company is not a parameter that is recognized by that stripe endpoint. It creates the token, but ignores your passed parameter

search api in loopback nodejs

I have a need to implement this api in loopback nodejs
https://myapi.com/part_numbers?part_number=1245,6787,89490,940044...
Any ideas on how to go about it ?
The path after part_number should accept atleast 100 partnumbers and then return me the result.
All the documentation that i have looked at in loopback talks abut only sending a get request to something like https://myapi.com/part_numbers?part_number=1245
but not about sending for multiple comma separated values
Any ideas on how do i build this endpoint using loopback and nodejs I am using mysql as the backend datastore.
Disclaimer: I am a maintainer of LoopBack and co-author of the pull request adding support for character-delimited arrays in input arguments.
LoopBack provides a feature flag to enable comma-delimited array values in input arguments, this flag was added by https://github.com/strongloop/strong-remoting/pull/142. (Unfortunately it's not documented yet.)
How to use it:
1) Configure allowed delimiters in your server/config.json:
{
"restApiRoot": "/api",
// ...
"rest": {
"handleErrors": false,
// ADD THE FOLLOWING LINE
"arrayItemDelimiters": [","],
// original content - keep it around:
"normalizeHttpPath": false,
"xml": false
},
// ...
}
2) Define a custom remote method (see docs) accepting an argument of type "array of numbers". For example, assuming you have a model called PartNumbers already defined:
PartNumbers.get = function(numbers) {
// replace this code with your implementation
// here, we simply return back the parsed array
return Promise.resolve(numbers);
};
PartNumbers.remoteMethod('get', {
accepts: {
arg: 'part_numbers',
type: ['number'],
required: true,
},
// modify "returns" to match your actual response format
returns: {
arg: 'data',
type: 'object',
root: true,
},
http: {verb: 'GET', path: '/'},
});
3) Start you application, open API Explorer at http://localhost:3000/explorer and give your new method a ride!

Ember.js data records shows content: null in relationships inspector

I have the following code in my 'user.js' model in ember-data:
export default DS.Model.extend({
organization: DS.belongsTo('organization'),
//other stuff
});
The CRUD for the website is working as expected, and in MongoDB I can see the following for the organization field of User:
"organization" : ObjectId("571974742ce868d575b79d6a"),
BUT, and I'm not sure if this is an error in my code or me not understanding how Ember-data works, I cannot access that ID from a model hook like so:
model(){
return this.store.findRecord("user", this.get("session.currentUser.id"))
.then(user => this.store.findRecord("location", {organization: user.organization}));
}
And if I go to the Ember inspector to observe the belongsTo attribute of the User object, I see:
organization: <(subclass of Ember.ObjectProxy):ember956>
But clicking through I see content: null
What am I doing wrong? Could it be a server-side error?
Edit including JSON response from server for the above findRecord("user") call:
{
"links":{
"self":"/users/5719749a2ce868d575b79d6b"
},
"included":[
{
"type":"organizations",
"id":"571974742ce868d575b79d6a",
"links":{
"self":"/organizations/571974742ce868d575b79d6a"
},
"attributes":{
"creation-date":"2016-04-22T00:46:44.779Z"
}
}
],
"jsonapi":{
"version":"1.0"
},
"data":{
"type":"users",
"id":"5719749a2ce868d575b79d6b",
"links":{
"self":"/users/5719749a2ce868d575b79d6b"
},
"attributes":{
"email":"danthwa#gmail.com",
"first-name":"Daniel",
"last-name":"Thompson",
"registration-date":"2016-04-22T00:47:22.534Z"
},
"relationships":{
"organization":{
"type":"organizations",
"id":"571974742ce868d575b79d6a"
}
}
}
}
Confirmed. As stated by Kingpin2k,
the relationships isn't being built up correctly, I think the type and id inside of organization need to be within a data object.
This applies to Ember sites expecting a JSON API spec payload, meaning they have been configured to use JSONAPISerializer for incoming payloads.

Loopback: Cannot call Notification.create(). The create method has not been setup. The PersistedModel has not been correctly attached to a DataSource

I am using Loopback and the push component. When calling Notification.create() I get the error:
Cannot call Notification.create(). The create method has not been setup.
The PersistedModel has not been correctly attached to a DataSource!
I'm just running the basic example server 2.0. In code I am trying to create a Notification. What's the problem?
I too got the same problem when trying to use login function of User model.
Got it fixed after an hour of hit and trial.
Answer: I extended User model to MyUser model (No coding inside this model, just used it as a wrapper) and inside Hotel.js (in my case a business class where i use to authenticate user before accessing hotel details) created a remoteMethod for login
code:
Hotel.auth=function(uname,pwd, cb)
{
Hotel.app.models.MyUser.login({username: uname, password: pwd}, function (err, token) {
if(err)
cb(null,err);
else
cb(null,token);
});
}
Hotel.remoteMethod(
'auth',
{
accepts:
[
{arg: 'uname', type: 'string',required: true},
{arg: 'pwd', type: 'string',required: true}
],
returns: {arg: 'Response Message', type: 'string'}
}
);
This works!
This one is pretty old, but just to put something up here. Without seeing your setup my guess is that the model you are using is not connected to any data source, or one that is not written properly. The default connector is in-memory and does implement this method correctly. Check your server/model-config.json file and find the entry for Notification and check what you have for the data source.

LoopBack Remote Methods and Access to Model Data

I've been working on this for hours and I'm completely lost, because the loopback documentation is not helpful.
I'm trying to write application logic into a model. The documentation for that is here. Unfortunately, the example doesn't demonstrate anything useful other than passing an external value into the remote method and returning it again. I'd like to understand how to run a query in this context and access model data, but I have searched for hours and not been able to find documentation on even these simple tasks. Maybe I'm just looking in the wrong places. Can anyone help?
Typically, you can accomplish most things you'd want to do such as querying and accessing model data (CRUD operations) through the built-in methods that all models get; see http://docs.strongloop.com/display/LB/Working+with+data. Defining a remote method (custom REST endpoint) for these would be redundant.
You access the standard model CRUD Node APIs (e.g. myModel.create(), myModel.find(), myModel.updateAll() ) in the remote method code if you want to.
You may also find further related examples in https://github.com/strongloop/loopback-example-app-logic
Here's an example using the Getting Started app https://github.com/strongloop/loopback-getting-started app. It defines a remote method that takes a number arg and prints the name of the coffeeshop with that ID to the console:
This code is in common/models/coffeeshop.js:
module.exports = function(CoffeeShop) {
...
// Return Coffee Shop name given an ID.
CoffeeShop.getName = function(shopId, cb) {
CoffeeShop.findById( shopId, function (err, instance) {
response = "Name of coffee shop is " + instance.name;
cb(null, response);
console.log(response);
});
}
...
CoffeeShop.remoteMethod (
'getName',
{
http: {path: '/getname', verb: 'get'},
accepts: {arg: 'id', type: 'number', http: { source: 'query' } },
returns: {arg: 'name', type: 'string'}
}
);
};
You can use the API Explorer to load http://0.0.0.0:3000/explorer/#!/CoffeeShops/getName then enter a number (there are only three coffee shops in the app initially) as the query param and hit "Try It Out!"
Or just GET a URL like http://0.0.0.0:3000/api/CoffeeShops/getid?id=1
Rand
I finally discovered my problem. Object properties must be loaded in a callback of the function calling the CRUD operation. The following syntax worked for me:
module.exports = function (TestModel) {
TestModel.testRemoteMethod = function (id, name, cb) {
TestModel.findOne({where: {id: id}}, function(err, modelInstance) {
//modelInstance has properties here and can be returned to
//the API call using the callback, for example:
cb(null, {"name": modelInstance.name});
}
}
TestModel.remoteMethod('testRemoteMethod',
//..rest of config

Resources