How can I get model reference on the fly nestjs mongoose - node.js

So my problem is I have models that is separated by one of our domain's types, and it has a lot of types which each one of em has a dedicated collection. As I know, we can inject the model in the service constructor like this way:
#InjectModel(ModelName.Job) private readonly jobModel: JobModel,
It is a bit messy to me to inject all of those collections in the constructor, and also they are not useful at the same time. So I wonder if I could load mongoose model dynamically inside the service's method using the our domain type as the key, more or less same as the module reference like this:
private getModelReference(reference: any) {
return this.moduleReference.get(ModelName[reference]);
}
But, any other workarounds to load the model dynamically on the fly are appreciated.

It is technically possible to do. Using your code above you can do
private getModelReference(reference: any) {
return this.moduleReference.get(getModelToken(ModelName[reference]));
}
Assuming that ModelName[reference] refers back to a mongoose model name (i.e. Cat.name or just 'Cat')

Related

Dynamic determination for database

I have some entity mapping to a collection in a mongoDB. However, I have a separate database I want the same code to run against (eg. Constants.db_B). How can I make this parameter dynamic so I can run this without changing the constant and recompiling? If I could pass this as a parameter that would be fine too.
#MongoEntity(collection = "sample", database = Constants.db_A)
public class SomeEntity extends PanacheMongoEntity {
}
I tried using ConfigProperty on the Constants class, but it only injects it on a bean instance and not the class itself.
Is this possible?
It's not possible right now. This has been issued in the quarkus project.
https://github.com/quarkusio/quarkus/issues/14789
It's not the same casuistry than yours but there's a solution made from the Author of that issue, may be helpful for you
https://gitlab.com/ch3rub1/quarkus-mongo-mutitenant

Nest.js injection of model?

I have the follwoing code from tutorial|:
constructor(#InjectModel('User') private readonly userModel: Model<User>) {}
Where User is:
export interface User extends Document {
readonly name: string;
readonly age: number;
readonly phone: string;
}
Could you explain how #InjectModel works, what is 'User' and why we passed Model<User>, what does it mean?
What I can inject also using #InjectModel?
All right, to get into this, first we have to take to truth that interfaces do not exist at runtime. So the User interface you have is only useful during development. I'll try to break this down step by step, starting from the end of the line and working backwards.
Model<User>: Model is an interface type exposed by mongoose that allows us to know that the model we're using has methods like find and create. By saying Model<User> we are saying "This is a mongoose model object that refers to the User interface. This is especially useful for Typescript because as the functions are typed with generics, it knows what the return of methods like find are: an array of User objects. The model interface is really Model<T> where T is the interface that extends Document (another mongoose type).
What is 'User': 'User' is the string equivalent of the name of the interface. If your interface that extends Document is called Dog you use 'Dog', if it's Animal you use 'Animal'. The reason for not passing the interface is because interfaces do not exist at runtime (unlike classes).
How does #InjectModel() work: Okay, the really fun part of the question to answer. Nest works normally by using Injection Tokens. Normally, these tokens are determined by the type of the injected value. In your case Model<User>. Now, the problem here is that A) interfaces don't exist at runtime and B) Typescript does not reflect generics well, so even if Model was a class, all that could be gotten would be Model which isn't enough information on what to inject. So the next logical step Nest takes is to allow a user to provide injection tokens and use the #Inject() decorator. You can do things like injecting an object this way (like package configuration information). Useful, but a bit hard to work with without building your own providers. Now steps in #InjectModel(). #InjectModel() builds an injection token based on the string that's passed into the function. This token is something along the lines of typeModel where type is actually what you pass into the function. This tells Nest specifically what model we are injecting. This also needs to align with the provider created with MongooseModule.forFeature(), hence why name and the value passed to #InjectModel() need to be aligned. Usually it's easiest to align when they use the same string name as the interface.

Abstracting class using mongoose

I'm developing an application in which I need to have some abstraction.
I mean there, that I would like to "simulate" an interface behaviour like creating a contract inside of my concrete classes.
Actually, dealing with Users, I'm having a UserMongoRepository class with the contract implemented :
getAll() returns the full list of users by promise
getById(id) returns the user concerned by promise
save(user) saves the user by promise
... etc
I have the same methods implemented inside of the UserMysqlRepository (allowing me to switch behaviour when a change is needed.
Problem
My problem is that I'm dealing with Mongoose that doesn't act like a datamapper, but more like an active record.
It means that my implementation of save(user) would be a bit weird like following :
save(user){
let mongooseUser = this.convert(user);
return user.save();
}
The convert method allows me to switch from a standard Model to a specific Mongoose model. It allows me, again, to have some abstraction and to don't have to rewrite my full application data access.
My real problem is when I try to unit test my full class :
import MongooseUser from '../../auth/mongooseModel/MongooseUser';
/**
* UserMongoRepositoryclass
*/
export default class UserMongoRepository{
/**
* Create an UserMongoRepository
*/
constructor(){
}
/**
* Convert a User to a MongooseUser
*/
convert(user){
return new MongooseUser({email:user.mail,password:user.password,firstname:user.firstName, lastname:user.lastName});
}
findById(id){
return MongooseUser.find({id:id});
}
save(user){
return user.save();
}
}
In a standard way, I would inject my DAO inside of my constructor, and being able to mock it.
In the case of mongoose, it's a bit disturbing, because the element that makes the job isn't an instantiated object (so that I can mock it) but a class definition imported at the top of the document.
Solutions
Should I pass the MongooseUser class definition as a parameter inside of the constructor ?
Implying that I will have this code inside of the convert method :
let user = new this.MongooseUser({})
Have you got a better idea, to abstract mongoose behaviour in data mapper way ?
I don't want to use another module, it's, in my sense, the most advanced one with NodeJS...
I'm not familiar with the import syntax (nor EMCASCRIPT-6), though you say you're using node.js, so I'd recommend using the proxquire package. The idea is that the package allows you to require an external package, while stubbing the requirements that that package would use. So in your case, you could do something like:
proxyquire('../my/class/that/uses/mongoose', {
mongoose: MyTestMongooseImplementation
})
Which would allow you to use your own mongoose implementation while still using your MongooseUser as you have defined it in your package. Alternatively, you could just override the the MongooseUser class (path relative to the the file whose requirements you are stubbing:
proxyquire('/path/to/UserMongooseRepository', {
'../../auth/mongooseModel/MongooseUser': MyTestMongooseUser
})
Documentation: https://www.npmjs.com/package/proxyquire

How to perform a search on several entities with Symfony 2

I need to perform a search on several entities with the same string then order the results.
I've heard/read a little about FOSElasticaBundle, would this bundle be able to do it? It seems (to me) to have almost to much features for this purpose and I'm not sure it could run on a shared server (hostgator).
The other solution I can think of at the moment is doing the search "manually" (by using join and union) but I'm wondering where should I put such a function: in an existing controller, a new one, a new bundle or somewhere else?
I'm worried as well that this manual solution could come to a cost, especially on some non-indexable fields.
You would do custom entity repositories. Check out the docs. Basically this extends the default FindAll, FindOneBy, etc.
You would have a function like so:
class MyEntityRepository extends Doctrine\ORM\EntityRepository {
public function findByCustomRule(){
//this is mapped to your entity (automatically adds the select)
$queryBuilder = $this->createQueryBuilder('someAlias');
$queryBuilder->orderBy('...');
//this is mapped to any entity
$queryBuilder = $this->getEntityManager()->createQueryBuilder();
$queryBuilder->select('...');
//result
$result = $queryBuilder->getQuery()->getResult();
}
}
This class is defined in the doctrine mapping and lives inside the Entity folder.. Check the docs out and you should get a basic idea.

Dynamic Properties for object instances?

After the previous question "What are the important rules in Object Model Design", now I want to ask this:
Is there any way to have dynamic properties for class instances?
Suppose that we have this schematic object model:
So, each object could have lots of properties due to the set of implemented Interfaces, and then become relatively heavy object. Creating all the possible -and of course reasonable- object can be a way for solving this problem (i.e. Pipe_Designed v.s. Pipe_Designed_NeedInspection), but I have a large number of interfaces by now, that make it difficult.
I wonder if there is a way to have dynamic properties, something like the following dialog to allow the end user to select available functionalities for his/hers new object.
What you want is Properties pattern. Check out long and boring but clever article from Steve Yegge on this
I think maybe you're putting too many roles into the "Road" and "Pipe" classes, because your need for dynamic properties seems to derive from various states/phases of the artifacts in your model. I would consider making an explicit model using associations to different classes instead of putting everything in the "Road" or "Pipe" class using interfaces.
If you mean the number of public properties, use explicit interface implementation.
If you mean fields (and object space for sparse objects): you can always use a property bag for the property implementation.
For a C# example:
string IDesigned.ApprovedBy {
get {return GetValue<string>("ApprovedBy");}
set {SetValue("ApprovedBy", value);}
}
with a dictionary for the values:
readonly Dictionary<string, object> propValues =
new Dictionary<string, object>();
protected T GetValue<T>(string name)
{
object val;
if(!propValues.TryGetValue(name, out val)) return default(T);
return (T)val;
}
protected void SetValue<T>(string name, T value)
{
propValues[name] = value;
}
Note that SetValue would also be a good place for any notifications - for example, INotifyPropertyChanged in .NET to implement the observer pattern. Many other architectures have something similar. You can do the same with object keys (like how EventHandlerList works), but string keys are simpler to understand ;-p
This only then takes as much space as the properties that are actively being used.
A final option is to encapsulate the various facets;
class Foo {
public bool IsDesigned {get {return Design != null;}}
public IDesigned Design {get;set;}
// etc
}
Here Foo doesn't implement any of the interfaces, but provides access to them as properties.

Resources