loopback hasMany relation remoteMethod hook - loopbackjs

I am using loopback for develop my own website.
But recently I had a problem of hasMany remoteMethod.
Here is the problem:
I have two models :
person.json:
{
"name": "Person",
"base": "PersistedModel",
"strict": true,
"idInjection": true,
"properties": {
/*...
....
*/
},
"validations": [],
"relations": {
"friends": {
"type": "hasMany",
"model": "Friend",
"foreignKey": "personId"
}
},
"acls": [],
"methods": []
}
friend.json
friend.json:
{
"name": "friend",
"base": "PersistedModel",
"strict": true,
"idInjection": true,
"properties": {
/*...
....
*/
},
"validations": [],
"relations": {
},
"acls": [],
"methods": []
}
I want to use beforeRemote when I call POST /api/Persons/{id}/friends.
So I code in person.js
module.exports = function(Person) {
Person.beforeRemote('__create__friends', function(ctx, instance, next) {
/*
code here
*/
});
};
But it does not work!
At the beginning I think it's the matter of '__create__friends',but when I
code in person.js like :
module.exports = function(Person) {
Person.disableRemoteMethod('__create__friends');
};
I could disable the '__create__friends' successfully.
So what's the problem?
Can anyone help me?

Because methods for related models are attached to Person prototype, you should register hook like this:
Person.beforeRemote('prototype.__create__friends', function() {
next()
})

Related

Loopback custom connector implementation

I am trying to implement a custom loopback connector and it's not clear to me how this all works.
Here are my models:
{
"customer": {
"dataSource": "qb",
"public": false
},
"company": {
"dataSource": "qb",
"public": true
},
"payment": {
"dataSource": "qb",
"public": false
},
"invoice": {
"dataSource": "qb",
"public": false
}
}
The most important part to the model (and to save space) is
{
"relations": {
"company": {
"type": "belongsTo",
"model": "company",
"foreignKey": "id",
"primaryKey": "id"
}
}
}
And, in company.json
{
"name": "company",
"plural": "companies",
"base": "Model",
"idInjection": true,
"options": {
"validateUpsert": true
},
"properties": {
"id": {
"type": "string",
"required": true
}
},
"validations": [],
"relations": {
"customers": {
"type": "hasMany",
"model": "customer",
"foreignKey": "customerId"
},
"payments": {
"type": "hasMany",
"model": "payment",
"foreignKey": "customerId"
},
"invoices": {
"type": "hasMany",
"model": "customer",
"foreignKey": "customerId"
}
},
"acls": [],
"methods": {}
}
which, as expected, produces URLs like:
/companies/${id}/customers/${fk}
So, I try the swagger UI and submit: GET /companies/4620816365214377730/customers/456
The problem I have is now 2 fold:
It calls the all function on my connector every time - right away, that doesn't make sense. I've given it 2 specific ID's why would it possible want all of anything?
I managed the above and produced the results asked, but then loopback reports a 404:
{
"error": {
"statusCode": 404,
"name": "Error",
"message": "could not find a model with id 4620816365214377730",
"code": "MODEL_NOT_FOUND",
"stack": "Error: could not find a model with id 4620816365214377730"
}
}
So, I definitely don't get it - the first param in callback is the err, and the second is the result. I have literally hardcoded it to be right (I think)
How do I implement simple CRUD? Why does it not call my findById function? I have breakpoints everywhere
const {Connector: connector} = require('loopback-connector')
const util = require("util");
exports.initialize = function initializeDataSource(dataSource, callback) {
dataSource.connector = new QbConnector(dataSource.settings);
dataSource.connector.dataSource = dataSource;
};
exports.QbConnector = QbConnector
function QbConnector(settings, datasource) {
connector.call(this, 'quickbooks', settings)
this.datasource = datasource
this.client = require(`./qb`)(require('./axios'))
}
util.inherits(QbConnector, connector);
// connector.defineAliases(QbConnector.prototype, 'find', 'findById');
QbConnector.prototype.create = function(data, callback) {
console.log()
}
QbConnector.prototype.replaceOrCreate = function(model, data, options, cb) {
console.log()
}
QbConnector.prototype.findOne = function (filter,cb) {
console.log()
}
QbConnector.prototype.all = function(model, filter, callback) {
this.client[model]?.get(filter.where.id)
?.then(data => callback(null,{id: filter.where.id}))
?.catch(e => callback(JSON.stringify(e.response.data,null,4)))
}
QbConnector.prototype.count = function (whereClause,callback) {
console.log()
}
QbConnector.prototype.save = function(model, data, options, cb) {
console.log()
}
QbConnector.prototype.findById = function (id, filter, options) {
console.log()
}
When I step into the callback it's definition is a guaranteed error (the message I am seeing)
(function anonymous(number, plural, select, pluralFuncs, fmt
) {
return function(d) { return "could not find a model with id " + d["0"]; }
})

Loopback: How to define a property with an array of strings in Loopback?

I have the following model in a loopback application, that will be persisted in a MongoDB:
Model
Name Coffeshop:
Id
Name (string)
City (String)
Question:
Now i want to be able to store a list of strings in a new property called "tags":
Tags (Array of string)
There is no relation to other models necessary. I need just a plain flat list of strings.
How can i achieve this?
Code:
{
"name": "CoffeeShop",
"plural": "CoffeeShops",
"base": "PersistedModel",
"idInjection": true,
"options": {
"validateUpsert": true
},
"properties": {
"name": {
"type": "string",
"required": true
},
"city": {
"type": "string",
"required": true
}
},
"validations": [],
"relations": {},
"acls": [],
"methods": {}
}
Thats easy:
{
"name": "CoffeeShop",
"plural": "CoffeeShops",
"base": "PersistedModel",
"idInjection": true,
"options": {
"validateUpsert": true
},
"properties": {
"name": {
"type": "string",
"required": true
},
"city": {
"type": "string",
"required": true
},
"tags": {
"type": [
"string"
],
"required": false
}
},
"validations": [],
"relations": {},
"acls": [],
"methods": {}
}

Remove pk in the loopback swagger

In loopback, how could I remove the PK from the swagger json displayed.
This is the json displayed in my swagger:
{
"user_id": "string",
"order_type": "string",
"date": "2016-04-28",
"payload": {
"id": 0
},
"id": 0
}
image detail- Swagger
how could I remove the "id": 0 ?
This is my order.json :
{
"name": "Order",
"plural": "Orders",
"base": "Model",
"idInjection": true,
"options": {
"validateUpsert": true
},
"properties": {
"user_id": {
"type": "string",
"required": true
},
"order_type": {
"type": "string",
"required": true
},
"date": {
"type": "date",
"required": true
},
"payload": {
"type": "Payload",
"required": true
}
},
"validations": [],
"relations": {},
"acls": [],
"methods": {}
}
This is my order.js:
module.exports = (Order) => {
Order.create = function(body, cb) {
//
}
Order.remoteMethod('create', {
'http': {'path': '/'},
'accepts': [
{'arg': 'body', 'type': 'Order', 'required': true, 'http': { 'source': 'body' } }
]
});
};
Hidden property did the trick
{
"name": "Order",
"plural": "Orders",
"base": "Model",
"idInjection": false,
"options": {
"validateUpsert": true
},
"properties": {
...
},
"validations": [],
"relations": {},
"acls": [],
"methods": {},
"hidden": ["id"]
}

scope in inherited model

I have a contact db table and model. Employee model inherits from contact.
If i do GET employees/ it returns all the contacts.
How should I set up my employee.json if I want to return only the contacts with partnerId = 1?
{
"name": "employee",
"base": "contact",
"strict": false,
"idInjection": false,
"options": {
"validateUpsert": true,
"postgresql": {
"schema": "public",
"table": "contact"
}
},
"scope": {
"where": {
"partnerId": 1
}
},
//...
}
Debug says calling GET employees/ makes the following query:
SELECT "name", "position", "email", "password", "id" FROM "public"."contact" ORDER BY "id"
It does not seem that scope is added.
models/partner.json
{
"name": "partner",
// ...
"properties": {
"name": {
"type": "string",
"required": true
},
// ...
},
"validations": [],
"relations": {
"contacts": {
"type": "hasMany",
"model": "contact"
}
//...
},
"acls": [],
"methods": {}
}
Try using the where filter, either in the REST API
/employees?filter[where][partnerId]=1
or in your Employee.js
Employee.find({ where: {partnerId:1} });
https://docs.strongloop.com/display/APIC/Where+filter

Createmany in Strongloop Loopback

I have an Order model which hasMany OrderItem models. But once a client wants to create an Order, it has to create an Order object first then for each product he added to his basket, he needs to create responding OrderItems separately. As you may notice it causes many reduntant requests. May be I can make a custom method for OrderItems which consumes a product list. But i was wondering if there is a built in mechanism for this like createMany since it is a very useful operation.
ORDER MODEL
{
"name": "Order",
"plural": "Orders",
"base": "PersistedModel",
"idInjection": true,
"properties": {
"customerId": {
"type": "number",
"required": true
},
"branchId": {
"type": "number",
"required": true
}
},
"validations": [],
"relations": {
"orderItems": {
"type": "hasMany",
"model": "OrderItem",
"foreignKey": "orderId"
}
},
"acls": [],
"methods": []
}
ORDERITEM MODEL
{
"name": "OrderItem",
"plural": "OrderItems",
"base": "PersistedModel",
"idInjection": true,
"properties": {
"UnitPrice": {
"type": "number"
},
"productId": {
"type": "number",
"required": true
},
"purchaseOrderId": {
"type": "number",
"required": true
},
"quantity": {
"type": "number"
}
},
"validations": [],
"relations": {
"product": {
"type": "belongsTo",
"model": "Product",
"foreignKey": "productId"
},
"purchaseOrder": {
"type": "belongsTo",
"model": "PurchaseOrder",
"foreignKey": ""
}
},
"acls": [],
"methods": []
}
Loopback "create" method accepts also an array of objects (see PersistedModel.create docs) so you should try creating one "create" call and send an array of OrderItems.