Skip to content
Closed
3 changes: 2 additions & 1 deletion bower.json
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
"angular-resource": "~1.2.10",
"angular-mocks": "~1.2.10",
"requirejs": "~2.1.10",
"chai": "~1.8.1"
"chai": "~1.8.1",
"lodash": "~2.4.1"
}
}
2 changes: 1 addition & 1 deletion karma.conf.js
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ module.exports = function(config) {

// list of files to exclude
exclude: [
// 'test/**/*.js'
'test.e2e/spec/fixtures/**/*.js'
],


Expand Down
83 changes: 80 additions & 3 deletions lib/services.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
var fs = require('fs');
var path = require('path');
var ejs = require('ejs');

ejs.filters.q = function(obj) {
Expand All @@ -12,24 +13,30 @@ ejs.filters.q = function(obj) {
* var generateServices = require('loopback-sdk-angular').services;
* var app = require('./server/server');
*
* var client = generateServices(app, 'lbServices', '/api');
* var client = generateServices(app, 'lbServices', '/api', clientModelConfig);
* require('fs').writeFileSync('client/loopback.js', client, 'utf-8');
* ```
*
* @param {Object} app The loopback application created via `app = loopback()`.
* @param {string=} ngModuleName A name for the generated Angular module.
* Default: `lbServices`.
* @param {string=} apiUrl The URL where the client can access the LoopBack
* server app. Default: `/`.
* server app. Default: `/`.*
* @param {Object} clientModelConfig Optional - The client model config that
* will determine what/how the services are generated. By default, (without
* providing any, all models wil be generated without options.
* @returns {string} The generated javascript code.
* @header generateServices
*/
module.exports = function generateServices(app, ngModuleName, apiUrl) {
module.exports = function generateServices(app, ngModuleName,
apiUrl, clientModelConfig) {
ngModuleName = ngModuleName || 'lbServices';
apiUrl = apiUrl || '/';

var models = describeModels(app);

if (!!clientModelConfig) applyClientModelConfig(models, clientModelConfig);

var servicesTemplate = fs.readFileSync(
require.resolve('./services.template.ejs'),
{ encoding: 'utf-8' }
Expand Down Expand Up @@ -175,3 +182,73 @@ function findModelByName(models, name) {
return models[n];
}
}

// Apply client model config, usually from client/model-config.json
function applyClientModelConfig(models, clientModelConfig) {
var modelConfig;

try {
// Do not use require() below : require caches value, and if it is modified
// next call will use this modified data. Unless object is deep cloned,
// which is an alternative as reading file each time.
var configFile = fs.readFileSync(clientModelConfig, {encoding: 'utf-8'});
modelConfig = JSON.parse(configFile);
} catch(err) {
console.error('FATAL: Provided client config file could not be loaded : ' +
clientModelConfig, err);
process.exit(1);
}

// Default location in loopback workspace, relative to /client/model-config.js
var sources = [
'../common/models',
'./models'
];
if (!!modelConfig._meta && Array.isArray(modelConfig._meta.sources)) {
sources = modelConfig._meta.sources;
delete modelConfig._meta;
}
sources = sources.map(function(source) {
return path.join(path.dirname(clientModelConfig), source);
});

var n;
// Discard models not present in config
for (n in models) {
if (!(n in modelConfig)) {
console.log('Info: Model ' + n + ' was not defined in client config, ' +
'it will not be included in generated services file');
delete models[n];
}
}

for (n in modelConfig) {
if (n in models) {
models[n].isRemote = true;
} else {
if (modelConfig[n].dataSource == 'remote') {
console.log('Warning: Model ' + n + ' is expected to be REST exposed ' +
' but is not found in app, so it will not be included ' +
' in generated services file');
delete modelConfig[n];
continue;
} else {
models[n] = {isRemote: false};
}
}

var meta = models[n];
meta.extensions = [];
meta.dependencies = modelConfig[n].dependencies || [];
// Supported file syntax for model ModelName : model-name.js
var fsModelName = n.replace(/([a-z])([A-Z])/g, '$1-$2').toLowerCase();

// Add this model extension functions to models description
// in `extensions` array property
for (var idx = 0; idx < sources.length; idx++) {
var file = path.resolve(path.join(sources[idx], fsModelName + '.js'));
if (fs.existsSync(file))
meta.extensions.push(require(file));
}
}
}
76 changes: 71 additions & 5 deletions lib/services.template.ejs
Original file line number Diff line number Diff line change
Expand Up @@ -15,11 +15,32 @@ var authHeader = 'authorization';
*/
var module = angular.module(<%-: moduleName | q %>, ['ngResource']);

<% for (var modelName in models) {
<%
/*
* Returns an angular dependency-injection function opening block
*
* Example declareNgDeps(['$q', 'myDep'], false) :
* Returns : "['$q', 'myDep', function($q, myDep) {"
*
* Example declareNgDeps(['$q'], true) :
* Returns : "['$q', 'LoopBackResource', 'LoopBackAuth', '$injector',
function($q, LoopBackResource, LoopBackAuth, $injector) {"
*/
function declareNgDeps(deps, isRemote) {
deps = deps || [];
if (isRemote) {
deps = deps.concat(['LoopBackResource', 'LoopBackAuth', '$injector']);
}
return '[' + deps.map(JSON.stringify).join(',') + (deps.length? ',' : '') +
'function(' + deps.join(',') + ') {';
}

for (var modelName in models) {
var meta = models[modelName];
if (typeof meta.isRemote === 'undefined' || meta.isRemote) {

// capitalize the model name
modelName = modelName[0].toUpperCase() + modelName.slice(1);
// capitalize the model name
modelName = modelName[0].toUpperCase() + modelName.slice(1);
-%>
/**
* @ngdoc object
Expand All @@ -44,8 +65,9 @@ var module = angular.module(<%-: moduleName | q %>, ['ngResource']);
*/
module.factory(
<%-: modelName | q %>,
['LoopBackResource', 'LoopBackAuth', '$injector', function(Resource, LoopBackAuth, $injector) {
var R = Resource(
<%-: declareNgDeps(meta.dependencies, true) %>

var R = LoopBackResource(
urlBase + <%-: meta.ctor.getFullPath() | q %>,
<% /*
Constructor arguments are hardcoded for now.
Expand Down Expand Up @@ -245,6 +267,50 @@ module.factory(
<% }); // forEach methods name -%>
<% } // for each scope -%>

<% } else { // if meta.isRemote -%>

/**
* @ngdoc object
* @name <%-: moduleName %>.<%-: modelName %>
* @object
*
* @description
*
* An object for interacting with the local `<%-: modelName %>` model.
*
*/
module.factory(<%-: modelName | q %>,
<%-: declareNgDeps(meta.dependencies, false) %>

// Simple object constructor that can be called
// with object properties as optional parameter
var R = function(opts) {
if (typeof opts === 'object') for (var prop in opts) {
if (opts.hasOwnProperty(prop)) {
this[prop] = opts[prop];
}
}
};

<% } // if meta.isRemote -%>

<% // Get available model extentions for this model and apply on resource object
(meta.extensions || []).forEach(function(extension) { -%>

(<%-: extension %>)(R);

<% }); // forEach model extension -%>

/**
* @ngdoc property
* @name <%- moduleName %>.<%- modelName %>#modelName
* @propertyOf <%- moduleName %>.<%- modelName %>
* @description
* The name of the model represented by this $resource,
* i.e. `<%- modelName %>`.
*/
R.modelName = <%-: modelName | q %>;

return R;
}]);

Expand Down
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@
"karma-mocha-reporter": "^0.2.6",
"karma-phantomjs-launcher": "^0.1.2",
"karma-requirejs": "^0.2.1",
"lodash": "^2.4.1",
"loopback": "^2.0",
"loopback-datasource-juggler": "^2.0",
"mocha": "~1.18.0",
Expand Down
3 changes: 2 additions & 1 deletion test.e2e/given.js
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,8 @@ define(['angular', 'angularMocks', 'angularResource'], function(angular) {
.then(injectScriptAtUrl)
.then(function() {
return function createTestInjector() {
var injector = angular.injector(['ng', 'ngMockE2E', options.name]);
var injector = angular.injector(['ng', 'ngMockE2E',
'lodash', options.name]);
// Setup the mocked http provider to pass all $http requests
// to our LoopBack server
var $httpBackend = injector.get('$httpBackend');
Expand Down
36 changes: 36 additions & 0 deletions test.e2e/spec/fixtures/model-config.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
{
"_meta": {
"sources": [
"./models"
]
},
"MyModel": {
"dataSource": "remote",
"dependencies": ["_"]
},
"lower-case-not-an-identifier": {
"dataSource": "remote"
},
"Customer": {
"dataSource": "remote"
},
"User": {
"dataSource": "remote"
},
"Product": {
"dataSource": "remote"
},
"Category": {
"dataSource": "remote"
},
"Town": {
"dataSource": "remote"
},
"Country": {
"dataSource": "remote"
},
"Address": {
"dataSource": null,
"dependencies": ["_"]
}
}
49 changes: 49 additions & 0 deletions test.e2e/spec/fixtures/models/address.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
// Dependencies
// Note:
// * The below values are relevant for server-side
// * For client-side, dependencies must be declared in model-config.json file
// * And they have to be available as an Angular provider in your app
var _ = require('lodash');
// Description: Extend `Address` model in Angular client generated service
// with static and prototype methods/properties
//
// Notes:
// * Docular comments will be included in Service doc as long as
// they moduleName and modelName are correct
// * Model must be declared in client-model.json to be generated/extended
module.exports = function (Address) {

/**
* @ngdoc property
* @name lbServices.Address#contryCodes
* @propertyOf lbServices.Address
*
* @description
*
* Transform ISO contry code to readable string
*
*/
Address.countryCodes = {
'us': 'United States',
'fr': 'France'
};

/**
* @ngdoc method
* @name lbServices.Address#getFullAddress
* @methodOf lbServices.Address
*
* @description
*
* Instance method returning complete address
*
* @return {String} Complete address
*/
Address.prototype.getFullAddress = function () {
// Just to test dependency on lodash :
_.noop();
return this.recipient + ' ' + Address.countryCodes[this.country];
};

return Address;
};
Loading