What's the correct way via API to create an instance with a through relation in loopback.io? - loopbackjs

I've two models, A and B which extends user buildt-in model. They both have a relation "has many" with each other using a through model A_B.
I want to add an instance of B related with an existing A instance.
I've try to post the new B instance with a field As ("As" is the relation name) setted with an array containing the A instance
var b = {"property1":"asdf","property2":"asdf","As":a};
$http.post(serverURL+"/api/bs",b);
The b instance is created, but there is no relation created.
I must to create the A_B instance by hand (or in "after save" hook)?
PD: I'm using angularjs and it's $http service to make API calls.

Check this out: HasManyThrough relation
The advantage of using this approach: new url endpoints are created along with common CRUD operation i.e. New rest endpoint has its own specific tasks and therefore, its usage is easy to understand and is more maintainable. These rest endpoints will create relations in the database as the CRUD operations happen.
You can get the generated url using loopback api on browser.

Related

AWS Studio create new mutation

I am kind of new to aws amplify and I don't understand where I can create a new mutation of type "create".
I would like to do the following:
I have one house model (GraphQL) that has a name and can have multiple people assigned to it (one to many).
When I create the house, I want to automatically assign the user who is connected (cognito) to be the owner of the house. From the serverside so on the mutation because i don't want to assign this in the api call since it could be modified.
Any tips where I can create this mutation or a link to a tutorial on how to accomplish this?

Retrieve db records based on user role

I'm new in Laravel that's why I'm pretty sure that my ideas are wrong. To the point...
I'm building Laravel application.
What I have among other:
Users ( build in with Laravel auth with my custom fields )
Roles ( pivot, many to many )
Companies ( each user belongs to company ( many users can belong to one company ).
Locations ( each company has many Locations )
Now I'm in the middle of creating documents. For now it doesn't matter if user_id or company_id will be included in the document header.
What I need is to have ability to e.g.
Show documents - when I go to page with documents list with ADMIN role I will see all docs stored in db BUT when user with USER role goes to the same route ... he'll get the list of owned docs
location/edit/{id} - prevent going to url with not mine id - this is simpler and I guess can be dealed using middleware
I have 3 ideas:
Create somekind of FrontController and inside constructor run method that returns all users_ids ( or all companies_ids ) if user is ADMIN or when USER return only one id. All controller in the application then extends this FrontController
Create Service Class ( end up with many services depends on what model to retrieve ), method to get records from db calling repository with role parameter. Then in this method do the checks which ids should be used.
Maybe User somehow Laravel Policies and before() method. Nów I’m reading documentation but I really don't know how to use it in this case but I feel that this idea is also possible.
I feel that these ideas are "dirty". Can you, please, provide information how to implement this nicely with code snippet? I think this subject is very common and a lot of people will use this thred. I would be grateful for any tips.
One approach could be using local scopes.
https://laravel.com/docs/5.5/eloquent#local-scopes
On your Document model define two scopes:
public function scopeBelongingToUser($query)
{
return $query->where('user_id', auth()->user()->id);
}
// this is the same as doing on your User model
public function documents()
{
$this->hasMany(Document::class);
}
public function scopeBelongingToAdmin($query)
{
if (auth()->user()->roles->contains('admin') {
return $query->select('*');
}
abort(403, 'Unauthorized');
}
Then you can use it later with:
Document::belongingToUser();
Document::belongingToAdmin();

Rails 4 generic parent model with more specific child models

I am working on my first real Rails 4 app and I have run into a problem with my design.
Currently I have a "Service" model which started out with attributes such as name, online_status, ip, dns_name, port, and service_type. This model has evolved to include many methods and attributes for specific service_types (like auth_tokens, etc.) and thus it is very overgrown. The columns added to the database to accommodate the needs of the different types of services make this model act like a ghetto version of STI without separate classes/models.
The Service model also has methods such as ping() which is used to determine the online_status. I believe the types of services are different enough to warrant their own separate tables because each service seems to have many unique properties and methods.
Example:
A generic service has: name, ip, dns_name, online_status, etc...
A specific service such as Plex will have: name, ip, dns_name, online_status, username, password, auth_token, etc...
The issue, is that I would like to be able to access the more specific types of services from their parent Service class. So when I create a view, I can loop through all the generic services and the more specific services as if they were all the same type of service (or at least be able to access all services in some simple way without looping through each type and appending them).
I also need to access the specific types of models on their own, so doing something like #couchpotatos.each in my view will only go through the instances of the Couchpotato class.
Controllers play into this confusion too since I don't exactly know how to have a single page display all these different types of models from the same controller.
Criticism is welcome! I'm learning, so if this desired design absolutely bonkers, please let me know :D
Ok let's give it shot. I hope I understand your current situation, but the first thing a thought of is using a ServiceConcern containing the shared logic of a service. So a basic example would be:
module Service
extend ActiveSupport::Concern
included do
belongs_to :user
end
def ping
"pong"
end
end
class PlexService < ActiveRecord::Base
include Service
def ping
"plex-pong"
end
end
You would create a new model for each Service implementation that MUST have the stuff a Service should have (in the case above it would be a user_id)
The problem remaining would be a generic way to find all the implementations of the Service concern.
To achieve that, you have to implement a STI, where the Base object would be "Service" with user_id and a type (in the case described above) and implementations with their overrides

Is there a way to map an object graph with #Query?

I'm am trying to migrate my SDN3 embedded configuration to using SDN 3.3.0 with a Neo4j instance in server mode (communicating via the REST API then).
When the DB was embedded making a lot of small hits to the DB was not a big deal as Neo4j is capable of handling this kind of queries super fast.
However now that I run my Neo4j separately from my application (ie. in server mode) making a lot of small queries is not advisable because of the network overhead.
User user = userRespository.findOne(123);
user.fetch(user.getFriends());
user.fetch(user.getManager());
user.fetch(user.getAgency());
This will trigger quite a few queries, especially if I want to get, not a single user, but a list of users.
Can I use the #Query annotation and fetch the user and the related entities and map it into an User object?
I was thinking of something like this:
#Query("MATCH (u:User)-[r:FRIEND]->(f) RETURN u,r,f"
Is such a thing possible with Spring Data Neo4j? Will it be possible with Spring Data Neo4j 4?
You can define a class for query result using the #QueryResult directive and let the method for the query return an object of that class, i.e.:
#QueryResult
public interface UserWithFriends {
#ResultColumn("u")
User getUser();
#ResultColumn("f")
List<User> friends();
}
#Query("MATCH (u:User)-[:FRIEND]->(f) WHERE u.name={name} RETURN u,f")
UserWithFriends getUserByName(#Param("name") String name);

Multi-tenant Django applications using Mongoengine

I want to build a multi tenant architecture for a SAAS system. We are using Django as our backend and mongoengine as our main database and gunicorn as our web-server.
Our clients are a few big companies, so the number of databases pre-allocating space shouldn't be a problem.
The first approach we took was to write a middleware to determine the source of the request to properly connect to a mongoengine database. Here is the code:
class MongoConnectionMiddleware(object):
def process_request(self, request):
if request.user.is_authenticated():
mongo_connect(request.user.profile.establishment)
And the mongo_connect method:
def mongo_connect(establishment):
db_name = 'db_client_%d' % establishment.id
connect(db_name)
This will register the "default" alias as the db_name for every mongoengine request.
But it seems that when many concurrent users from different companies are making requests, each one sets the default db_name to it's own name.
As an example:
Company A makes a request and connects to database A. While A is making it's work company B connects to database B. This makes A also connect to B's database in the process, so A fails to find some ids.
¿Is there a way to isolate the connection to the mongo database per request to avoid this problem?
Unfortunately MongoEngine seems to be designed around a very basic use case of a single primary connection and multiple auxiliary connections.
http://docs.mongoengine.org/en/latest/guide/connecting.html#connecting-to-mongodb
To get around the default connection logic, I define the first connection I come across as the default, I also add it as a named connection. I then add any subsequent connection as named connections only.
https://github.com/MongoEngine/mongoengine/issues/607#issuecomment-38651532
You can use the with_db decorator to switch from one connection to another, but it's a contextmanager call, which means as soon as you leave the with statement, it will revert. It also still requires a default connection.
http://docs.mongoengine.org/en/latest/guide/connecting.html#switch-database-context-manager
You might be able to put it inside a function and then yield inside the with to prevent it reverting immediately, I'm not sure if this is valid.
You could use a wrapper of some kind, either a function, class or a custom QuerySet, that checks the current django/flask session and switches the db to the appropriate connection.
I'm not sure if a QuerySet can do this, but it would probably be the nicest way if it can.
http://docs.mongoengine.org/en/latest/guide/querying.html#custom-querysets
I included some code in this issue here where I change the database connection for my models.
https://github.com/MongoEngine/mongoengine/issues/605
def switch(model, db):
model._meta['db_alias'] = db
# must set _collection to none so it is re-evaluated
model._collection = None
return model
MyDocument = switch(MyDocument, 'db-alias')
You'll also want to take a look at the code that mongoengine uses to switch dbs.
Beware that mongo engine likes to cache things, so changing a few variables here and there doesn't always cause an effect. It's full of surprises like this.
Edit:
I should also add, that the 'connect' call won't pick up value changes. So calling connect with new parameters wont take effect unless its a new alias. Even the disconnect function (which isn't exposed publically) doesn't let you do this as the models will cache the connection. I mention this in some of the issues linked above and also here: https://github.com/MongoEngine/mongoengine/issues/566