How to programmatically detach a model from a loopback application? - node.js

I am using loopback without the strongloop framework itself, meaning I have no access to any of the cli tools. I am able to succesfully create and launch a loopback server and define/load some models in this fashion:
var loopback = require('loopback');
var app = loopback();
var dataSource = app.dataSource
(
'db',
{
adapter : 'memory'
});
);
var UserModel = app.loopback.findModel('User');
UserModel.attachTo(dataSource);
app.model(UserModel);
/* ... other models loading / definitions */
// Expose API
app.use('/api', app.loopback.rest());
What I would like to achieve is to be able to detach a model from the loopback application at runtime, so it is not available from the rest API nor the loopback object anymore (without the need to restart the node script).
I know it is possible to remove a model definition made previously from the cli:
Destroy a model in loopback.io, but this is not valid in my case since what it does is to remove the json objects that are loaded at strongloop boot, which is not applicable here.
I would appreciate very much any help regarding this, I have found nothing in the strongloop API documentation.

Disclaimer: I am a core developer of LoopBack.
I am afraid there is no easy way for deleting models at runtime, we are tracking this request in issue #1590.
so it is not available from the rest API nor the loopback object anymore
Let's take a look at the REST API first. In order to remove your model from the REST API, you need to remove it from the list of "shared classes" maintained by strong-remoting and then clean the cached handler middleware.
delete app.remotes()._classes[modelName];
delete app.remotes()._typeRegistry._types[modelName];
delete app._handlers.rest;
When the next request comes in, LoopBack will create a new REST handler middleware and rebuild the routing table.
In essence, you need to undo the work done by this code.
In order to remove the model from LoopBack JavaScript APIs, you need to remove it from the list of models maintained by application's registry:
delete app.models[modelName];
delete app.models[classify(modelName)];
delete app.models[camelize(modelName)];
app.models.models.splice(app.models.indexOf(ModelCtor), 1);
(This is undoing the work done by this code).
Next, you need to remove it from loopback-datasource-juggler registries:
delete app.registry.modelBuilder.models[modelName];
Caveats:
I haven't run/tested this code, it may not work out of the box.
It does not handle the case where the removed model has relations with other models.
It does not notify loopback-component-explorer about the change in the API

Update
There's now a function called deleteModelByName that does exactly that.
https://apidocs.strongloop.com/loopback/#app-deletemodelbyname
https://github.com/strongloop/loopback/pull/3858/commits/0cd380c590be7a89d155e5792365d04f23c55851

Related

Feathers JS nested Routing or creating alternate services

The project I'm working on uses the feathers JS framework server side. Many of the services have hooks (or middleware) that make other calls and attach data before sending back to the client. If I have a new feature that needs to query a database but for a only few specific things I'm thinking I don't want to use the already built out "find" method for this database query as that "find" method has many other unneeded hooks and calls to other databases to get data I do not need for this new query on my feature.
My two solutions so far:
I could use the standard "find" query and just write if statements in all hooks that check for a specific string parameter that can be passed in on client side so these hooks are deactivated on this specific call but that seems tedious especially if I find this need for several other different services that have already been built out.
I initialize a second service below my main service so if my main service is:
app.use('/comments', new JHService(options));
right underneath I write:
app.use('/comments/allParticipants', new JHService(options));
And then attach a whole new set of hooks for that service. Basically it's a whole new service with the only relation to the origin in that the first part of it's name is 'comments' Since I'm new to feathers I'm not sure if that is a performant or optimal solution.
Is there a better solution then those options? or is option 1 or option 2 the most correct way to solve my current issue?
You can always wrap the population hooks into a conditional hook:
const hooks = require('feathers-hooks-common');
app.service('myservice').after({
create: hooks.iff(hook => hook.params.populate !== false, populateEntries)
});
Now population will only run if params.populate is not false.

Do I have to add loopback-component-passport's core models manually?

I installed loopback-component-passport so I can use it with strongloop's Loopback framework. I followed the docs,
but after this command: npm install loopback-component-passport, the following files/models are not created:
UserIdentity model
UserCredential model
ApplicationCredential model
These files are used by Loopback for third-party authentication. Do I have to add them manually? Or am I doing something wrong?
Yes, you have to add them manually. You can refer this example, loopback-example-passport on github.
The reason is the relationships of loopback-component-passport's core models i.e UserIdentity model, UserCredential and ApplicationCredential with Loopback's core model AccessToken and User doesn't come preconfigured which is required for authentication.
Also, you might notice that the developer extended the models but didn't added any model.js. This is so because there was no need to add any runtime logic. For starters, you might want to extend the core models as per the example and create relationship and acls only. Then you can proceed with custom logic.
I think loopback built in models stay tucked away in node_modules, so assuming you mean that these tables are missing from your datastore, you can do an autoupdate in order to get loopback to build any missing tables.
I add the following code to a file in the server/boot directory when I need to during development.
module.exports = function(app, done) {
app.datasources.mysql_db.autoupdate(function(err) {
if (err) throw err;
console.log("autoupdate");
done();
})
}
Where mysql_db is the name of your datastore.
This will update the datasource when the server boot but shouldn't drop existing data (saying that I have seen instances where foreign keys are lost, so care & db backup is still needed).

How to get metadata from MongoDB with Breeze

Currently I have a project using WebAPI and EF with Breeze, it works fine with Metadata stuffs for validation on server but when migrating to NodeJS and MongoDB, I get stuck for trying get Metadata from MongoDB. I checked out zza BMEAN app but I just saw on this project:
app.get('/breeze/Breeze/Metadata', getMetadata);
function getMetadata(req, res, next) {
next({
statusCode: 404,
message: "No metadata from the server; metadata is defined on the client"
});
}
I also read all document about Breeze/MongoDB but still doesn't help me to get Metadata for this.
The main point is I just want to change backend with BMEAN instead of WebAPI+EF+Breeze, don't need to change code on client.
Thanks
The metadata is provided by EF, not by MongoDB. If you are using a CodeFirst approach with EF then you should already have a DBContext.
This talks about how to use the DBContext -
http://www.breezejs.com/documentation/entity-framework-dbcontext
This talks about how to use EF as a design tool to build your meta data from classes -
http://www.breezejs.com/documentation/ef-design-tool
Odds are you already have what you need to generate the metadata it is just extending that and exposing a service to provide it to the client.
PW Kad's answer is correct, but to clarify, there is no way to get metadata from a MongoDB database because the database itself has an indeterminate structure. So you have to tell your client what the structure is. If you want to use the same client code for EF and Mongo then saving the metadata provided by the EFContext in your Mongo project makes a lot of sense. In other cases simply define the metadata directly on the client via Breeze's metadata api calls.

Architecting CouchDB with nodejs

Does anyone have any experience with CouchDB where a real DAL was utilized? CouchDB is not like any other datastore out there, esp. due to its notion of views which add an interesting dynamic to data - business logic separation... not to mention revision controlling the application source code.
Side Note: Libraries like Nano are not a DAL. They are akin to a database driver. Using Nano directly from business logic would tie the application to CouchDB. Not what I want. Instead my custom made DAL uses Nano as a driver, but separates the business logic from Nano completely.
Question: any best practices or documents I should read? Any existing DALs that can switch between MongoDB & CouchDB for common things (to act as a starting point for what I am trying to do)?
You may want to check out resourceful https://github.com/flatiron/resourceful it has support for several data adapters, including mongodb and couchdb
Here is a simple use case:
var resourceful = require('resourceful');
var Creature = resourceful.define('creature', function () {
//
// Specify a storage engine
//
this.use('couchdb');
//
// Specify some properties with validation
//
this.string('diet');
this.bool('vertebrate');
this.array('belly');
//
// Specify timestamp properties
//
this.timestamps();
});
//
// Now that the `Creature` prototype is defined
// we can add custom logic to be available on all instances
//
Creature.prototype.feed = function (food) {
this.belly.push(food);
};

CRUD blueprint overriding in sails.js

According to this closed issue in sails:
https://github.com/balderdashy/sails/issues/835
CRUD Blueprint Overrides
"absolutely, this is coming in v0.10"
I'd like to modify the blueprints in my sailsjs service to allow named roots (consuming in ember).
Currently I'm having to customize every controller I create with actions that are largely duplicates of what is already in the blueprints.
I suspect that I can move this code out of my controllers now and into a blueprints override area, but I'm not clear on where to put that code.
Any examples or even just a pointer to the relevant code in sails the .10 repo would be greatly appreciated.
Update
In order to override blueprints in Sails 1.0 in the manner described below, you must first install the "custom blueprints" plugin for your project (npm install sails-hook-custom-blueprints).
To override blueprints in Sails v0.10, you create an api/blueprints folder and add your blueprint files (e.g. find.js, create.js, etc.) within. You can take a look at the code for the default actions in the Sails blueprints hook for a head start.
Adding custom blueprints is also supported, but they currently do not get bound to routes automatically. If you create a /blueprints/foo.js file, you can bind a route to it in your /config/routes.js file with (for example):
'GET /myRoute': {blueprint: 'foo'}
you can add actions with these names inside your controller to override default behaviour
to change destroy behavior
module.exports = {
destroy: function(req,res){
Goal.update({ id: req.param('id') }, { deleted: true })
.exec(function (err, goal) {
if (err) return res.json(err, 400);
return res.json(goal[0]);
});
}
}
It is possible to use the build in blueprints, but with policies running first. These policies might verify that the user is logged in, has the correct access, or similar. Really handy!
On each model, you have available callbacks both before and after data has been stored. Dig in: http://sailsjs.com/documentation/concepts/models-and-orm/lifecycle-callbacks
There is no default callback available for blueprints result. But don't give up. It is still possible to use the build in blueprints, and only modify the output. It might not be the most elegant solution, but it works well. Check out my “hack” here: Sails blueprints lifecycle

Resources