From 30bbfbf34e4d717b7b71f4b853639ae38bf38205 Mon Sep 17 00:00:00 2001 From: jeff-clegg Date: Fri, 1 Apr 2016 18:19:58 -0400 Subject: [PATCH 1/2] Update dependency and test command for PhantomJS --- package.json | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/package.json b/package.json index e9bc64b..291e43d 100644 --- a/package.json +++ b/package.json @@ -6,7 +6,7 @@ "scripts": { "prepublish": "node ./apidocs/describe-builtin-models.js", "pretest": "jshint .", - "test": "node ./test.e2e/test-server.js node node_modules/karma/bin/karma start --single-run --browsers PhantomJS" + "test": "node ./test.e2e/test-server.js node node_modules/karma/bin/karma start --single-run --browsers PhantomJS2" }, "repository": { "type": "git", @@ -42,7 +42,7 @@ "karma-junit-reporter": "^0.3.8", "karma-mocha": "^0.2.1", "karma-mocha-reporter": "^1.1.5", - "karma-phantomjs-launcher": "^0.2.3", + "karma-phantomjs2-launcher": "^0.5.0", "karma-requirejs": "^0.2.1", "loopback": "^2.0", "loopback-datasource-juggler": "^2.0", From 0ddf5402d021d3742c560d74002e716a8d3c7182 Mon Sep 17 00:00:00 2001 From: Jeff Clegg Date: Fri, 15 Jul 2016 22:37:46 -0700 Subject: [PATCH 2/2] rebase phantomjs upgrade --- .eslintrc | 3 + .jshintignore | 5 - .jshintrc | 24 -- CHANGES.md | 20 ++ CONTRIBUTING.md | 4 +- LICENSE | 25 ++ LICENSE.md | 9 - apidocs/.eslintrc | 6 + apidocs/describe-builtin-models.js | 8 +- index.js | 4 + karma.conf.js | 11 +- lib/services.js | 102 ++++++-- lib/services.template.ejs | 369 ++++++++++++++++------------- package.json | 13 +- parse-helper.js | 5 + test.e2e/given.js | 5 + test.e2e/spec/services.spec.js | 352 +++++++++++++++++---------- test.e2e/test-main.js | 15 +- test.e2e/test-server.js | 27 ++- test.e2e/util.js | 7 +- 20 files changed, 641 insertions(+), 373 deletions(-) create mode 100644 .eslintrc delete mode 100644 .jshintignore delete mode 100644 .jshintrc create mode 100644 LICENSE delete mode 100644 LICENSE.md create mode 100644 apidocs/.eslintrc diff --git a/.eslintrc b/.eslintrc new file mode 100644 index 0000000..a6e5297 --- /dev/null +++ b/.eslintrc @@ -0,0 +1,3 @@ +{ + "extends": "loopback" +} \ No newline at end of file diff --git a/.jshintignore b/.jshintignore deleted file mode 100644 index 3f12ace..0000000 --- a/.jshintignore +++ /dev/null @@ -1,5 +0,0 @@ -bower_components/ -node_modules/ -coverage/ -karma.conf.js -apidocs/loopback-core.js diff --git a/.jshintrc b/.jshintrc deleted file mode 100644 index 77a36c8..0000000 --- a/.jshintrc +++ /dev/null @@ -1,24 +0,0 @@ -{ -"node": true, -"browser": true, -"camelcase" : true, -"eqnull" : true, -"indent": 2, -"undef": true, -"quotmark": "single", -"maxlen": 80, -"trailing": true, -"newcap": true, -"nonew": true, -"sub": true, -"globals": { - "describe": true, - "it": true, - "before": true, - "beforeEach": true, - "after": true, - "afterEach": true, - "define": true, - "expect": true -} -} diff --git a/CHANGES.md b/CHANGES.md index 708d983..cfddf92 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -1,3 +1,23 @@ +2016-07-13, Version 1.8.0 +========================= + + * Expose configured properties on LoopBackResource (Matteo Padovano) + + * Describe model schema in generated $resource (Miroslav Bajtos) + + * update copyright notices and license (Ryan Graham) + + * Clear user data when logout returns error response (Matteo Padovano) + + * Lint generated code (David Cheung) + + * Use ESlint in replace of jshint (David Cheung) + + * added test for LoopBackResourceProvider.getAuthHeader() method. (Martin Juhasz) + + * Added getter for AuthHeader value in LoopBackResource (Martin Juhasz) + + 2016-02-24, Version 1.7.0 ========================= diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index af14d6e..8ad9359 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -147,5 +147,5 @@ Contributing to `loopback-sdk-angular` is easy. In a few simple steps: inaccurate in any respect. Email us at callback@strongloop.com. ``` -[Google C++ Style Guide]: https://google-styleguide.googlecode.com/svn/trunk/cppguide.xml -[Google Javascript Style Guide]: https://google-styleguide.googlecode.com/svn/trunk/javascriptguide.xml +[Google C++ Style Guide]: https://google.github.io/styleguide/cppguide.html +[Google Javascript Style Guide]: https://google.github.io/styleguide/javascriptguide.xml diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..47a5d46 --- /dev/null +++ b/LICENSE @@ -0,0 +1,25 @@ +Copyright (c) IBM Corp. 2014,2015. All Rights Reserved. +Node module: loopback-sdk-angular +This project is licensed under the MIT License, full text below. + +-------- + +MIT license + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/LICENSE.md b/LICENSE.md deleted file mode 100644 index 3702054..0000000 --- a/LICENSE.md +++ /dev/null @@ -1,9 +0,0 @@ -Copyright (c) 2013-2015 StrongLoop, Inc. - -loopback-sdk-angular uses a dual license model. - -You may use this library under the terms of the [MIT License][], -or under the terms of the [StrongLoop Subscription Agreement][]. - -[MIT License]: http://opensource.org/licenses/MIT -[StrongLoop Subscription Agreement]: http://strongloop.com/license diff --git a/apidocs/.eslintrc b/apidocs/.eslintrc new file mode 100644 index 0000000..04e9789 --- /dev/null +++ b/apidocs/.eslintrc @@ -0,0 +1,6 @@ +{ + "extends": "../.eslintrc", + "rules": { + "quotes": ["off"] + } +} \ No newline at end of file diff --git a/apidocs/describe-builtin-models.js b/apidocs/describe-builtin-models.js index accf462..1b17115 100644 --- a/apidocs/describe-builtin-models.js +++ b/apidocs/describe-builtin-models.js @@ -1,3 +1,9 @@ +// Copyright IBM Corp. 2014,2016. All Rights Reserved. +// Node module: loopback-sdk-angular +// This file is licensed under the MIT License. +// License text available at https://opensource.org/licenses/MIT + +/* eslint quotes: ["error", "single"] */ var fs = require('fs'); var path = require('path'); @@ -6,7 +12,7 @@ var loopbackCoreJs = path.resolve(__dirname, 'loopback-core.js'); try { var generator = require('..'); var loopback = require('loopback'); -} catch(err) { +} catch (err) { if (err.code === 'MODULE_NOT_FOUND' && fs.existsSync(loopbackCoreJs)) { console.log('Cannot load the generator, node_modules were not installed.'); console.log('Ignoring the error since the output file is already there.'); diff --git a/index.js b/index.js index 11eb64d..4bd8ba2 100644 --- a/index.js +++ b/index.js @@ -1,2 +1,6 @@ +// Copyright IBM Corp. 2014,2015. All Rights Reserved. +// Node module: loopback-sdk-angular +// This file is licensed under the MIT License. +// License text available at https://opensource.org/licenses/MIT exports.services = require('./lib/services'); diff --git a/karma.conf.js b/karma.conf.js index 96e7770..129f6bc 100644 --- a/karma.conf.js +++ b/karma.conf.js @@ -1,3 +1,8 @@ +// Copyright IBM Corp. 2014,2016. All Rights Reserved. +// Node module: loopback-sdk-angular +// This file is licensed under the MIT License. +// License text available at https://opensource.org/licenses/MIT + // Karma configuration // Generated on Fri Jan 17 2014 19:17:51 GMT+0100 (CET) @@ -20,7 +25,7 @@ module.exports = function(config) { { pattern: 'test.e2e/**/*.js', included: false }, // Include lib/ files to let Karma watch for changes there - { pattern: 'lib/**/*.js', included: false } + { pattern: 'lib/**/*.js', included: false }, ], // list of files to exclude @@ -35,7 +40,7 @@ module.exports = function(config) { // CI friendly test output junitReporter: { - outputFile: 'karma-xunit.xml' + outputFile: 'karma-xunit.xml', }, @@ -73,6 +78,6 @@ module.exports = function(config) { // Continuous Integration mode // if true, it capture browsers, run tests and exit - singleRun: false + singleRun: false, }); }; diff --git a/lib/services.js b/lib/services.js index 1b71d39..2c36624 100644 --- a/lib/services.js +++ b/lib/services.js @@ -1,8 +1,14 @@ +// Copyright IBM Corp. 2014,2016. All Rights Reserved. +// Node module: loopback-sdk-angular +// This file is licensed under the MIT License. +// License text available at https://opensource.org/licenses/MIT + var fs = require('fs'); var ejs = require('ejs'); +var extend = require('util')._extend; ejs.filters.q = function(obj) { - return JSON.stringify(obj, null, 2 ); + return JSON.stringify(obj, null, 2); }; /** @@ -12,23 +18,45 @@ 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, { + * ngModuleName: 'lbServices', + * apiUrl: '/api' + * }); * require('fs').writeFileSync('client/loopback.js', client, 'utf-8'); * ``` * + * To preserve backwards compatibility, the three-arg variant is still + * supported: + * + * ```js + * var client = generateServices(app, 'lbServices', '/api'); + * ``` + * * @param {Object} app The loopback application created via `app = loopback()`. + * @options {Object} options * @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: `/`. + * @param {Boolean} includeSchema Include model definition. * @returns {string} The generated javascript code. * @header generateServices */ -module.exports = function generateServices(app, ngModuleName, apiUrl) { - ngModuleName = ngModuleName || 'lbServices'; - apiUrl = apiUrl || '/'; +module.exports = function generateServices(app, options) { + if (typeof options === 'string') { + // legacy API: generateServices(app, ngModuleName, apiUrl) + options = { + ngModuleName: arguments[1], + apiUrl: arguments[2], + }; + } - var models = describeModels(app); + options = extend({ + ngModuleName: 'lbServices', + apiUrl: '/', + }, options); + + var models = describeModels(app, options); var servicesTemplate = fs.readFileSync( require.resolve('./services.template.ejs'), @@ -36,13 +64,13 @@ module.exports = function generateServices(app, ngModuleName, apiUrl) { ); return ejs.render(servicesTemplate, { - moduleName: ngModuleName, + moduleName: options.ngModuleName, models: models, - urlBase: apiUrl.replace(/\/+$/, '') + urlBase: options.apiUrl.replace(/\/+$/, ''), }); }; -function describeModels(app) { +function describeModels(app, options) { var result = {}; app.handler('rest').adapter.getClasses().forEach(function(c) { var name = c.name; @@ -60,25 +88,25 @@ function describeModels(app) { // the sharedCtor parameters should be added to the parameters // of prototype methods. c.methods.forEach(function fixArgsOfPrototypeMethods(method, key) { - if (method.name=='create') { + if (method.name == 'create') { var createMany = Object.create(method); - createMany.name = 'createMany'; - createMany.isReturningArray = function() { return true; }; - c.methods.splice(key+1, 0, createMany); + createMany.name = 'createMany'; + createMany.isReturningArray = function() { return true; }; + c.methods.splice(key + 1, 0, createMany); } var ctor = method.restClass.ctor; if (!ctor || method.sharedMethod.isStatic) return; method.accepts = ctor.accepts.concat(method.accepts); - if(!method.accepts) return; + if (!method.accepts) return; // Any extra http action arguments in the path need to be added to the // angular resource actions as params method.accepts.forEach(function findResourceParams(arg) { - if(!arg.http) return; + if (!arg.http) return; - if(arg.http.source === 'path' && arg.arg !== 'id') { - if(!method.resourceParams) { + if (arg.http.source === 'path' && arg.arg !== 'id') { + if (!method.resourceParams) { method.resourceParams = []; method.hasResourceParams = true; } @@ -94,6 +122,10 @@ function describeModels(app) { buildScopes(result); + if (options.includeSchema) { + buildSchemas(result, app); + } + return result; } @@ -152,7 +184,7 @@ function buildScopeMethod(models, modelName, method) { modelClass.scopes[scopeName] = { methods: {}, - targetClass: targetClass + targetClass: targetClass, }; } else if (modelClass.scopes[scopeName] === null) { // Skip the scope, the warning was already reported @@ -184,18 +216,18 @@ function buildScopeMethod(models, modelName, method) { var reverseModel = findModelByName(models, targetClass); reverseModel.methods.push(reverseMethod); - if(reverseMethod.name.match(/create/)){ + if (reverseMethod.name.match(/create/)) { var createMany = Object.create(reverseMethod); - createMany.name = createMany.name.replace( + createMany.name = createMany.name.replace( /create/, 'createMany' ); - createMany.internal = createMany.internal.replace( + createMany.internal = createMany.internal.replace( /create/, 'createMany' ); - createMany.isReturningArray = function() { return true; }; - reverseModel.methods.push(createMany); + createMany.isReturningArray = function() { return true; }; + reverseModel.methods.push(createMany); } var scopeMethod = Object.create(method); @@ -204,7 +236,7 @@ function buildScopeMethod(models, modelName, method) { scopeMethod.deprecated = false; scopeMethod.internal = false; modelClass.scopes[scopeName].methods[apiName] = scopeMethod; - if(scopeMethod.name.match(/create/)){ + if (scopeMethod.name.match(/create/)) { var scopeCreateMany = Object.create(scopeMethod); scopeCreateMany.name = scopeCreateMany.name.replace( /create/, @@ -222,3 +254,25 @@ function findModelByName(models, name) { return models[n]; } } + +function buildSchemas(models, app) { + for (var modelName in models) { + var modelProperties = app.models[modelName].definition.properties; + var schema = {}; + for (var prop in modelProperties) { // eslint-disable-line one-var + schema[prop] = extend({}, modelProperties[prop]); + // normalize types - convert from ctor (function) to name (string) + var type = schema[prop].type; + if (typeof type === 'function') { + type = type.modelName || type.name; + } + // TODO - handle array types + schema[prop].type = type; + } + + models[modelName].modelSchema = { + name: modelName, + properties: schema, + }; + } +} diff --git a/lib/services.template.ejs b/lib/services.template.ejs index 2c9ac2b..9a0ca31 100644 --- a/lib/services.template.ejs +++ b/lib/services.template.ejs @@ -1,5 +1,6 @@ // CommonJS package manager support -if (typeof module !== 'undefined' && typeof exports !== 'undefined' && module.exports === exports) { +if (typeof module !== 'undefined' && typeof exports !== 'undefined' && + module.exports === exports) { // Export the *name* of this Angular module // Sample usage: // @@ -9,17 +10,18 @@ if (typeof module !== 'undefined' && typeof exports !== 'undefined' && module.ex module.exports = <%-: moduleName | q %>; } -(function(window, angular, undefined) {'use strict'; +(function(window, angular, undefined) { + 'use strict'; -var urlBase = <%-: urlBase | q %>; -var authHeader = 'authorization'; + var urlBase = <%-: urlBase | q %>; + var authHeader = 'authorization'; -function getHost(url) { - var m = url.match(/^(?:https?:)?\/\/([^\/]+)/); - return m ? m[1] : null; -} + function getHost(url) { + var m = url.match(/^(?:https?:)?\/\/([^\/]+)/); + return m ? m[1] : null; + } -var urlBaseHost = getHost(urlBase) || location.host; + var urlBaseHost = getHost(urlBase) || location.host; /** * @ngdoc overview @@ -31,11 +33,10 @@ var urlBaseHost = getHost(urlBase) || location.host; * the models exposed by the LoopBack server via the REST API. * */ -var module = angular.module(<%-: moduleName | q %>, ['ngResource']); + var module = angular.module(<%-: moduleName | q %>, ['ngResource']); <% for (var modelName in models) { var meta = models[modelName]; - // capitalize the model name modelName = modelName[0].toUpperCase() + modelName.slice(1); -%> @@ -66,101 +67,109 @@ var module = angular.module(<%-: moduleName | q %>, ['ngResource']); * including filter/where find query */ -%> */ -module.factory( - <%-: modelName | q %>, - ['LoopBackResource', 'LoopBackAuth', '$injector', function(Resource, LoopBackAuth, $injector) { - var R = Resource( - urlBase + <%-: meta.ctor.getFullPath() | q %>, + module.factory( + <%-: modelName | q %>, + [ + 'LoopBackResource', 'LoopBackAuth', '$injector', + function(Resource, LoopBackAuth, $injector) { + var R = Resource( + urlBase + <%-: meta.ctor.getFullPath() | q %>, <% /* Constructor arguments are hardcoded for now. We should generate it from sharedCtor.accepts instead. */ -%> - { 'id': '@id' }, - { + { 'id': '@id' }, + { <% meta.methods.forEach(function(action) { - var methodName = action.name.split('.').join('$'); --%> -<% ngdocForMethod(modelName, methodName, action); -%> - <%-: methodName | q %>: { + var methodName = action.name.split('.').join('$'); + ngdocForMethod(modelName, methodName, action); -%> + <%-: methodName | q %>: { <% if (action.isReturningArray()) { -%> - isArray: true, + isArray: true, <% } -%> <% if (meta.isUser && methodName === 'login') { -%> - params: { - include: "user" - }, - interceptor: { - response: function(response) { - var accessToken = response.data; - LoopBackAuth.setUser(accessToken.id, accessToken.userId, accessToken.user); - LoopBackAuth.rememberMe = response.config.params.rememberMe !== false; - LoopBackAuth.save(); - return response.resource; - } - }, + params: { + include: 'user', + }, + interceptor: { + response: function(response) { + var accessToken = response.data; + LoopBackAuth.setUser( + accessToken.id, accessToken.userId, accessToken.user); + LoopBackAuth.rememberMe = + response.config.params.rememberMe !== false; + LoopBackAuth.save(); + return response.resource; + }, + }, <% } else if (meta.isUser && methodName === 'logout') { -%> - interceptor: { - response: function(response) { - LoopBackAuth.clearUser(); - LoopBackAuth.clearStorage(); - return response.resource; - } - }, + interceptor: { + response: function(response) { + LoopBackAuth.clearUser(); + LoopBackAuth.clearStorage(); + return response.resource; + }, + responseError: function(responseError) { + LoopBackAuth.clearUser(); + LoopBackAuth.clearStorage(); + return responseError.resource; + }, + }, <% } -%> <% if (action.hasResourceParams) { -%> - params: { + params: { <% action.resourceParams.forEach(function(param, i, arr) { -%> - '<%= param.arg %>': '@<%= param.arg %>'<%= i < arr.length -1 ? ',' : '' %> + '<%= param.arg %>': '@<%= param.arg %>', <% }); //action.params.foreach -%> - }, + }, <% } -%> - url: urlBase + <%-: action.getFullPath() | q %>, - method: <%-: action.getHttpMethod() | q %> - }, + url: urlBase + <%-: action.getFullPath() | q %>, + method: <%-: action.getHttpMethod() | q %>, + }, <% }); // meta.methods.foreach -%> <% if (meta.isUser) { -%> - /** - * @ngdoc method - * @name <%- moduleName %>.<%- modelName %>#getCurrent - * @methodOf <%- moduleName %>.<%- modelName %> - * - * @description - * - * Get data of the currently logged user. Fail with HTTP result 401 - * when there is no user logged in. - * - * @param {function(Object,Object)=} successCb - * Success callback with two arguments: `value`, `responseHeaders`. - * - * @param {function(Object)=} errorCb Error callback with one argument: - * `httpResponse`. - * - * @returns {Object} An empty reference that will be - * populated with the actual data once the response is returned - * from the server. - */ - "getCurrent": { - url: urlBase + <%-: meta.getPath() | q %> + "/:id", - method: "GET", - params: { - id: function() { - var id = LoopBackAuth.currentUserId; - if (id == null) id = '__anonymous__'; - return id; + /** + * @ngdoc method + * @name <%- moduleName %>.<%- modelName %>#getCurrent + * @methodOf <%- moduleName %>.<%- modelName %> + * + * @description + * + * Get data of the currently logged user. Fail with HTTP result 401 + * when there is no user logged in. + * + * @param {function(Object,Object)=} successCb + * Success callback with two arguments: `value`, `responseHeaders`. + * + * @param {function(Object)=} errorCb Error callback with one argument: + * `httpResponse`. + * + * @returns {Object} An empty reference that will be + * populated with the actual data once the response is returned + * from the server. + */ + 'getCurrent': { + url: urlBase + <%-: meta.getPath() | q %> + '/:id', + method: 'GET', + params: { + id: function() { + var id = LoopBackAuth.currentUserId; + if (id == null) id = '__anonymous__'; + return id; + }, + }, + interceptor: { + response: function(response) { + LoopBackAuth.currentUserData = response.data; + return response.resource; + }, + }, + __isGetCurrentUser__: true, }, - }, - interceptor: { - response: function(response) { - LoopBackAuth.currentUserData = response.data; - return response.resource; - } - }, - __isGetCurrentUser__ : true - } <% } -%> - } - ); + } + ); <% meta.methods.forEach(function(action) { @@ -218,15 +227,15 @@ module.factory( }; <% } -%> - /** - * @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 %>; + /** + * @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 %>; <% for (var scopeName in meta.scopes) { var scope = meta.scopes[scopeName]; @@ -276,12 +285,23 @@ module.factory( <% }); // forEach methods name -%> <% } // for each scope -%> - return R; - }]); +<% if (meta.modelSchema) { -%> + /** + * @ngdoc object + * @name <%-: moduleName %>.<%- modelName %>#schema + * @propertyOf <%-: moduleName %>.<%- modelName %> + * @description + * The schema of the model represented by this $resource + */ + R.schema = <%- JSON.stringify(meta.modelSchema, null, 2) -%>; +<% } -%> + + return R; + }]); <% } // for modelName in models -%> -module + module .factory('LoopBackAuth', function() { var props = ['accessTokenId', 'currentUserId', 'rememberMe']; var propsPrefix = '$LoopBack$'; @@ -306,13 +326,13 @@ module this.accessTokenId = accessTokenId; this.currentUserId = userId; this.currentUserData = userData; - } + }; LoopBackAuth.prototype.clearUser = function() { this.accessTokenId = null; this.currentUserId = null; this.currentUserData = null; - } + }; LoopBackAuth.prototype.clearStorage = function() { props.forEach(function(name) { @@ -330,7 +350,7 @@ module var key = propsPrefix + name; if (value == null) value = ''; storage[key] = value; - } catch(err) { + } catch (err) { console.log('Cannot access local/session storage:', err); } } @@ -343,11 +363,10 @@ module .config(['$httpProvider', function($httpProvider) { $httpProvider.interceptors.push('LoopBackAuthRequestInterceptor'); }]) - .factory('LoopBackAuthRequestInterceptor', [ '$q', 'LoopBackAuth', + .factory('LoopBackAuthRequestInterceptor', ['$q', 'LoopBackAuth', function($q, LoopBackAuth) { return { 'request': function(config) { - // filter out external requests var host = getHost(config.url); if (host && host !== urlBaseHost) { @@ -360,16 +379,16 @@ module // Return a stub 401 error for User.getCurrent() when // there is no user logged in var res = { - body: { error: { status: 401 } }, + body: { error: { status: 401 }}, status: 401, config: config, - headers: function() { return undefined; } + headers: function() { return undefined; }, }; return $q.reject(res); } return config || $q.when(config); - } - } + }, + }; }]) /** @@ -407,6 +426,17 @@ module authHeader = header; }; + /** + * @ngdoc method + * @name <%-: moduleName %>.LoopBackResourceProvider#getAuthHeader + * @methodOf <%-: moduleName %>.LoopBackResourceProvider + * @description + * Get the header name that is used for sending the authentication token. + */ + this.getAuthHeader = function() { + return authHeader; + }; + /** * @ngdoc method * @name <%-: moduleName %>.LoopBackResourceProvider#setUrlBase @@ -434,7 +464,7 @@ module }; this.$get = ['$resource', function($resource) { - return function(url, params, actions) { + var LoopBackResource = function(url, params, actions) { var resource = $resource(url, params, actions); // Angular always calls POST on $save() @@ -448,6 +478,16 @@ module }; return resource; }; + + LoopBackResource.getUrlBase = function() { + return urlBase; + }; + + LoopBackResource.getAuthHeader = function() { + return authHeader; + }; + + return LoopBackResource; }]; }); <% @@ -464,28 +504,28 @@ function ngdocForMethod(modelName, methodName, action, responseModelName) { <% if (action.internal) { -%> - // INTERNAL. <%- action.internal %> + // INTERNAL. <%- action.internal %> <% return; } -%> - /** - * @ngdoc method - * @name <%- moduleName %>.<%- modelName %>#<%- methodName %> - * @methodOf <%- moduleName %>.<%- modelName %> + /** + * @ngdoc method + * @name <%- moduleName %>.<%- modelName %>#<%- methodName %> + * @methodOf <%- moduleName %>.<%- modelName %> <% if (action.deprecated) { -%> - * @deprecated <%- action.deprecated %> + * @deprecated <%- action.deprecated %> <% } -%> - * - * @description - * + * + * @description + * <% if (!action.description) { action.description = '\n' + '(The remote method definition does not provide any description.)\n' + ''; } -%> - * <%-: action.description | replace:/\n/g, '\n * ' %> - * + * <%-: action.description | replace:/\n/g, '\n * ' %> + * <% var params = action.accepts; var postData; @@ -498,77 +538,76 @@ if (action.getHttpMethod() == 'POST' || action.getHttpMethod() == 'PUT') { }); } -%> - * @param {Object=} parameters Request parameters. + * @param {Object=} parameters Request parameters. <% if (params.length == 0) { -%> - * - * This method does not accept any parameters. - * Supply an empty object or omit this argument altogether. + * + * This method does not accept any parameters. + * Supply an empty object or omit this argument altogether. <% } else { params.forEach(function(arg) { -%> - * - * - `<%- arg.arg %>` – `{<%- getJsDocType(arg) %>}` - <%- -(arg.description || '').replace(/\n/g, '\n * ') %> + * + * - `<%- arg.arg %>` – `{<%- getJsDocType(arg) %>}` -<%- +(arg.description ? ' ' + arg.description : '').replace(/\n/g, '\n * ') %> <% if (meta.isUser && methodName === 'login' && arg.arg === 'include') { -%> - * Default value: `user`. + * Default value: `user`. <% } -%> <% }); } -%> <% if (meta.isUser && methodName === 'login') { -%> - * - * - `rememberMe` - `boolean` - Whether the authentication credentials - * should be remembered in localStorage across app/browser restarts. - * Default: `true`. + * + * - `rememberMe` - `boolean` - Whether the authentication credentials + * should be remembered in localStorage across app/browser restarts. + * Default: `true`. <% } -%> <% if (postData) { -%> - * - * @param {Object} postData Request data. + * + * @param {Object} postData Request data. <% if (postData.length == 0) { -%> - * - * This method does not accept any data. Supply an empty object. + * + * This method does not accept any data. Supply an empty object. <% } else if (postData.length == 1 && postData[0].http && postData[0].http.source == 'body') { -%> - * - * This method expects a subset of model properties as request parameters. + * + * This method expects a subset of model properties as request parameters. <% } else { postData.forEach(function(arg) { -%> - * - * - `<%- arg.arg %>` – `{<%- getJsDocType(arg) %>}` - <%- -(arg.description || '').replace(/\n/g, '\n * ') %> + * + * - `<%- arg.arg %>` – `{<%- getJsDocType(arg) %>}` -<%- +(arg.description ? ' ' + arg.description : '').replace(/\n/g, '\n * ') %> <% }); } } -%> - * + * <% var returnType = action.isReturningArray() ? 'Array.': 'Object'; -%> - * @param {function(<%- returnType %>,Object)=} successCb - * Success callback with two arguments: `value`, `responseHeaders`. - * - * @param {function(Object)=} errorCb Error callback with one argument: - * `httpResponse`. - * - * @returns {<%- returnType %>} An empty reference that will be - * populated with the actual data once the response is returned - * from the server. - * + * @param {function(<%- returnType %>,Object)=} successCb + * Success callback with two arguments: `value`, `responseHeaders`. + * + * @param {function(Object)=} errorCb Error callback with one argument: + * `httpResponse`. + * + * @returns {<%- returnType %>} An empty reference that will be + * populated with the actual data once the response is returned + * from the server. + * <% if (!action.returns || action.returns.length == 0) { -%> - * This method returns no data. + * This method returns no data. <% } else if (action.returns[0].root) { -%> <% if (action.returns[0].description) { -%> - * <%- action.returns[0].description -.replace(/\n/g, '\n * ').trimRight() %> + * <%- action.returns[0].description +.replace(/\n+/g, '\n * ').trimRight() %> <% } else { -%> - * - * (The remote method definition does not provide any description. - * This usually means the response is a `<%- responseModelName || modelName %>` object.) - * + * + * (The remote method definition does not provide any description. + * This usually means the response is a `<%- responseModelName || modelName %>` object.) + * <% } -%> <% } else { -%> - * Data properties: + * Data properties: <% action.returns.forEach(function(arg) { -%> - * - * - `<%- arg.arg %>` – `{<%- getJsDocType(arg) %>}` - <%- -(arg.description || '').replace(/\n/g, '\n * ') %> + * + * - `<%- arg.arg %>` – `{<%- getJsDocType(arg) %>}` -<%- +(arg.description ? ' ' + arg.description : '').replace(/\n/g, '\n * ') %> <% }); } -%> - */ + */ <% } // end of ngdocForMethod -%> - })(window, window.angular); diff --git a/package.json b/package.json index 291e43d..9b38204 100644 --- a/package.json +++ b/package.json @@ -1,12 +1,14 @@ { "name": "loopback-sdk-angular", - "version": "1.7.0", + "version": "1.8.0", "description": "Tool for auto-generating Angular $resource services for LoopBack", "main": "index.js", "scripts": { - "prepublish": "node ./apidocs/describe-builtin-models.js", - "pretest": "jshint .", - "test": "node ./test.e2e/test-server.js node node_modules/karma/bin/karma start --single-run --browsers PhantomJS2" + "generate-loopback-core": "node ./apidocs/describe-builtin-models.js", + "prepublish": "npm run generate-loopback-core", + "test": "node ./test.e2e/test-server.js node node_modules/karma/bin/karma start --single-run --browsers PhantomJS2", + "lint": "eslint .", + "posttest": "npm run generate-loopback-core && npm run lint" }, "repository": { "type": "git", @@ -34,9 +36,10 @@ "cors": "^2.2", "debug": "^2.2.0", "errorhandler": "^1.1.1", + "eslint": "^2.5.3", + "eslint-config-loopback": "^1.0.0", "express": "^4.6", "fs.extra": "^1.2", - "jshint": "^2.4", "karma": "^0.13.19", "karma-chrome-launcher": "^0.2.2", "karma-junit-reporter": "^0.3.8", diff --git a/parse-helper.js b/parse-helper.js index c74d933..df04ae9 100644 --- a/parse-helper.js +++ b/parse-helper.js @@ -1,3 +1,8 @@ +// Copyright IBM Corp. 2014. All Rights Reserved. +// Node module: loopback-sdk-angular +// This file is licensed under the MIT License. +// License text available at https://opensource.org/licenses/MIT + /*! * Parsers for extracting data from the generated lb-service.js code. * Used by unit-tests in grunt-loopback-sdk-angular and diff --git a/test.e2e/given.js b/test.e2e/given.js index 5ae75d4..7312c8f 100644 --- a/test.e2e/given.js +++ b/test.e2e/given.js @@ -1,3 +1,8 @@ +// Copyright IBM Corp. 2014,2015. All Rights Reserved. +// Node module: loopback-sdk-angular +// This file is licensed under the MIT License. +// License text available at https://opensource.org/licenses/MIT + define(['angular', 'angularMocks', 'angularResource'], function(angular) { 'use strict'; diff --git a/test.e2e/spec/services.spec.js b/test.e2e/spec/services.spec.js index 2cbb07e..194b163 100644 --- a/test.e2e/spec/services.spec.js +++ b/test.e2e/spec/services.spec.js @@ -1,76 +1,81 @@ +// Copyright IBM Corp. 2014,2015. All Rights Reserved. +// Node module: loopback-sdk-angular +// This file is licensed under the MIT License. +// License text available at https://opensource.org/licenses/MIT + define(['angular', 'given', 'util'], function(angular, given, util) { 'use strict'; describe('services', function() { describe('url base and authentication header customization', function() { var createInjector, - $injector, - httpProvider, - loopBackResourceProvider, - moduleName = 'urlBaseAndAuthHeaderCustomization', - // set angular configuration - // 1. Add special HttpTestRequestInterceptor - // 2. Expose providers to parent scope to easily access - // them from the tests - setTestAngularModuleConfig = function() { - angular.module(moduleName) - .config(function(LoopBackResourceProvider, $httpProvider) { - loopBackResourceProvider = LoopBackResourceProvider; - httpProvider = $httpProvider; - httpProvider.interceptors.push('HttpTestRequestInterceptor'); - }) - .factory('HttpTestRequestInterceptor', function($q) { - return { - 'request': function(config) { - var deferred = $q.defer(); - // set a promise as timeout to avoid - // unnecessary request, as soon as the promise - // is resolved the "resource" promise that is - // responsable for making the real request will be - // canceled and it will throw an error that also - // propagates the config data needed to do the assertions. - config.timeout = deferred.promise; - // set httpTestRequestInterceptor variable to - // be able to handle cancelled requests coming from - // this interceptor. - config.httpTestRequestInterceptor = true; - // resolve the promise immediately - deferred.resolve(); - return config; - } - }; - }); - }, - expectMockedRequestPromise = function(promise) { - return promise.then( - // success handler - // NOTE: interceptor should always fail due the request is - // being cancelled so if it succeed it means that - // something is wrong and the test should fail. - function() { - throw new Error('The request was supposed to fail.'); - }, - // error handler - function(req) { - var config = req.config; - // when request has been cancelled by HttpTestRequestInterceptor - // then do the assertion otherwise just fail - if (config.httpTestRequestInterceptor) { - return req; - } else { - throw new Error('httpTestRequestInterceptor is not working'); - } - } - ); + $injector, + httpProvider, + loopBackResourceProvider; + var moduleName = 'urlBaseAndAuthHeaderCustomization'; + // set angular configuration + // 1. Add special HttpTestRequestInterceptor + // 2. Expose providers to parent scope to easily access + // them from the tests + var setTestAngularModuleConfig = function() { + angular.module(moduleName) + .config(function(LoopBackResourceProvider, $httpProvider) { + loopBackResourceProvider = LoopBackResourceProvider; + httpProvider = $httpProvider; + httpProvider.interceptors.push('HttpTestRequestInterceptor'); + }) + .factory('HttpTestRequestInterceptor', function($q) { + return { + 'request': function(config) { + var deferred = $q.defer(); + // set a promise as timeout to avoid + // unnecessary request, as soon as the promise + // is resolved the "resource" promise that is + // responsable for making the real request will be + // canceled and it will throw an error that also + // propagates the config data needed to do the assertions. + config.timeout = deferred.promise; + // set httpTestRequestInterceptor variable to + // be able to handle cancelled requests coming from + // this interceptor. + config.httpTestRequestInterceptor = true; + // resolve the promise immediately + deferred.resolve(); + return config; + }, }; + }); + }; + var expectMockedRequestPromise = function(promise) { + return promise.then( + // success handler + // NOTE: interceptor should always fail due the request is + // being cancelled so if it succeed it means that + // something is wrong and the test should fail. + function() { + throw new Error('The request was supposed to fail.'); + }, + // error handler + function(req) { + var config = req.config; + // when request has been cancelled by HttpTestRequestInterceptor + // then do the assertion otherwise just fail + if (config.httpTestRequestInterceptor) { + return req; + } else { + throw new Error('httpTestRequestInterceptor is not working'); + } + } + ); + }; before(function() { return given.servicesForLoopBackApp( { name: moduleName, models: { - MyModel: { name: { type: String, required: true } } - } + MyModel: { name: { type: String, required: true }}, + }, }) .then(function(_createInjector) { setTestAngularModuleConfig(); @@ -88,13 +93,25 @@ define(['angular', 'given', 'util'], function(angular, given, util) { }); describe('LoopBackResourceProvider', function() { + it('has getAuthHeader method', function() { + expect(loopBackResourceProvider).to.have.property('getAuthHeader'); + }); + + it('can get authHeader', function() { + var authHeader = 'X-Awesome-Token'; + loopBackResourceProvider.setAuthHeader(authHeader); + var gotAuthHeader = loopBackResourceProvider.getAuthHeader(); + + return expect(gotAuthHeader).to.equal(authHeader); + }); + it('has setAuthHeader method', function() { expect(loopBackResourceProvider).to.have.property('setAuthHeader'); }); it('can configure authorization header', function() { - var authHeader = 'X-Awesome-Token', - accessTokenId = '123456'; + var authHeader = 'X-Awesome-Token'; + var accessTokenId = '123456'; loopBackResourceProvider.setAuthHeader(authHeader); var $injector = createInjector(); @@ -147,6 +164,40 @@ define(['angular', 'given', 'util'], function(angular, given, util) { }); }); + describe('LoopBackResource', function() { + it('has getAuthHeader method', function() { + var $injector = createInjector(); + var loopBackResource = $injector.get('LoopBackResource'); + expect(loopBackResource).to.have.property('getAuthHeader'); + }); + + it('can get authHeader', function() { + var $injector = createInjector(); + var loopBackResource = $injector.get('LoopBackResource'); + var authHeader = 'X-Awesome-Token'; + loopBackResourceProvider.setAuthHeader(authHeader); + var gotAuthHeader = loopBackResource.getAuthHeader(); + + return expect(gotAuthHeader).to.equal(authHeader); + }); + + it('has getUrlBase method', function() { + var $injector = createInjector(); + var loopBackResource = $injector.get('LoopBackResource'); + expect(loopBackResource).to.have.property('getUrlBase'); + }); + + it('can get urlBase', function() { + var $injector = createInjector(); + var loopBackResource = $injector.get('LoopBackResource'); + var urlBase = 'http://test.urlbase'; + loopBackResourceProvider.setUrlBase(urlBase); + var base = loopBackResource.getUrlBase(); + + return expect(base).to.equal(urlBase); + }); + }); + describe('LoopBackAuthRequestInterceptor', function() { it('should be configured as an $httpProvider\'s interceptor', function() { @@ -256,7 +307,6 @@ define(['angular', 'given', 'util'], function(angular, given, util) { } ); }); - }); }); @@ -266,8 +316,8 @@ define(['angular', 'given', 'util'], function(angular, given, util) { return given.servicesForLoopBackApp( { models: { - MyModel: { name: { type: String, required: true } } - } + MyModel: { name: { type: String, required: true }}, + }, }) .then(function(createInjector) { $injector = createInjector(); @@ -315,15 +365,15 @@ define(['angular', 'given', 'util'], function(angular, given, util) { var arr = MyModel.createMany([ { name: 'one', multi: true }, { name: 'two', multi: true }, - { name: 'three', multi: true } + { name: 'three', multi: true }, ], function() { expect(arr).to.have.property('length', 3); }); - return arr.$promise.then(function() { - var found = MyModel.find({ - filter: { where: { multi: true } } }, + return arr.$promise.then(function() { + var found = MyModel.find({ + filter: { where: { multi: true }}}, function() { var namesFound = found.map(function(it) { return it.name; }); expect(namesFound).to.eql(['one', 'two', 'three']); @@ -344,7 +394,7 @@ define(['angular', 'given', 'util'], function(angular, given, util) { ); return promise.then(function() { var found = MyModel.find( - { filter: { where: { name: obj.name } } }, + { filter: { where: { name: obj.name }}}, function() { expect(found).to.have.length(1); expect(found[0].id).to.equal(obj.id); @@ -365,7 +415,7 @@ define(['angular', 'given', 'util'], function(angular, given, util) { }) .then(function() { var found = MyModel.find( - { filter: { where: { name: obj.name } } }, + { filter: { where: { name: obj.name }}}, function() { expect(found).to.have.length(1); expect(found[0].id).to.equal(obj.id); @@ -393,7 +443,7 @@ define(['angular', 'given', 'util'], function(angular, given, util) { 'deleteById', 'removeById', 'count', - 'prototype$updateAttributes' + 'prototype$updateAttributes', ]); }); @@ -408,8 +458,8 @@ define(['angular', 'given', 'util'], function(angular, given, util) { return given.servicesForLoopBackApp( { models: { - 'lower-case-not-an-identifier': {} - } + 'lower-case-not-an-identifier': {}, + }, }) .then(function(createInjector) { $injector = createInjector(); @@ -432,14 +482,14 @@ define(['angular', 'given', 'util'], function(angular, given, util) { setupFn: (function(app, cb) { var Pretender = app.models.Pretender; Pretender.prototype['__get__spaces'] = function(cb) { - cb(null, [1,2,3]); + cb(null, [1, 2, 3]); }; Pretender.remoteMethod( '__get__spaces', { isStatic: false, http: { path: '/spaces', verb: 'get' }, - returns: { arg: 'spaces', type: 'array', root: true } + returns: { arg: 'spaces', type: 'array', root: true }, } ); cb(); @@ -472,18 +522,18 @@ define(['angular', 'given', 'util'], function(angular, given, util) { accessTokens: { model: 'AccessToken', type: 'hasMany', - foreignKey: 'userId' - } - } - } + foreignKey: 'userId', + }, + }, + }, }, product: { properties: { - model: String - } - } + model: String, + }, + }, }, - enableAuth: true + enableAuth: true, }) .then(function(_createInjector) { createInjector = _createInjector; @@ -542,6 +592,27 @@ define(['angular', 'given', 'util'], function(angular, given, util) { .catch(util.throwHttpError); }); + it('clears authentication data on logout error', function() { + return givenLoggedInUser() + .then(function() { + var auth = $injector.get('LoopBackAuth'); + expect(auth.accessTokenId, 'accessTokenId').to.not.equal(null); + auth.accessTokenId = 'fake_access_token'; + return Customer.logout().$promise; + }) + .then(function() { + var auth = $injector.get('LoopBackAuth'); + expect(auth.accessTokenId, 'accessTokenId').to.equal(null); + expect(auth.currentUserId, 'currentUserId').to.equal(null); + + // Check that localStorage was cleared too. + auth = getNew('LoopBackAuth'); + expect(auth.accessTokenId, 'stored accessTokenId').to.equal(null); + expect(auth.currentUserId, 'stored currentUserId').to.equal(null); + }) + .catch(util.throwHttpError); + }); + it('clears authentication data in local and session storage ' + 'on logout when rememberMe=true and page has been reloaded after login', function() { @@ -599,9 +670,9 @@ define(['angular', 'given', 'util'], function(angular, given, util) { }); it('resolves `undefined` rememberMe to true', function() { - var loginParams = { rememberMe : undefined }; - return givenLoggedInUser('rememberMe@example.com',loginParams) - .then(function( user ) { + var loginParams = { rememberMe: undefined }; + return givenLoggedInUser('rememberMe@example.com', loginParams) + .then(function(user) { var LoopBackAuth = $injector.get('LoopBackAuth'); expect(LoopBackAuth.rememberMe).to.equal(true); }) @@ -609,11 +680,11 @@ define(['angular', 'given', 'util'], function(angular, given, util) { }); it('`rememberMe` false should be correct for Storages', function() { - var loginParams = { rememberMe : false }; - return givenLoggedInUser('dontremember@example.com',loginParams) - .then(function( user ) { + var loginParams = { rememberMe: false }; + return givenLoggedInUser('dontremember@example.com', loginParams) + .then(function(user) { var LoopBackAuth = $injector.get('LoopBackAuth'); - var rememberMeKey = LoopBackAuth.propsPrefix+'rememberMe'; + var rememberMeKey = LoopBackAuth.propsPrefix + 'rememberMe'; expect(LoopBackAuth.rememberMe).to.equal(false); expect(localStorage[rememberMeKey]).to.not.equal(true); expect(sessionStorage[rememberMeKey]).to.not.equal(true); @@ -698,7 +769,7 @@ define(['angular', 'given', 'util'], function(angular, given, util) { }); }); - it('provides User.getCurrentId method', function () { + it('provides User.getCurrentId method', function() { return givenLoggedInUser() .then(function(token) { expect(Customer.getCurrentId()).to.equal(token.userId); @@ -709,7 +780,7 @@ define(['angular', 'given', 'util'], function(angular, given, util) { function givenLoggedInUser(email, loginParams) { var credentials = { email: email || 'user-' + (++idCounter) + '@example.com', - password: 'a-password' + password: 'a-password', }; return Customer.create(credentials).$promise @@ -730,7 +801,7 @@ define(['angular', 'given', 'util'], function(angular, given, util) { // use the built-in User model }, }, - enableAuth: true + enableAuth: true, }) .then(function(createInjector) { $injector = createInjector(); @@ -761,10 +832,10 @@ define(['angular', 'given', 'util'], function(angular, given, util) { relations: { categories: { model: 'Category', - type: 'hasAndBelongsToMany' - } - } - } + type: 'hasAndBelongsToMany', + }, + }, + }, }, Category: { properties: { name: 'string' }, @@ -772,11 +843,11 @@ define(['angular', 'given', 'util'], function(angular, given, util) { relations: { products: { model: 'Product', - type: 'hasAndBelongsToMany' - } - } - } - } + type: 'hasAndBelongsToMany', + }, + }, + }, + }, }, setupFn: (function(app, cb) { /*globals debug:true */ @@ -794,12 +865,12 @@ define(['angular', 'given', 'util'], function(angular, given, util) { cb(null, { product: prod, - category: cat + category: cat, }); }); }); }); - }).toString() + }).toString(), }) .then(function(createInjector) { $injector = createInjector(); @@ -822,7 +893,7 @@ define(['angular', 'given', 'util'], function(angular, given, util) { 'findById', 'link', 'unlink', - 'updateById' + 'updateById', ]); }); @@ -861,7 +932,7 @@ define(['angular', 'given', 'util'], function(angular, given, util) { .then(function(cat) { return Product.categories.unlink({ id: testData.product.id, - fk: cat.id + fk: cat.id, }).$promise; }) .then(function() { @@ -879,7 +950,7 @@ define(['angular', 'given', 'util'], function(angular, given, util) { return Product.categories.link( { id: testData.product.id, - fk: cat.id + fk: cat.id, }, // IMPORTANT: we must pass an empty postData arg, otherwise // both id and fk are sent in the request body and the "id" value @@ -901,14 +972,14 @@ define(['angular', 'given', 'util'], function(angular, given, util) { [ { name: 'another-cat' }, { name: 'yet-another-cat' }, - { name: 'last-cat' } + { name: 'last-cat' }, ], function() { expect(cats).to.have.property('length', 3); }); return cats.$promise .then(function() { - cats.forEach(function(cat){ + cats.forEach(function(cat) { expect(cat).to.be.an.instanceof(Category); }); }); @@ -934,6 +1005,45 @@ define(['angular', 'given', 'util'], function(angular, given, util) { }); }); + describe('$resource generated with includeSchema:true', function() { + var $injector; + before(function() { + return given.servicesForLoopBackApp( + { + models: { + Product: { + properties: { + name: 'string', + price: { type: 'number' }, + }, + }, + }, + includeSchema: true, + }) + .then(function(createInjector) { + $injector = createInjector(); + }); + }); + + it('has "schema" property with normalized LDL', function() { + var Product = $injector.get('Product'); + var methodNames = Object.keys(Product); + expect(methodNames).to.include.members(['schema']); + var schema = Product.schema; + expect(schema).to.have.property('name', 'Product'); + expect(schema).to.have.property('properties'); + console.log('schema properties', schema.properties); + expect(schema.properties).to.eql({ + // "name: 'string'" was converted to full schema object + name: { type: 'String' }, + // Type "number" was normalized to "Number" + price: { type: 'Number' }, + // auto-injected id property + id: { id: 1, generated: true, type: 'Number' }, + }); + }); + }); + describe('for models with belongsTo relation', function() { var $injector, Town, Country, testData; before(function() { @@ -946,10 +1056,10 @@ define(['angular', 'given', 'util'], function(angular, given, util) { relations: { country: { model: 'Country', - type: 'belongsTo' - } - } - } + type: 'belongsTo', + }, + }, + }, }, Country: { properties: { name: 'string' }, @@ -957,11 +1067,11 @@ define(['angular', 'given', 'util'], function(angular, given, util) { relations: { towns: { model: 'Town', - type: 'hasMany' - } - } - } - } + type: 'hasMany', + }, + }, + }, + }, }, setupFn: (function(app, cb) { /*globals debug:true */ @@ -982,14 +1092,14 @@ define(['angular', 'given', 'util'], function(angular, given, util) { cb(null, { country: country, - town: town + town: town, }); }); } ); } ); - }).toString() + }).toString(), }) .then(function(createInjector) { $injector = createInjector(); diff --git a/test.e2e/test-main.js b/test.e2e/test-main.js index 319e3d5..bad6631 100644 --- a/test.e2e/test-main.js +++ b/test.e2e/test-main.js @@ -1,3 +1,8 @@ +// Copyright IBM Corp. 2014,2016. All Rights Reserved. +// Node module: loopback-sdk-angular +// This file is licensed under the MIT License. +// License text available at https://opensource.org/licenses/MIT + var tests = []; for (var file in window.__karma__.files) { if (window.__karma__.files.hasOwnProperty(file)) { @@ -18,27 +23,27 @@ requirejs.config({ angularResource: 'node_modules/angular-resource/angular-resource', angularMocks: 'node_modules/angular-mocks/angular-mocks', given: 'test.e2e/given', - util: 'test.e2e/util' + util: 'test.e2e/util', }, shim: { 'angular': { exports: 'angular' }, 'angularResource': { deps: ['angular'], - exports: 'ngResource' + exports: 'ngResource', }, 'angularMocks': { deps: ['angular'], - exports: 'angular.mock' + exports: 'angular.mock', }, - 'chai': { exports: 'chai' } + 'chai': { exports: 'chai' }, }, // ask Require.js to load these files (all our tests) deps: tests, // start test run, once Require.js is done - callback: window.__karma__.start + callback: window.__karma__.start, }); require(['chai'], function(chai) { diff --git a/test.e2e/test-server.js b/test.e2e/test-server.js index f5a63dc..0b74ea6 100644 --- a/test.e2e/test-server.js +++ b/test.e2e/test-server.js @@ -1,3 +1,8 @@ +// Copyright IBM Corp. 2014,2016. All Rights Reserved. +// Node module: loopback-sdk-angular +// This file is licensed under the MIT License. +// License text available at https://opensource.org/licenses/MIT + /* The test server is an HTTP service allowing front-end tests running in a browser to setup @@ -13,13 +18,9 @@ var morgan = require('morgan'); var errorHandler = require('errorhandler'); var port = process.env.PORT || 3838; -var baseUrl; -var apiUrl; +var baseUrl, apiUrl, lbApp, servicesScript; var masterApp = express(); -var lbApp; -var servicesScript; - // Speed up the password hashing algorithm // for tests using the built-in User model loopback.User.settings.saltWorkFactor = 4; @@ -66,6 +67,7 @@ masterApp.post('/setup', function(req, res, next) { var name = opts.name; var models = opts.models; var enableAuth = opts.enableAuth; + var includeSchema = opts.includeSchema; var setupFn = compileSetupFn(name, opts.setupFn); if (!name) @@ -105,7 +107,17 @@ masterApp.post('/setup', function(req, res, next) { } try { - servicesScript = generator.services(lbApp, name, apiUrl); + if (includeSchema) { + // the new options-based API + servicesScript = generator.services(lbApp, { + ngModuleName: name, + apiUrl: apiUrl, + includeSchema: includeSchema, + }); + } else { + // the old API, test it to verify backwards compatibility + servicesScript = generator.services(lbApp, name, apiUrl); + } } catch (err) { console.error('Cannot generate services script:', err.stack); servicesScript = 'throw new Error("Error generating services script.");'; @@ -116,7 +128,6 @@ masterApp.post('/setup', function(req, res, next) { res.send(200, { servicesUrl: baseUrl + 'services?' + name }); }.bind(this)); - }); function compileSetupFn(name, source) { @@ -134,7 +145,7 @@ masterApp.get('/services', function(req, res, next) { }); masterApp.use('/api', function(res, req, next) { - if(!lbApp) return next(new Error('Call /setup first.')); + if (!lbApp) return next(new Error('Call /setup first.')); lbApp(res, req, next); }); diff --git a/test.e2e/util.js b/test.e2e/util.js index 8074fa2..f93b75c 100644 --- a/test.e2e/util.js +++ b/test.e2e/util.js @@ -1,3 +1,8 @@ +// Copyright IBM Corp. 2014,2016. All Rights Reserved. +// Node module: loopback-sdk-angular +// This file is licensed under the MIT License. +// License text available at https://opensource.org/licenses/MIT + define(function() { 'use strict'; @@ -10,7 +15,7 @@ define(function() { var msg = 'HTTP ' + res.status; if (res.data && res.data.error && res.data.error.message) msg += ' ' + res.data.error.message; - msg += ' [' + res.config.method + ' ' +res.config.url + ']'; + msg += ' [' + res.config.method + ' ' + res.config.url + ']'; var details = res.data && res.data.error && res.data.error.details; if (details)