Loopback - Easiest way to extend a built-in model
Asked Answered
S

1

6

I've been using Loopback to create an API. The documentation is generally really good but doesn't really answer my question about the following: how do I extend (not replace) a built in model?

The most promising piece of information came from this page - it specifies the way of basing a class from another class, via inheritance. This is useful but not ideal - I'd like to create relationships to custom models from the stock models, for example - "Role" should have many "Permission".

The page I mention also shows a Javascript file, located at common/models/<modelName>.js, where it states you can "extend" a model based on the properties and options you give it. The server never seems to hit the file... For example - I put a file in common/models/role.js with the following content:

var properties = {
  exampleProperty: {type: String, required: true}
};


var user = loopback.Model.extend('Role', properties);
console.log('test');

First off, it doesn't seem to hit the file at all (no console.log output given). Second, obviously because of the first point, it doesn't extend the model with the properties I created.

Am I missing something obvious or is the documentation just plain wrong?

Skulk answered 8/4, 2015 at 12:3 Comment(2)
same problem here. docs seem rather incomplete when explaining how to extend builtin models - they seem to suggest u can extend, but like u, i found that using for example, user.json/.js isn't an option. did u try inheritance as suggested here? i'm concerned it will break access tokens or generally cause more problems.Kerin
Hi there, yes inheritance is the way to go. If you extend the base User class you will receive the same methods and somehow it figures out the accessToken stuff for you too.Skulk
E
5

You should generate a new model via slc loopback:model named user. By default, the built in user is named User, which is why you can use lowercase user or even UserModel if you prefer. Then when you are prompted by the model generator for a base model, choose User. See https://github.com/strongloop/loopback-faq-user-management/blob/master/common/models/user.json#L3

Expedient answered 8/4, 2015 at 15:48 Comment(2)
Thanks, I guess the documentation is a bit misleading. I wanted to add new properties and relations to the original models, but I guess this isn't the best way.Skulk
Yes, extending the built-in model and then adding your properties and relations is definitely the way to go.Expedient

© 2022 - 2024 — McMap. All rights reserved.