Repository navigation
Description
Isomorphic AngularJS SDK for LoopBack
Isomorphic AngularJS SDK provides AngularJS wrapper for browserified LoopBack
models.
1. Promisify callback-based methods
Edit 2014-09-30 It may be better to promisify loopback and loopback-datasource-juggler, so that the promise-based API is available both at the client and the server. See loopbackio/loopback-datasource-juggler#177
AngularJS uses promises instead of callbacks in most places. The first change needed to make LoopBack more AngularJS-like is to convert all callback-based async functions to return promises.
Naive implementation: walk through all model objects and wrap/replace all static and instance (prototype) methods with promisified versions.
obj[key + 'Async'] = function() {
var deferred = $q.defer();
var callback = function(err) {
if (err) return deferred.reject(err);
var results = Array.prototype.slice.call(arguments, 1);
if (results.length == 1) results = results[0];
deferred.resolve(results);
});
var args = Array.prototype.slice.call(arguments);
args.push(callback);
obj[key].apply(this, args);
return deferred.promise;
}The implementation should be optimized a bit, see bluebird/promisify for inspiration.
Caveat 1
Not all methods are asynchronous (callback-based). Sync methods must not be promisified. I am proposing to implement the following solutions:
- A naming convention similar to Node.js core API.
Methods called*Syncare consider synchronous. - When a function has the property
isSync: true, the method is considered
synchronous. This way the server API can stay without changes but still
provide fine-grained control over which functions are promisified
in the Angular client.
Caveat 2
We have to preserve callback-based methods since they may be
used by other isomorphic functions, e.g.
User.prototype.login = function() {
var query = // setup query
this.findOne({where: query}, function(err, user) {
// etc.
});Solutions:
- Add
Asyncpostfix to all promisified functions in the same way
as Bluebird does. - Create proxy objects exposing promisified functions using the same names.
These proxy objects will be registered for dependency injection.
Since the isomorphic code calls methods on the original object,
there won't be any clashes.
2. API design
Angular's native ngResource module uses the following convention: model methods
(resource actions) return an object (or array) that is later populated with
data from the response.
The object (array) has also some extra properties like $promise and
$resolved. The method itself has the following signature:
HTTP GET "class" actions:
Resource.action([parameters], [success], [error])non-GET "class" actions:
Resource.action([parameters], postData, [success], [error])non-GET instance actions:
instance.$action([parameters], [success], [error])
Restangular comes with an alternative design called enhanced promises.
The model method returns a promise object with few extra properties and methods:
call(methodName, params*): This will return a new promise of the previous
value, after calling the method called methodName with the parameters params.
get(fieldName): This will return a new promise for the type of the field. The
param of this new promise is the property fieldName from the original promise
result.push(object): This method will only be in the promises of arrays. It's a subset
of the call method that does a push.$object: This returns the reference to the object that will be filled once the
server responds a value. This means that if you call getList this will be an
empty array by default. Once the array is returned from the server, this same
$objectproperty will get filled with results from the server.
See Restangular README for more details and code examples
(link)
I am proposing to base the API design on restangular's enhanced promises:
- They make it easier to compose async operations, since the return value
is a promise and there are helper functions likecallandget
pushing this even further. - At the same time, it's easy to add the future result to the scope via
$object, which is similar to what users of ngResource are accustomed to. - There are less moving parts to worry about: instead of ngResource's
successCallback, errorCallback, $promise and $resolve, there is only
the enhanced promise and $object property.
3. Dependency Injection
AngularJS applications use dependency injection instead of require
for loading components.
Consider this early implementation of a Todo controller, mixing Angular
injection and require:
var Todo = require('models/todo');
function TodoCtrl($scope, $routeParams, $filter) {
Todo.find(// etc.
}To make the code idiomatic, the "require" part should be moved to
a factory and the controller should get the Todo model via dependency
injection.
function TodoCtrl($scope, $routeParams, $filter, Todo) {
Todo.find(// etc.
}
// in the app setup
module.factory('Todo', function() {
return require('models/todo');
// or perhaps
// return client.models.todo;
});The setup part can be provided by LoopBack AngularJS SDK. Below is a sample
code demonstrating the proposed API:
var lbng = require('loopback-angular');
var loopback = require('loopback');
var client = loopback();
// setup models and connectors
app.model(require('models/todo'));
// 1. Ask lbng to define a new angular module called 'lbModels'
lbng.module('lbModels')
// 2. Define services for all loopback models
.allModelsFrom(client.models)
// 3. Optionally define a service
// wrapping (promisifying) any object
.service('Util', require('shared/util'));4. Client API documentation
This seems like the most difficult part. How to document the API provided by
AngularJS models to make it easy for front-end developers to discover what
methods are available, what are their signatures and how they should be used?
The 1.x series of loopback-angular set the expectation pretty high by providing
auto-generated ngdoc comments and grunt & cli tools to rended these
comments as HTML API docs viewable in the browser.
The isomorphic version of the SDK should preserve this goodness.
Things to consider:
- discovering what to document
- API differences
- jsdoc comments
Discovering what to document
LoopBack uses the concept of mixins, where e.g. DAO methods are injected
to models at runtime. To include mixed-in methods in the generated API docs,
the generator cannot rely on a static analysis of the code, it has to
execute the application setup.
Solution A
Keep the loopback-related application setup isolated from angular code.
The API docs generator can load the application setup in Node.js, since
the code is isomorphic and does not depend on AngularJS.
The documentation is generated only for models registered with the client
loopback app.
Solution B
Generate docs for all services registered via lbng.module. This requires
to run the client app setup in a browser (e.g. phantomjs).
The ngdoc file can be created from within the phantomjs environment
using the filesystem API
(docs).
API differences
The promisified angularized API is slightly different from the server-side
API. That makes it even more important to provide an accurate API reference
for front-end developers.
From the SDK perspective, it means the ngdoc generator has to know what changes
are being applied to the isomorphic functions by the SDK and apply similar
transformations when generating ngdoc comments.
JSDoc comments
As a developer writing isomorphic function, I would prefer
to use jsdoc comments to describe the methods, not remoting metadata like
fn.description.
On the other hand, DAO functions mixed in by
loopback-datasource-juggler generally don't have jsdoc comments and provide
fn.description instead. That means we can't rely on jsdoc comments only.
Since the ngdoc generator is walking through models loaded in the js engine,
it cannot access jsdoc comments in the source code.
The solution is to write a transform plugin for browserify that
parses the source code and emits code storing jsdoc comments
as a new (function) property
(proof of concept):
// original file
/**
* Hello world.
* @param cb Lorem ipsum.
*/
function foobar(cb) {
// line comment
return 'foobar';
}
// transformed result
/**
* Hello world.
* @param cb Lorem ipsum.
*/
function foobar(cb) {
// line comment
return 'foobar';
}
foobar.jsdoc = "\nHello world.\n@param cb Lorem ipsum.\n "To keep the size of the production code small, the transformation should be
applied only when generating a bundle for the purpose of API docs generator.
Activity
bajtos commentedon Jun 7, 2017
This is no longer relevant, the discussion continues in #133.