diff --git a/.github/CONTRIBUTING.md b/.github/CONTRIBUTING.md index 701884b6..1aee8eff 100644 --- a/.github/CONTRIBUTING.md +++ b/.github/CONTRIBUTING.md @@ -1,13 +1,43 @@ -#### What type of pull request are you creating? -- [ ] Bug Fix -- [ ] Enhancement -- [ ] Documentation -#### How many unit test did you write for this pull request? +# How to contribute +I'm really glad you're reading this, volunteer developers to help this project are always welcome. +If you haven't already, follow me ([@johncasarrubias](irc://chat.freenode.net/opengovernment) on twitter). I want you to keep informed about new features and tutorials. -Write a reason if none (e.g just fixed a typo): +Here are some important resources: + * [MEAN Expert Blog](http://mean.expert) tutorials about the MEAN Stack. + * [WIKI](https://github.com/mean-expert-official/loopback-sdk-builder/wiki) official wiki documentation. + * [Angular 2 Testing](https://angular.io/docs/ts/latest/guide/testing.html) official documentation for testing environment. + * Bugs? [GitHub Issues](https://github.com/mean-expert-official/loopback-sdk-builder/issues) is where to report them -#### Please add a description for your pull request: \ No newline at end of file +## Adding Issues +If you find any bug or enhancement, you are always welcome to create a [New Issue](https://github.com/mean-expert-official/loopback-sdk-builder/issues). + +## Pull Request +If you would like to contribute by adding new features, enhancements or by fixing bugs; please consider that you need to create an issue prior your pull request. This is important for tracking purposes in CHANGELOG. + +**IMPORTANT: Make sure you create a branch from `development` and then create the pull request also to development and not to master.** + +Please send a [GitHub Pull Request](https://github.com/mean-expert-official/loopback-sdk-builder/pull/new/development) with a clear list of what you've done (read more about [pull requests](http://help.github.com/pull-requests/)). When you send a pull request, we will love you forever if you include RSpec examples. We can always use more test coverage. Please make sure all of your commits are atomic (one feature per commit). + +Always write a clear log message for your commits. One-line messages are fine for small changes, but bigger changes should look like this: + + $ git commit -m "A brief summary of the commit + > + > A paragraph describing what changed and its impact." + +Most of the times you will need to add a new test or we may not be able to integrate it. Though, there are some cases when you don't need to add a unit test, like fixing a typo, adding a missing type, etc. + +## Testing + +Tests are being created and excecuted by using the Angular-CLI Tool, please refer to the official documentation. + +````sh +$ cd to/loopback-sdk-builder +$ npm test +```` + +Thanks, +Jonathan Casarrubias, [MEAN Expert](http://mean.expert). \ No newline at end of file diff --git a/.github/ISSUE_TEMPLATE.md b/.github/ISSUE_TEMPLATE.md index 315eb039..973d5458 100644 --- a/.github/ISSUE_TEMPLATE.md +++ b/.github/ISSUE_TEMPLATE.md @@ -5,7 +5,7 @@ #### What version of this module are you using? - [ ] 2.0.10 (Stable) -- [ ] 2.1.0-beta.14 +- [ ] 2.1.0-rc.n (2.1 Release Candidate n) - [ ] Other Write other if any: diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md index d540d80a..5273db10 100644 --- a/.github/PULL_REQUEST_TEMPLATE.md +++ b/.github/PULL_REQUEST_TEMPLATE.md @@ -1,40 +1,12 @@ -# How to contribute +#### What type of pull request are you creating? +- [ ] Bug Fix +- [ ] Enhancement +- [ ] Documentation -I'm really glad you're reading this, volunteer developers to help this project are always welcome. +#### How many unit test did you write for this pull request? -If you haven't already, follow me ([@johncasarrubias](irc://chat.freenode.net/opengovernment) on twitter). I want you to keep informed about new features and tutorials. -Here are some important resources: +Write a reason if none (e.g just fixed a typo): - * [MEAN Expert Blog](http://mean.expert) tutorials about the MEAN Stack. - * [WIKI](https://github.com/mean-expert-official/loopback-sdk-builder/wiki) official wiki documentation. - * [Angular 2 Testing](https://angular.io/docs/ts/latest/guide/testing.html) official documentation for testing environment. - * Bugs? [GitHub Issues](https://github.com/mean-expert-official/loopback-sdk-builder/issues) is where to report them -## Adding Issues -If you find any bug or enhancement, you are always welcome to create a [New Issue](https://github.com/mean-expert-official/loopback-sdk-builder/issues). - -## Pull Request -If you would like to contribute by adding new features, enhancements or by fixing bugs; please consider that you need to create an issue prior your pull request. This is important for tracking purposes in CHANGELOG. - -Please send a [GitHub Pull Request](https://github.com/mean-expert-official/loopback-sdk-builder/pull/new/master) with a clear list of what you've done (read more about [pull requests](http://help.github.com/pull-requests/)). When you send a pull request, we will love you forever if you include RSpec examples. We can always use more test coverage. Please make sure all of your commits are atomic (one feature per commit). - -Always write a clear log message for your commits. One-line messages are fine for small changes, but bigger changes should look like this: - - $ git commit -m "A brief summary of the commit - > - > A paragraph describing what changed and its impact." - -Most of the times you will need to add a new test or we may not be able to integrate it. Though, there are some cases when you don't need to add a unit test, like fixing a typo, adding a missing type, etc. - -## Testing - -Tests are being created and excecuted by using the Angular-CLI Tool, please refer to the official documentation. - -````sh -$ cd to/loopback-sdk-builder -$ npm test -```` - -Thanks, -Jonathan Casarrubias, [MEAN Expert](http://mean.expert). \ No newline at end of file +#### Please add a description for your pull request: \ No newline at end of file diff --git a/CHANGELOG.md b/CHANGELOG.md index c536d876..2f0b713d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,27 @@ This file is created to keep history of the LoopBack SDK Builder, it does not consider or keeps any history of its parent module `loopback-sdk-angular`. +## Release 2.1.0-rc1 + +- Fix: https://github.com/mean-expert-official/loopback-sdk-builder/issues/232 +- Fix: https://github.com/mean-expert-official/loopback-sdk-builder/issues/231 +- Fix: https://github.com/mean-expert-official/loopback-sdk-builder/issues/228 +- Fix: https://github.com/mean-expert-official/loopback-sdk-builder/issues/201 +- Fix: https://github.com/mean-expert-official/loopback-sdk-builder/issues/223 +- Fix: https://github.com/mean-expert-official/loopback-sdk-builder/issues/220 +- Fix: https://github.com/mean-expert-official/loopback-sdk-builder/issues/31 +- Fix: https://github.com/mean-expert-official/loopback-sdk-builder/issues/199 +- Fix: https://github.com/mean-expert-official/loopback-sdk-builder/issues/210 +- Fix: https://github.com/mean-expert-official/loopback-sdk-builder/issues/209 +- Fix: https://github.com/mean-expert-official/loopback-sdk-builder/issues/208 +- Fix: https://github.com/mean-expert-official/loopback-sdk-builder/issues/207 +- Fix: https://github.com/mean-expert-official/loopback-sdk-builder/issues/206 +- Fix: https://github.com/mean-expert-official/loopback-sdk-builder/issues/36 +- Fix: https://github.com/mean-expert-official/loopback-sdk-builder/issues/205 +- Fix: https://github.com/mean-expert-official/loopback-sdk-builder/issues/204 +- Fix: https://github.com/mean-expert-official/loopback-sdk-builder/issues/203 +- Fix: https://github.com/mean-expert-official/loopback-sdk-builder/issues/202 + ## Release 2.1.0-beta.17 - Fix: https://github.com/mean-expert-official/loopback-sdk-builder/issues/190 diff --git a/README.md b/README.md index f97ffaa5..6eea3c5d 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -[![npm version](https://badge.fury.io/js/%40mean-expert%2Floopback-sdk-builder.svg)](https://badge.fury.io/js/%40mean-expert%2Floopback-sdk-builder) [![Build Status](https://travis-ci.org/mean-expert-official/loopback-sdk-builder.svg?branch=development)](https://travis-ci.org/mean-expert-official/loopback-sdk-builder) [![dependencies](https://david-dm.org/mean-expert-official/loopback-sdk-builder.png)](https://david-dm.org/mean-expert-official/loopback-sdk-builder) [![Known Vulnerabilities](https://snyk.io/test/npm/@mean-expert/loopback-sdk-builder/badge.svg)](https://snyk.io/test/npm/@mean-expert/loopback-sdk-builder) +[![npm version](https://badge.fury.io/js/%40mean-expert%2Floopback-sdk-builder.svg)](https://badge.fury.io/js/%40mean-expert%2Floopback-sdk-builder) [![Build Status](https://travis-ci.org/mean-expert-official/loopback-sdk-builder.svg?branch=development)](https://travis-ci.org/mean-expert-official/loopback-sdk-builder) [![dependencies](https://david-dm.org/mean-expert-official/loopback-sdk-builder.png)](https://david-dm.org/mean-expert-official/loopback-sdk-builder) ![LoopBack SDK Builder](https://storage.googleapis.com/mean-expert-images/sdk-builder.jpg) diff --git a/bin/lb-sdk b/bin/lb-sdk index 175112d4..a9f8a815 100755 --- a/bin/lb-sdk +++ b/bin/lb-sdk @@ -22,16 +22,20 @@ var argv = optimist .usage('\n******************************************* LoopBack SDK Builder 2.0 *******************************************\n' + '\nGenerate Client SDK for your LoopBack Application.' + '\nUsage:' + - '\n ./node_modules/.bin/lb-sdk server/server app/shared/sdk -d [ng4web | nativescript2] -i [enabled | disabled]') + '\n ./node_modules/.bin/lb-sdk server/server app/shared/sdk -d [ng2web | ng2native | ng2universal] -i [enabled | disabled] -v [enabled | strict | disabled]') .describe('l', 'Client\'s library (angular2, react , ...)') - .describe('d', 'Platform specific drivers (ng4web, nativescript2, ng2universal )') + .describe('d', 'Platform specific drivers (ng2web, ng2native, ng2universal)') .describe('i', 'Enable PubSub, IO and FireLoop functionality') .describe('w', 'Automatically wipe SDK Directory') + .describe('v', 'Add default values in models') + .describe('f', 'Generate only FireLoop SDK + Auth Services') .default('l', 'angular2') - .default('d', 'ng4web') + .default('d', 'ng2web') .default('i', 'enabled') .default('w', 'disabled') - .alias({ u: 'url', m: 'module-name', l: 'library', i: 'io', d: 'driver', w: 'wipe' }) + .default('v', 'disabled') + .default('f', 'disabled') + .alias({ u: 'url', m: 'module-name', l: 'library', i: 'io', d: 'driver', w: 'wipe', v: 'default-values', v: 'fireloop-only' }) .demand(1) .argv; /** @@ -56,6 +60,9 @@ console.log(chalk.green('* Sylvain Dumont *')); console.log(chalk.green('* Chris Tunbridge *')); console.log(chalk.green('* Miguel Serrano *')); +console.log(chalk.green('* Julien Ledun *')); +console.log(chalk.green('* Paul Robinson *')); +console.log(chalk.green('* Corentin Hatte *')); console.log(chalk.green('* *')); console.log(chalk.green('* ORIGINALLY FORKED FROM *')); console.log(chalk.green('* Miroslav Bajtos\' *')); @@ -89,8 +96,10 @@ var context = { apiUrl: argv['url'] || app.get('restApiRoot') || '/api', outputFolder: argv._[1], isIo: argv['i'] || 'disabled', - driver: argv['d'] || 'ng4web', - wipe: argv['w'] || 'disabled' + driver: argv['d'] || 'ng2web', + wipe: argv['w'] || 'disabled', + defaultValue: argv['v'] || 'disabled', + fireloopOnly: argv['f'] || 'disabled' }; function verifyPath() { diff --git a/lib/angular2/drivers/nativescript2/socket.driver.ejs b/lib/angular2/drivers/nativescript2/socket.driver.ejs deleted file mode 100644 index 6c8302f6..00000000 --- a/lib/angular2/drivers/nativescript2/socket.driver.ejs +++ /dev/null @@ -1,9 +0,0 @@ -/* tslint:disable */ -var SocketIO = require('nativescript-socketio').SocketIO; -export class SocketDriver { - static connect(url: any, options: any) { - let socketIO: any = new SocketIO(url, options) - socketIO.connect(); - return socketIO; - } -} diff --git a/lib/angular2/drivers/ng4web/storage.driver.ejs b/lib/angular2/drivers/ng4web/storage.driver.ejs deleted file mode 100644 index a26dcbc6..00000000 --- a/lib/angular2/drivers/ng4web/storage.driver.ejs +++ /dev/null @@ -1,12 +0,0 @@ -/* tslint:disable */ -export class StorageDriver { - static set(key: string, value: string) { - localStorage.setItem(key, value); - } - static get(key: string): string { - return localStorage.getItem(key); - } - static remove(key: string): any { - localStorage.removeItem(key); - } -} diff --git a/lib/angular2/index.js b/lib/angular2/index.js index 638c7a1e..2fb937bb 100644 --- a/lib/angular2/index.js +++ b/lib/angular2/index.js @@ -11,10 +11,14 @@ var mkdirp = require('mkdirp'); var rmdir = require('rimraf'); var ejs = require('ejs'); var utils = require('../utils'); +var _ = require('underscore'); +_.mixin(require('underscore.inflections')); /** * EJS Q Filter + * Deprecated in EJS 2 :( */ ejs.filters.q = (obj) => JSON.stringify(obj, null, 2); +ejs.filters.pluralize = (text) => _.pluralize(text); /** * Generate Client SDK for the given loopback application. */ @@ -43,8 +47,9 @@ module.exports = function generate(ctx) { * Always, so we need to import from the right place */ ctx.loadAccessToken = (ctx.models.AccessToken ? false : true); + console.log('DRIVER: ', ctx.driver); /** - * LoopBack SDK Builder Schema for Angular 2 and NativeScript 2 + * LoopBack SDK Builder Schema for Angular 2 and ng2native 2 **/ let schema = [ /** @@ -56,7 +61,10 @@ module.exports = function generate(ctx) { params: { isIo: ctx.isIo, models: ctx.models, - buildModuleImports: buildModuleImports + driver: ctx.driver, + buildModuleImports, + buildNgModuleImports, + buildNgProviders } }, { @@ -82,6 +90,14 @@ module.exports = function generate(ctx) { output: '/services/core/index.ts', params: { isIo: ctx.isIo } }, + /** + * MODEL LIST SERVICES + */ + { + template: './shared/services/custom/models.ejs', + output: '/services/custom/SDKModels.ts', + params: { models: ctx.models } + }, /** * SDK CONFIG */ @@ -108,7 +124,8 @@ module.exports = function generate(ctx) { output: '/services/core/base.service.ts', params: { isIo: ctx.isIo, - buildBaseServiceImports: buildBaseServiceImports + buildServiceDI, + buildBaseServiceImports } }, { @@ -127,32 +144,57 @@ module.exports = function generate(ctx) { params: {} }, /** - * STORAGE DRIVER + * STORAGE */ { - template: './drivers/' + ctx.driver + '/storage.driver.ejs', - output: '/storage/storage.driver.ts', + template: './shared/storage/internal.storage.ts', + output: '/storage/internal.storage.ts', + params: {} + }, + { + template: './shared/storage/cookie.node.ts', + output: '/storage/cookie.node.ts', + params: {} + }, + { + template: './shared/storage/cookie.browser.ts', + output: '/storage/cookie.browser.ts', + params: {} + }, + { + template: './shared/storage/storage.native.ts', + output: '/storage/storage.native.ts', params: {} } ]; /** - * PUBSUB MODULE SUPPORT + * REALTIME MODULE SUPPORT */ if (ctx.isIo === 'enabled') { schema = schema.concat([ { - template: './drivers/' + ctx.driver + '/socket.driver.ejs', + template: './shared/sockets/connections.ts', + output: '/sockets/socket.connections.ts', + params: {} + }, + { + template: './shared/sockets/socket.browser.ts', + output: '/sockets/socket.browser.ts', + params: {} + }, + { + template: './shared/sockets/socket.driver.ts', output: '/sockets/socket.driver.ts', params: {} }, { - template: './shared/sockets/index.ejs', - output: '/sockets/index.ts', + template: './shared/sockets/socket.native.ts', + output: '/sockets/socket.native.ts', params: {} }, { - template: './shared/sockets/connections.ejs', - output: '/sockets/socket.connections.ts', + template: './shared/sockets/socket.node.ts', + output: '/sockets/socket.node.ts', params: {} }, { @@ -187,7 +229,7 @@ module.exports = function generate(ctx) { return; } else { console.info('LoopBack SDK Builder: adding %s model to SDK', modelName); - schema = schema.concat([ + schema.push( /** * SDK MODELS */ @@ -197,14 +239,23 @@ module.exports = function generate(ctx) { params: { model: ctx.models[modelName], modelName: modelName, + plural: ctx.models[modelName].sharedClass.ctor.settings.plural + || ejs.filters.pluralize(modelName), buildModelImports: buildModelImports, - buildModelProperties: buildModelProperties + buildModelProperties: buildModelProperties, + buildPropertyType: buildPropertyType, + buildPropertyDefaultValue: buildPropertyDefaultValue, + buildRelationType: buildRelationType, + buildModelImports, + buildModelProperties } - }, - /** - * SDK CUSTOM SERVICES - */ - { + } + ); + /** + * SDK CUSTOM SERVICES + */ + if (ctx.fireloopOnly === 'disabled' || (ctx.models[modelName].sharedClass.ctor.settings.base === 'User')) { + schema.push({ template: './shared/services/custom/service.ejs', output: '/services/custom/' + modelName + '.ts', params: { @@ -212,18 +263,19 @@ module.exports = function generate(ctx) { model: ctx.models[modelName], modelName: modelName, moduleName: ctx.moduleName, - buildPostBody: buildPostBody, - buildUrlParams: buildUrlParams, - buildRouteParams: buildRouteParams, loadAccessToken: ctx.loadAccessToken, - buildMethodParams: buildMethodParams, - buildServiceImports: buildServiceImports, - normalizeMethodName: normalizeMethodName, - buildObservableType: buildObservableType, - paramIsContext: paramIsContext + buildPostBody, + buildUrlParams, + buildRouteParams, + buildMethodParams, + buildServiceDI, + buildServiceImports, + normalizeMethodName, + buildObservableType, + paramIsContext } - } - ]); + }); + } } }); /** @@ -290,11 +342,17 @@ module.exports = function generate(ctx) { if (model.isUser && property === 'credentials') return; let meta = model.properties[property]; let isOptional = isInterface && !meta.required ? '?' : ''; - output.push(` ${property}${isOptional}: ${buildPropertyType(meta.type)};`); + let defaultValue = !isInterface ? ` = ${buildPropertyDefaultValue(meta)}` : ''; + defaultValue = ctx.defaultValue !== 'enabled' && ctx.defaultValue !== 'strict' ? '' : defaultValue; + defaultValue = ctx.defaultValue === 'strict' && !meta.hasOwnProperty('default') ? '' : defaultValue; + output.push(` ${property}${isOptional}: ${buildPropertyType(meta.type)}${defaultValue};`); }); // Add Model Relations Object.keys(model.sharedClass.ctor.relations).forEach(relation => { - output.push(` ${relation}${isInterface ? '?' : ''}: ${buildRelationType(model, relation)};`); + let relationType = buildRelationType( model, relation ); + let defaultTypeValue = !isInterface && ctx.defaultValue === 'enabled' && relationType.indexOf('Array') >= 0 ? ' = []' : ''; + defaultTypeValue = !isInterface && ctx.defaultValue === 'enabled' && relationType.indexOf('Array') === -1 ? ' = null' : defaultTypeValue; + output.push( ` ${relation}${isInterface ? '?' : ''}: ${relationType}${defaultTypeValue};` ); }); return output.join('\n'); } @@ -334,9 +392,11 @@ module.exports = function generate(ctx) { let imports = [ { module: 'Injectable, Inject, Optional', from: '@angular/core'}, { module: 'Http, Response', from: '@angular/http'}, + { module: 'SDKModels', from: './SDKModels'}, { module: 'BaseLoopBackApi', from: '../core/base.service'}, { module: 'LoopBackConfig', from: '../../lb.config'}, { module: 'LoopBackAuth', from: '../core/auth.service'}, + { module: 'SocketConnections', from: '../../sockets/socket.connections' }, { module: `LoopBackFilter, ${model.isUser ? `SDKToken${ (loadAccessToken && model.isUser) ? ', AccessToken' : '' }` : '' }`, from: '../../models/BaseModels' @@ -382,17 +442,39 @@ module.exports = function generate(ctx) { * @description * Define import statement for the SDK Module */ - function buildModuleImports(models, isIo) { + function buildModuleImports(models, isIo, driver) { let imports = [ { module: 'JSONSearchParams', from: './services/core/search.params'}, { module: 'ErrorHandler', from: './services/core/error.service'}, { module: 'LoopBackAuth', from: './services/core/auth.service'}, { module: 'LoggerService', from: './services/custom/logger.service'}, + { module: 'SDKModels', from: './services/custom/SDKModels'}, + { module: 'InternalStorage', from: './storage/internal.storage'}, + { module: 'SocketDriver', from: './sockets/socket.driver'}, + { module: 'SocketConnections', from: './sockets/socket.connections'}, { module: 'HttpModule', from: '@angular/http'}, { module: 'CommonModule', from: '@angular/common'}, { module: 'NgModule, ModuleWithProviders', from: '@angular/core'} ]; + switch (driver) { + case 'ng2web': + imports.push({ module: 'CookieBrowser', from: './storage/cookie.browser'}); + imports.push({ module: 'SocketBrowser', from: './sockets/socket.browser'}); + break; + case 'ng2universal': + imports.push({ module: 'CookieBrowser', from: './storage/cookie.browser'}); + imports.push({ module: 'CookieNode', from: './storage/cookie.node'}); + imports.push({ module: 'SocketBrowser', from: './sockets/socket.browser'}); + imports.push({ module: 'SocketNode', from: './sockets/socket.node'}); + break; + case 'ng2native': + imports.push({ module: 'StorageNative', from: './storage/storage.native'}); + imports.push({ module: 'SocketNative', from: './sockets/socket.native'}); + break; + } + + if (isIo === 'enabled') { imports.push({ module: 'RealTime', from: './services/core/real.time'}); } @@ -404,6 +486,65 @@ module.exports = function generate(ctx) { return buildImports(imports); } + /** + * @method buildNgModuleImports + * @description + * Define import statement for the SDK NG Modules + */ + function buildNgModuleImports(models, environment, isIo, driver) { + let imports = ['LoopBackAuth', 'LoggerService', 'JSONSearchParams', 'SDKModels']; + if (isIo === 'enabled') { imports.push('RealTime'); } + Object.keys(models).forEach(modelName => imports.push(`${ capitalize(modelName) }Api`)); + switch (environment) { + case 'browser': + if (driver === 'ng2web' || driver === 'ng2universal') { + imports.push('{ provide: InternalStorage, useClass: CookieBrowser }'); + imports.push('{ provide: SocketDriver, useClass: SocketBrowser }'); + } + break; + case 'node': + if (driver === 'ng2universal') { + imports.push('{ provide: InternalStorage, useClass: CookieNode }'); + imports.push('{ provide: SocketDriver, useClass: SocketNode }'); + } + break; + case 'ng2native': + if (driver === 'ng2native') { + imports.push('{ provide: InternalStorage, useClass: StorageNative }'); + imports.push('{ provide: SocketDriver, useClass: SocketNative }'); + } + break; + } + return imports.join(',\n '); + } + /** + * @method buildNgProviders + * @description + * Define import statement for the SDK NG Modules + */ + function buildNgProviders(isIo) { + let imports = ['ErrorHandler']; + if (isIo === 'enabled') { imports.push('SocketConnections'); } + return imports.join(',\n '); + } + /** + * @method buildServiceDI + * @description + * Define import statement for the SDK NG Modules + */ + function buildServiceDI(isIo) { + let dependencies = ['@Inject(Http) protected http: Http']; + if (isIo === 'enabled') { + dependencies.push('@Inject(SocketConnections) protected connections: SocketConnections'); + } + dependencies = dependencies.concat([ + '@Inject(SDKModels) protected models: SDKModels', + '@Inject(LoopBackAuth) protected auth: LoopBackAuth', + '@Inject(JSONSearchParams) protected searchParams: JSONSearchParams', + '@Optional() @Inject(ErrorHandler) protected errorHandler: ErrorHandler' + ]) + return dependencies.join(',\n '); + } /** * @method buildBaseServiceImports * @description @@ -419,6 +560,7 @@ module.exports = function generate(ctx) { { module: 'LoopBackAuth', from: './auth.service'}, { module: 'LoopBackConfig', from: '../../lb.config'}, { module: 'AccessToken', from: '../../models/index'}, + { module: 'SDKModels', from: '../custom/SDKModels'}, { module: 'Observable', from: 'rxjs/Observable' }, { module: 'ErrorObservable', from: 'rxjs/observable/ErrorObservable' }, { module: 'rxjs/add/operator/catch' }, @@ -644,10 +786,44 @@ module.exports = function generate(ctx) { return 'any'; } } + /* + * @author Julien Ledun , + * @license MIT + * @method buildPropertyDefaultValue + * @description + * Define defaults null values for class properties + */ + function buildPropertyDefaultValue(property) { + let defaultValue = ( property.hasOwnProperty('default') ) ? property.default : ''; + switch (typeof property.type) { + case 'function': + switch(property.type.name) { + case 'String': + return `'${defaultValue}'`; + case 'Number': + return isNaN( Number(defaultValue) ) ? 0 : Number( defaultValue ); + case 'Boolean': + return Boolean( defaultValue ); + case 'Date': + return isNaN( Date.parse( defaultValue ) ) ? `new Date(0)` : `new Date('${defaultValue}')`; + case 'GeoPoint': + default: + return "null"; + } + case 'object': + if(Array.isArray(property.type)) { + return "[]"; + } + return "null"; + default: + return "null"; + } + } }; + /** - * HELPERS - */ +* HELPERS +*/ function capitalize(string) { return string[0].toUpperCase() + string.slice(1); } diff --git a/lib/angular2/shared/index.ejs b/lib/angular2/shared/index.ejs index 6942f683..21ca391b 100644 --- a/lib/angular2/shared/index.ejs +++ b/lib/angular2/shared/index.ejs @@ -1,7 +1,8 @@ /** * @module SDKModule * @author Jonathan Casarrubias -* @license MTI 2016 Jonathan Casarrubias +* @license MIT 2016 Jonathan Casarrubias +* @version 2.1.0 * @description * The SDKModule is a generated Software Development Kit automatically built by * the LoopBack SDK Builder open source module. @@ -32,42 +33,91 @@ * export class AppModule { } * **/ -<%- buildModuleImports(models, isIo) %> - +<%- buildModuleImports(models, isIo, driver) %> +<% if ( driver === 'ng2web' || driver === 'ng2universal' ) { -%> +/** +* @module SDKBrowserModule +* @description +* This module should be imported when building a Web Application in the following scenarios: +* +* 1.- Regular web application +* 2.- Angular universal application (Browser Portion) +* 3.- Progressive applications (Angular Mobile, Ionic, WebViews, etc) +**/ @NgModule({ imports: [ CommonModule, HttpModule ], declarations: [ ], exports: [ ], - providers: [ ] + providers: [ + <%- buildNgProviders(isIo) %> + ] }) - -export class SDKModule { +export class SDKBrowserModule { static forRoot(): ModuleWithProviders { return { - ngModule: SDKModule, - providers: [ -<% if ( isIo === 'enabled' ){ -%> RealTime, - -<% } --%> LoopBackAuth, - - ErrorHandler, - LoggerService, - JSONSearchParams,<% - Object.keys(models).forEach(function(modelName, i, arr) { - modelName = modelName[0].toUpperCase() + modelName.slice(1); - %> - <%- modelName %>Api<%= i < arr.length -1 ? ',' : '' %><% - });%> + ngModule : SDKBrowserModule, + providers : [ + <%- buildNgModuleImports(models, 'browser', isIo, driver) %> ] }; } } - +<% } -%> +<% if ( driver === 'ng2universal' ) { -%> +/** +* @module SDKNodeModule +* @description +* This module should be imported when building a Angular Universal Application. +**/ +@NgModule({ + imports: [ CommonModule, HttpModule ], + declarations: [ ], + exports: [ ], + providers: [ + <%- buildNgProviders(isIo) %> + ] +}) +export class SDKNodeModule { + static forRoot(): ModuleWithProviders { + return { + ngModule : SDKNodeModule, + providers : [ + <%- buildNgModuleImports(models, 'node', isIo, driver) %> + ] + }; + } +} +<% } -%> +<% if ( driver === 'ng2native' ) { -%> +/** +* @module SDKNativeModule +* @description +* This module should be imported when building a NativeScript Applications. +**/ +@NgModule({ + imports: [ CommonModule, HttpModule ], + declarations: [ ], + exports: [ ], + providers: [ + <%- buildNgProviders(isIo) %> + ] +}) +export class SDKNativeModule { + static forRoot(): ModuleWithProviders { + return { + ngModule : SDKNativeModule, + providers : [ + <%- buildNgModuleImports(models, 'nativescript', isIo, driver) %> + ] + }; + } +} +<% } -%> +/** +* Have Fun!!! +* - Jon +**/ export * from './models/index'; export * from './services/index'; export * from './lb.config'; -<% if ( isIo === 'enabled' ){ -%>export * from './sockets/index'; -<% } --%> diff --git a/lib/angular2/shared/models/base.ejs b/lib/angular2/shared/models/base.ejs index cc875baf..c449db69 100644 --- a/lib/angular2/shared/models/base.ejs +++ b/lib/angular2/shared/models/base.ejs @@ -16,6 +16,7 @@ export interface LoopBackFilter { export interface AccessTokenInterface { id?: string; ttl?: number; + issuedAt?: any; created?: any; userId?: string; rememberMe?: boolean; @@ -24,9 +25,11 @@ export interface AccessTokenInterface { export class AccessToken implements AccessTokenInterface { id:string; ttl: number; - created: any; + issuedAt?: any; + created?: any; userId: string; user: any; + rememberMe: boolean = null; constructor(instance?: AccessToken) { Object.assign(this, instance); } @@ -35,7 +38,8 @@ export class AccessToken implements AccessTokenInterface { export class SDKToken extends AccessToken { id: any = null; ttl: number = null; - created: any = null; + issuedAt?: any = null; + created?: any = null; userId: any = null; user: any = null; rememberMe: boolean = null; @@ -56,5 +60,5 @@ export interface StatFilter { end: string }, where?: {}, - groypBy?: string + groupBy?: string } diff --git a/lib/angular2/shared/models/fireloop.ejs b/lib/angular2/shared/models/fireloop.ejs index 327a839a..f19d4ade 100644 --- a/lib/angular2/shared/models/fireloop.ejs +++ b/lib/angular2/shared/models/fireloop.ejs @@ -1,20 +1,16 @@ -import { LoopBackConfig } from '../lb.config'; -import { AccessToken, FireLoopRef } from './index'; -import { SocketConnections } from '../sockets/socket.connections'; +import { FireLoopRef } from './index'; export class FireLoop { - private socket: any; private references: any = {}; - constructor(token: AccessToken) { - this.socket = SocketConnections.getHandler(LoopBackConfig.getPath(), token); - } + constructor(private socket: any, private models: { get: Function }) {} - public ref(model: { getModelName(): string }): FireLoopRef { + public ref(model: any): FireLoopRef { let name: string = model.getModelName(); if (this.references[name]) { return this.references[name]; } - this.references[name] = new FireLoopRef(name, this.socket); + model.models = this.models; + this.references[name] = new FireLoopRef(model, this.socket); return this.references[name]; } } diff --git a/lib/angular2/shared/models/flref.ejs b/lib/angular2/shared/models/flref.ejs index bcf9bf2a..72ecc87b 100644 --- a/lib/angular2/shared/models/flref.ejs +++ b/lib/angular2/shared/models/flref.ejs @@ -1,126 +1,228 @@ import { Subject } from 'rxjs/Subject'; -import { Observable } from 'rxjs/Observable'; +import { Observable } from 'rxjs/Rx'; import { LoopBackFilter, StatFilter } from './index'; - +/** + * @class FireLoopRef + * @author Jonathan Casarrubias + * @license MIT + * @description + * This class allows to create FireLoop References which will be in sync with + * Server. It also allows to create FireLoop Reference Childs, that allows to + * persist data according the generic model relationships. + **/ export class FireLoopRef { - + // Reference ID + private id: number = Date.now() + this.buildId(); + // Model Instance (For child references, empty on root references) private instance: any; - private socket: any; - private name: string; - private current: { name: string }; - private parent: FireLoopRef; + // Model Childs private childs: any = {}; - private observables: any = {}; - - constructor(name: string, socket: any, parent: FireLoopRef = null, current = null) { - this.name = name; - this.current = current; - this.parent = parent; - this.socket = socket; - return this; - } - - private operation(event: string, data: any): Observable { - let id: number = Math.floor(Math.random() * 100800) * - Math.floor(Math.random() * 100700) * - Math.floor(Math.random() * 198500); - let subject: Subject = new Subject(); - let config: {id: any, data: any, current: any, parent: any } = { - id: id, - data: data, - current: this.current, - parent: this.parent && this.parent.instance ? this.parent.instance : null - }; - if (!this.parent || (this.parent && this.current)) { - this.socket.emit(`${this.name}.${event}`, config); - } else { - let interval = setInterval(() => { - if (this.current) { - config.current = this.current; - this.socket.emit(`${this.name}.${event}`, config); - clearInterval(interval); - } - }, 500); - } - this.socket.on(`${this.name}.value.result.${id}`, (res: any) => - subject.next(res.error ? Observable.throw(res.error) : res) + /** + * @method constructor + * @param model + * @param socket + * @param parent + * @param relationship + * @description + * The constructor will receive the required parameters and then will register this reference + * into the server, needed to allow multiple references for the same model. + * This ids are referenced into this specific client connection and won't have issues + * with other client ids. + **/ + constructor( + private model: any, + private socket: any, + private parent: any = null, + private relationship: any = null + ) { + this.socket.emit( + `Subscribe.${ !parent ? model.getModelName() : parent.model.getModelName() }`, + { id : this.id, scope: model.getModelName(), relationship: relationship } ); - return subject.asObservable(); + return this; } - + /** + * @method upsert + * @param data + * @description + * Operation wrapper for upsert function. + **/ public upsert(data: any): Observable { return this.operation('upsert', data); } - + /** + * @method upsert + * @param data + * @description + * Operation wrapper for create function. + **/ public create(data: any): Observable { return this.operation('create', data); } - + /** + * @method upsert + * @param data + * @description + * Operation wrapper for remove function. + **/ public remove(data: any): Observable { return this.operation('remove', data); } - + /** + * @method on + * @param event + * @param filter + * @description + * Listener for different type of events. Valid events are: + * - change (Triggers on any model change -create, update, remove-) + * - value (Triggers on new entries) + * - child_added (Triggers when a child is added) + * - child_updated (Triggers when a child is updated) + * - child_removed (Triggers when a child is removed) + **/ public on(event: string, filter: LoopBackFilter = { limit: 100, order: 'id DESC' }): Observable { - event = `${this.name}.${event}`; - if (this.observables[event]) { return this.observables[event]; } - let subject: Subject = new Subject(); + let request: any; + if (!this.relationship) { + event = `${ this.model.getModelName() }.${event}`; + request = { filter }; + } else { + event = `${ this.parent.model.getModelName() }.${ this.relationship }.${event}`; + request = { filter, parent: this.parent.instance }; + } if (event.match(/(value|change|stats)/)) { - this.pull(event, filter, subject); + return Observable.merge( + this.pull(event, request), + this.broadcasts(event, request) + ); + } else { + return this.broadcasts(event, request); } - // Listen for broadcast announces - this.socket.on( - // When there is a broadcast announce - `${event}.broadcast.announce`, - // We send a request containing the filtering options - () => this.socket.emit(`${event}.broadcast.request`, filter) - ); - // Once processed our request will return a unique result - this.socket.on(`${event}.broadcast`, (res: any) => subject.next(res)); - this.observables[event] = subject.asObservable(); - return this.observables[event]; - } + } + /** + * @method stats + * @param filter + * @description + * Listener for real-time statistics, will trigger on every + * statistic modification. + * TIP: You can improve performance by adding memcached to LoopBack models. + **/ public stats(filter?: StatFilter): Observable { - let event = `${this.name}.stats`; - if (this.observables[event]) { return this.observables[event]; } - let subject: Subject = new Subject(); - this.pull(event, filter, subject); + let event = `${this.model.getModelName()}.stats`; + let src_pull: Observable = this.pull(event, filter); // Listen for broadcast announces - this.socket.on( - // When there is a broadcast announce - `${event}.broadcast.announce`, - // We send a request containing the filtering options - () => this.socket.emit(`${event}.broadcast.request`, filter) - ); - // Once processed our request will return a unique result - this.socket.on(`${event}.broadcast`, (res: any) => subject.next(res)); - this.observables[event] = subject.asObservable(); - return this.observables[event]; - } - - private pull(event: string, filter: any, subject: Subject): void { - this.socket.emit(`${event}.pull.request`, filter); - this.socket.on(`${event}.pull.requested`, (res: any) => subject.next(res)); + let src_request: Observable = Observable.fromEvent(this.socket, `${event}.broadcast.announce`); + src_request.subscribe((res: T) => this.socket.emit(`${event}.broadcast.request`, filter)); + // Listen for broadcasted results + let src_broadcast: Observable = Observable.fromEvent(this.socket, `${event}.broadcast`); + return Observable.merge(src_pull, src_broadcast); } - + /** + * @method make + * @param instance + * @description + * This method will set a model instance into this current FireLoop Reference. + * This allows to persiste parentship when creating related instances. + **/ public make(instance: any): FireLoopRef { - this.instance = instance; - return this; + let reference: FireLoopRef = new FireLoopRef(this.model, this.socket); + reference.instance = instance; + return reference; } - - public child(name: string): FireLoopRef { - if (!this.parent) { - let childName = `${this.name}.${name}`; - if (this.childs[childName]) { return this.childs[childName]; } - this.socket.emit(`${this.name}.relation.request`, { relation: name }); - this.socket.on(`${this.name}.relation.request.result`, (Model: { name: string }) => { - this.childs[childName].current = Model; - }); - this.childs[childName] = new FireLoopRef(childName, this.socket, this); - return this.childs[childName]; + /** + * @method child + * @param relationship + * @description + * This method creates child references, which will persist related model + * instances. e.g. Room.messages, where messages belongs to a specific Room. + **/ + public child(relationship: string): FireLoopRef { + // Return singleton instance + if (this.childs[relationship]) { return this.childs[relationship]; } + // Try to get relation settings from current model + let settings: any = this.model.getModelDefinition().relations[relationship]; + // Verify the relationship actually exists + if (!settings) { + throw new Error(`Invalid model relationship ${ this.model.getModelName() } <-> ${ relationship }, verify your model settings.`); + } + // Verify if the relationship model is public + if (settings.model === '') { + throw new Error(`Relationship model is private, cam't use ${ relationship } unless you set your model as public.`); + } + // Lets get a model reference and add a reference for all of the models + let model: any = this.model.models.get(settings.model); + model.models = this.model.models; + // If everything goes well, we will store a child reference and return it. + this.childs[relationship] = new FireLoopRef(model, this.socket, this, relationship); + return this.childs[relationship]; + } + /** + * @method pull + * @param relationship + * @description + * This method will pull initial data from server + **/ + private pull(event: string, request: any): Observable { + let sbj: Subject = new Subject(); + let that: FireLoopRef = this; + let nowEvent: any = `${event}.pull.requested.${ this.id }`; + this.socket.emit(`${event}.pull.request.${ this.id }`, request); + function pullNow(data) { + that.socket.removeListener(nowEvent, pullNow); + sbj.next(data); + }; + this.socket.on(nowEvent, pullNow); + return sbj.asObservable(); + } + /** + * @method operation + * @param relationship + * @description + * This internal method will run operations depending on current context + **/ + private broadcasts(event: string, request: any): Observable { + let sbj: Subject = new Subject(); + this.socket.on( + `${event}.broadcast.announce.${ this.id }`, + (res: T) => + this.socket.emit(`${event}.broadcast.request.${ this.id }`, request) + ); + this.socket.on(`${ event }.broadcast.${ this.id }`, (data) => sbj.next(data)); + return sbj.asObservable(); + } + /** + * @method operation + * @param event + * @param data + * @description + * This internal method will run operations depending on current context + **/ + private operation(event: string, data: any): Observable { + if (!this.relationship) { + event = `${ this.model.getModelName() }.${event}.${ this.id }`; } else { - console.warn('Only 1 child level is supported'); - // TODO ADD UNLIMITED LEVELS + event = `${ this.parent.model.getModelName() }.${ this.relationship }.${ event }.${ this.id }`; } + let subject: Subject = new Subject(); + let config: { data: any, parent: any } = { + data, + parent: this.parent && this.parent.instance ? this.parent.instance : null + }; + this.socket.emit(event, config); + this.socket.on(`${ this.model.getModelName() }.value.result.${ this.id }`, (res: any) => + subject.next(res.error ? Observable.throw(res.error) : res) + ); + return subject.asObservable(); + } + /** + * @method buildId + * @description + * This internal method build an ID for this reference, this allows to have + * multiple references for the same model or relationships. + **/ + private buildId(): number { + return Math.floor(Math.random() * 100800) * + Math.floor(Math.random() * 100700) * + Math.floor(Math.random() * 198500); } } diff --git a/lib/angular2/shared/models/model.ejs b/lib/angular2/shared/models/model.ejs index e03c0f36..1e8f045f 100644 --- a/lib/angular2/shared/models/model.ejs +++ b/lib/angular2/shared/models/model.ejs @@ -7,8 +7,8 @@ export interface <%- modelName %>Interface { export class <%- modelName %> implements <%- modelName %>Interface { <%- buildModelProperties(model) %> - constructor(instance?: <%- modelName %>Interface) { - Object.assign(this, instance); + constructor(data?: <%- modelName %>Interface) { + Object.assign(this, data); } /** * The name of the model represented by this $resource, @@ -17,4 +17,40 @@ export class <%- modelName %> implements <%- modelName %>Interface { public static getModelName() { return <%-: modelName | q %>; } + /** + * @method factory + * @author Jonathan Casarrubias + * @license MIT + * This method creates an instance of <%- modelName %> for dynamic purposes. + **/ + public static factory(data: <%- modelName %>Interface): <%- modelName %>{ + return new <%- modelName %>(data); + } + /** + * @method getModelDefinition + * @author Julien Ledun + * @license MIT + * This method returns an object that represents some of the model + * definitions. + **/ + public static getModelDefinition() { + return { + name: '<%- modelName %>', + plural: '<%- plural %>', + properties: {<% for ( var prop in model.properties ) { %> + <%= prop %>: { + name: '<%= prop %>', + type: '<%= buildPropertyType( model.properties[prop].type ) %>'<% if ( model.properties[prop].hasOwnProperty( "default" ) ) { %>, + default: <%- buildPropertyDefaultValue( model.properties[prop] ) %><% } %> + },<% } %> + }, + relations: {<% for ( var rel in model.sharedClass.ctor.relations ) { %> + <%= rel %>: { + name: '<%= rel %>', + type: '<%- buildRelationType( model, rel ) %>', + model: '<%- model.sharedClass.ctor.relations[rel].targetClass %>' + },<% } %> + } + } + } } diff --git a/lib/angular2/shared/services/core/auth.ejs b/lib/angular2/shared/services/core/auth.ejs index 201aac61..e178f56f 100644 --- a/lib/angular2/shared/services/core/auth.ejs +++ b/lib/angular2/shared/services/core/auth.ejs @@ -1,11 +1,9 @@ /* tslint:disable */ declare var Object: any; -import { Injectable } from '@angular/core'; -import { StorageDriver } from '../../storage/storage.driver'; -import { SDKToken<% if (loadAccessToken) { %>, AccessToken<% } %> } from '../../models/BaseModels'; -<% if (!loadAccessToken) { %> -import { AccessToken } from '../../models/AccessToken'; -<% } %> +import { Injectable, Inject } from '@angular/core'; +import { InternalStorage } from '../../storage/internal.storage'; +import { SDKToken, AccessToken } from '../../models/BaseModels'; + /** * @module LoopBackAuth * @author Jonathan Casarrubias <@johncasarrubias> @@ -19,10 +17,13 @@ export class LoopBackAuth { private token: SDKToken = new SDKToken(); protected prefix: string = '$LoopBackSDK$'; - constructor() { + constructor(@Inject(InternalStorage) protected storage: InternalStorage) { this.token.id = this.load('id'); this.token.user = this.load('user'); this.token.userId = this.load('userId'); + this.token.issuedAt = this.load('issuedAt'); + this.token.created = this.load('created'); + this.token.ttl = this.load('ttl'); this.token.rememberMe = this.load('rememberMe'); } @@ -51,6 +52,9 @@ export class LoopBackAuth { this.persist('id', this.token.id); this.persist('user', this.token.user); this.persist('userId', this.token.userId); + this.persist('issuedAt', this.token.issuedAt); + this.persist('created', this.token.created); + this.persist('ttl', this.token.ttl); this.persist('rememberMe', this.token.rememberMe); } }; @@ -60,11 +64,11 @@ export class LoopBackAuth { } protected load(prop: string): any { - return StorageDriver.get(`${this.prefix}${prop}`); + return this.storage.get(`${this.prefix}${prop}`); } public clear(): void { - Object.keys(this.token).forEach((prop: string) => StorageDriver.remove(`${this.prefix}${prop}`)); + Object.keys(this.token).forEach((prop: string) => this.storage.remove(`${this.prefix}${prop}`)); this.token = new SDKToken(); } // I do not persist everything in 1 value because I want @@ -72,7 +76,7 @@ export class LoopBackAuth { // expected and will be easier to handle as will perform better. protected persist(prop: string, value: any): void { try { - StorageDriver.set( + this.storage.set( `${this.prefix}${prop}`, (typeof value === 'object') ? JSON.stringify(value) : value ); diff --git a/lib/angular2/shared/services/core/base.ejs b/lib/angular2/shared/services/core/base.ejs index 8e7c2b1e..d5d76c74 100644 --- a/lib/angular2/shared/services/core/base.ejs +++ b/lib/angular2/shared/services/core/base.ejs @@ -1,5 +1,21 @@ /* tslint:disable */ -<%- buildBaseServiceImports(isIo) %> +import { Injectable, Inject, Optional } from '@angular/core'; +import { Http, Headers, Request } from '@angular/http'; +import { NgModule, ModuleWithProviders } from '@angular/core'; +import { JSONSearchParams } from './search.params'; +import { ErrorHandler } from './error.service'; +import { LoopBackAuth } from './auth.service'; +import { LoopBackConfig } from '../../lb.config'; +import { LoopBackFilter, SDKToken, AccessToken } from '../../models/BaseModels'; +import { SDKModels } from '../custom/SDKModels'; +import { Observable } from 'rxjs/Observable'; +import { ErrorObservable } from 'rxjs/observable/ErrorObservable'; +import 'rxjs/add/operator/catch'; +import 'rxjs/add/operator/map'; +import { Subject } from 'rxjs/Subject'; +import { SocketConnections } from '../../sockets/socket.connections'; +// Making Sure EventSource Type is available to avoid compilation issues. +declare var EventSource: any; /** * @module BaseLoopBackApi * @author Nikolay Matiushenkov @@ -15,13 +31,18 @@ export abstract class BaseLoopBackApi { protected path: string; + protected model: any; constructor( @Inject(Http) protected http: Http, + @Inject(SocketConnections) protected connections: SocketConnections, + @Inject(SDKModels) protected models: SDKModels, @Inject(LoopBackAuth) protected auth: LoopBackAuth, @Inject(JSONSearchParams) protected searchParams: JSONSearchParams, @Optional() @Inject(ErrorHandler) protected errorHandler: ErrorHandler - ) {} + ) { + this.model = this.models.get(this.getModelName()); + } /** * Process request @@ -37,7 +58,7 @@ export abstract class BaseLoopBackApi { url : string, routeParams : any = {}, urlParams : any = {}, - postBody : any = null, + postBody : any = {}, isio : boolean = false ): Observable { @@ -59,7 +80,6 @@ export abstract class BaseLoopBackApi { routeParams[key] + "$1" ); } -<% if ( isIo === 'enabled' ){ -%> if (isio) { if (requestUrl.match(/fk/)) { @@ -71,12 +91,11 @@ export abstract class BaseLoopBackApi { let token: AccessToken = new AccessToken(); token.id = this.auth.getAccessTokenId(); token.userId = this.auth.getCurrentUserId(); - let socket: any = SocketConnections.getHandler(LoopBackConfig.getPath(), token); + let socket: any = this.connections.getHandler(LoopBackConfig.getPath(), token); socket.on(event, (res: any) => subject.next(res)); return subject.asObservable(); } - <% } -%> - + // Body fix for built in remote methods using "data", "options" or "credentials // that are the actual body, Custom remote method properties are different and need // to be wrapped into a body object @@ -87,13 +106,19 @@ export abstract class BaseLoopBackApi { } else { body = postBody; } + // Separate filter object from url params + let filter: string = ''; + if (urlParams.filter) { + filter = `?filter=${ encodeURI(JSON.stringify(urlParams.filter))}`; + delete urlParams.filter; + } + this.searchParams.setJSON(urlParams); let request: Request = new Request({ headers : headers, method : method, - url : urlParams.filter ? `${requestUrl}?filter=${ encodeURI(JSON.stringify(urlParams.filter))}` - : requestUrl, - search : !urlParams.filter && Object.keys(urlParams).length > 0 + url : `${requestUrl}${filter}`, + search : Object.keys(urlParams).length > 0 ? this.searchParams.getURLSearchParams() : null, body : body ? JSON.stringify(body) : undefined }); @@ -101,4 +126,253 @@ export abstract class BaseLoopBackApi { .map((res: any) => (res.text() != "" ? res.json() : {})) .catch(this.errorHandler.handleError); } + /** + * @method create + * @author Jonathan Casarrubias + * @license MIT + * @description + * Generic create method + */ + public create(data: any = {}): Observable { + return this.request('POST', [ + LoopBackConfig.getPath(), + LoopBackConfig.getApiVersion(), + this.model.getModelDefinition().plural + ].join('/'), undefined, undefined, { data }).map((data: T) => this.model.factory(data)); + } + /** + * @method create + * @author Jonathan Casarrubias + * @license MIT + * @description + * Generic create method + */ + public createMany(data: any = {}): Observable { + return this.request('POST', [ + LoopBackConfig.getPath(), + LoopBackConfig.getApiVersion(), + this.model.getModelDefinition().plural + ].join('/'), undefined, undefined, { data }) + .map((datum: T[]) => datum.map((data: T) => this.model.factory(data))); + } + /** + * @method findById + * @author Jonathan Casarrubias + * @license MIT + * @description + * Generic findById method + */ + public findById(id: any, filter: LoopBackFilter = {}): Observable { + let _urlParams: any = {}; + if (filter) _urlParams.filter = filter; + return this.request('GET', [ + LoopBackConfig.getPath(), + LoopBackConfig.getApiVersion(), + this.model.getModelDefinition().plural, + ':id' + ].join('/'), { id }, _urlParams, undefined).map((data: T) => this.model.factory(data)); + } + /** + * @method find + * @author Jonathan Casarrubias + * @license MIT + * @description + * Generic find method + */ + public find(filter: LoopBackFilter = {}): Observable { + return this.request('GET', [ + LoopBackConfig.getPath(), + LoopBackConfig.getApiVersion(), + this.model.getModelDefinition().plural + ].join('/'), undefined, { filter }, undefined) + .map((datum: T[]) => datum.map((data: T) => this.model.factory(data))); + } + /** + * @method exists + * @author Jonathan Casarrubias + * @license MIT + * @description + * Generic exists method + */ + public exists(id: any): Observable { + return this.request('GET', [ + LoopBackConfig.getPath(), + LoopBackConfig.getApiVersion(), + this.model.getModelDefinition().plural, + 'exists' + ].join('/'), { id }, undefined, undefined); + } + /** + * @method findOne + * @author Jonathan Casarrubias + * @license MIT + * @description + * Generic findOne method + */ + public findOne(filter: LoopBackFilter = {}): Observable { + return this.request('GET', [ + LoopBackConfig.getPath(), + LoopBackConfig.getApiVersion(), + this.model.getModelDefinition().plural, + 'findOne' + ].join('/'), undefined, { filter }, undefined).map((data: T) => this.model.factory(data)); + } + /** + * @method updateAll + * @author Jonathan Casarrubias + * @license MIT + * @description + * Generic updateAll method + */ + public updateAll(where: any = {}, data: T): Observable { + let _urlParams: any = {}; + if (where) _urlParams.where = where; + return this.request('POST', [ + LoopBackConfig.getPath(), + LoopBackConfig.getApiVersion(), + this.model.getModelDefinition().plural, + 'update' + ].join('/'), undefined, _urlParams, { data }) + .map((datum: T[]) => datum.map((data: T) => this.model.factory(data))); + } + /** + * @method deleteById + * @author Jonathan Casarrubias + * @license MIT + * @description + * Generic deleteById method + */ + public deleteById(id: any): Observable { + return this.request('DELETE', [ + LoopBackConfig.getPath(), + LoopBackConfig.getApiVersion(), + this.model.getModelDefinition().plural, + ':id' + ].join('/'), { id }, undefined, undefined).map((data: T) => this.model.factory(data)); + } + /** + * @method count + * @author Jonathan Casarrubias + * @license MIT + * @description + * Generic count method + */ + public count(where: any = {}): Observable<{ count: number }> { + let _urlParams: any = {}; + if (where) _urlParams.where = where; + return this.request('GET', [ + LoopBackConfig.getPath(), + LoopBackConfig.getApiVersion(), + this.model.getModelDefinition().plural, + 'count' + ].join('/'), undefined, _urlParams, undefined); + } + /** + * @method updateAttributes + * @author Jonathan Casarrubias + * @license MIT + * @description + * Generic updateAttributes method + */ + public updateAttributes(id: any, data: T): Observable { + return this.request('PUT', [ + LoopBackConfig.getPath(), + LoopBackConfig.getApiVersion(), + this.model.getModelDefinition().plural, + ':id' + ].join('/'), { id }, undefined, { data }).map((data: T) => this.model.factory(data)); + } + /** + * @method upsert + * @author Jonathan Casarrubias + * @license MIT + * @description + * Generic upsert method + */ + public upsert(data: any = {}): Observable { + return this.request('PUT', [ + LoopBackConfig.getPath(), + LoopBackConfig.getApiVersion(), + this.model.getModelDefinition().plural, + ].join('/'), undefined, undefined, { data }).map((data: T) => this.model.factory(data)); + } + /** + * @method upsertWithWhere + * @author Jonathan Casarrubias + * @license MIT + * @description + * Generic upsertWithWhere method + */ + public upsertWithWhere(where: any = {}, data: any = {}): Observable { + let _urlParams: any = {}; + if (where) _urlParams.where = where; + return this.request('PUT', [ + LoopBackConfig.getPath(), + LoopBackConfig.getApiVersion(), + this.model.getModelDefinition().plural, + 'upsertWithWhere' + ].join('/'), undefined, _urlParams, { data }).map((data: T) => this.model.factory(data)); + } + /** + * @method replaceOrCreate + * @author Jonathan Casarrubias + * @license MIT + * @description + * Generic replaceOrCreate method + */ + public replaceOrCreate(data: any = {}): Observable { + return this.request('PUT', [ + LoopBackConfig.getPath(), + LoopBackConfig.getApiVersion(), + this.model.getModelDefinition().plural, + 'replaceOrCreate' + ].join('/'), undefined, undefined, { data }).map((data: T) => this.model.factory(data)); + } + /** + * @method replaceById + * @author Jonathan Casarrubias + * @license MIT + * @description + * Generic replaceById method + */ + public replaceById(id: any, data: any = {}): Observable { + return this.request('POST', [ + LoopBackConfig.getPath(), + LoopBackConfig.getApiVersion(), + this.model.getModelDefinition().plural, + ':id', 'replace' + ].join('/'), undefined, undefined, { data }).map((data: T) => this.model.factory(data)); + } + /** + * @method createChangeStream + * @author Jonathan Casarrubias + * @license MIT + * @description + * Generic createChangeStream method + */ + public createChangeStream(): Observable { + let subject = new Subject(); + if (typeof EventSource !== 'undefined') { + let emit = (msg: any) => subject.next(JSON.parse(msg.data)); + var source = new EventSource([ + LoopBackConfig.getPath(), + LoopBackConfig.getApiVersion(), + this.model.getModelDefinition().plural, + 'change-stream' + ].join('/')); + source.addEventListener('data', emit); + source.onerror = emit; + } else { + console.warn('SDK Builder: EventSource is not supported'); + } + return subject.asObservable(); + } + /** + * @method getModelName + * @author Jonathan Casarrubias + * @license MIT + * @description + * Abstract getModelName method + */ + abstract getModelName(): string; } diff --git a/lib/angular2/shared/services/core/io.ejs b/lib/angular2/shared/services/core/io.ejs index 785e90dd..7f775a12 100644 --- a/lib/angular2/shared/services/core/io.ejs +++ b/lib/angular2/shared/services/core/io.ejs @@ -1,17 +1,12 @@ import { Subject } from 'rxjs/Subject'; import { Observable } from 'rxjs/Observable'; -import { AccessToken } from '../../models'; -import { LoopBackConfig } from '../../lb.config'; -import { SocketConnections } from '../../sockets/socket.connections'; export class IO { private socket: any; private observables: any = {}; - constructor(token: AccessToken) { - this.socket = SocketConnections.getHandler(LoopBackConfig.getPath(), token); - } + constructor(socket: any) { this.socket = socket; } emit(event: string, data: any): void { this.socket.emit('ME:RT:1://event', { diff --git a/lib/angular2/shared/services/core/realtime.ejs b/lib/angular2/shared/services/core/realtime.ejs index 18bf25de..f3fe65aa 100644 --- a/lib/angular2/shared/services/core/realtime.ejs +++ b/lib/angular2/shared/services/core/realtime.ejs @@ -2,8 +2,10 @@ import { Injectable, Inject } from '@angular/core'; import { IO } from './io.service'; import { JSONSearchParams } from './search.params'; import { LoopBackAuth } from './auth.service'; -import { AccessToken } from '../../models'; +import { LoopBackConfig } from '../../lb.config'; import { FireLoop } from '../../models/FireLoop'; +import { SocketConnections } from '../../sockets/socket.connections'; +import { SDKModels } from '../custom/SDKModels'; @Injectable() export class RealTime { @@ -12,11 +14,17 @@ export class RealTime { public FireLoop: FireLoop; constructor( + @Inject(SocketConnections) protected connections: SocketConnections, + @Inject(SDKModels) protected models: SDKModels, @Inject(LoopBackAuth) protected auth: LoopBackAuth, @Inject(JSONSearchParams) protected searchParams: JSONSearchParams ) { - let token: AccessToken = this.auth.getToken(); - this.IO = new IO(token); - this.FireLoop = new FireLoop(token); + let socket: any = this.getConnection(); + this.IO = new IO(socket); + this.FireLoop = new FireLoop(socket, models); + } + + getConnection(): void { + return this.connections.getHandler(LoopBackConfig.getPath(), this.auth.getToken()); } } diff --git a/lib/angular2/shared/services/custom/index.ejs b/lib/angular2/shared/services/custom/index.ejs index abcb4cbe..cd236cbd 100644 --- a/lib/angular2/shared/services/custom/index.ejs +++ b/lib/angular2/shared/services/custom/index.ejs @@ -6,4 +6,5 @@ -%> export * from './<%- modelName %>'; <% } // for modelName in models -%> +export * from './SDKModels'; export * from './logger.service'; diff --git a/lib/angular2/shared/services/custom/models.ejs b/lib/angular2/shared/services/custom/models.ejs new file mode 100644 index 00000000..6eb009c4 --- /dev/null +++ b/lib/angular2/shared/services/custom/models.ejs @@ -0,0 +1,22 @@ +/* tslint:disable */ +import { Injectable } from '@angular/core'; +<% for (var modelName in models) { + var meta = models[modelName]; + // capitalize the model name + modelName = modelName[0].toUpperCase() + modelName.slice(1); +-%> +import { <%- modelName %> } from '../../models/<%- modelName %>'; +<% } // for modelName in models -%> + +@Injectable() +export class SDKModels { + + private models: { [name: string]: any } = { + <% for ( modelName in models ) { %><%= modelName %>: <%= modelName %>, + <% } %> + }; + + public get(modelName: string): any { + return this.models[modelName]; + } +} diff --git a/lib/angular2/shared/services/custom/service.ejs b/lib/angular2/shared/services/custom/service.ejs index e0d73d61..6e715cfc 100644 --- a/lib/angular2/shared/services/custom/service.ejs +++ b/lib/angular2/shared/services/custom/service.ejs @@ -1,8 +1,6 @@ /* tslint:disable */ <%- buildServiceImports(model, loadAccessToken) %> -// Making Sure EventSource Type is available to avoid compilation issues. -declare var EventSource: any; /** * Api services for the `<%-: modelName %>` model. @@ -17,12 +15,9 @@ declare var EventSource: any; export class <%-: modelName %>Api extends BaseLoopBackApi { constructor( - @Inject(Http) http: Http, - @Inject(LoopBackAuth) protected auth: LoopBackAuth, - @Inject(JSONSearchParams) protected searchParams: JSONSearchParams, - @Optional() @Inject(ErrorHandler) errorHandler: ErrorHandler + <%- buildServiceDI(isIo) %> ) { - super(http, auth, searchParams, errorHandler); + super(http, <% if (isIo === 'enabled') { %> connections, <% } %> models, auth, searchParams, errorHandler); } <% model.methods.forEach(function(action) { @@ -30,27 +25,12 @@ export class <%-: modelName %>Api extends BaseLoopBackApi { var httpVerb = action.getEndpoints ? action.getEndpoints()[0].verb : action.getHttpMethod(); var fullPath = action.getEndpoints ? action.getEndpoints()[0].fullPath : action.getFullPath(); + // all of these methods are extended from base service + if (methodName.match(/(^create$|^createMany$|^find$|^replaceOrCreate$|^replaceById$|^upsert$|^upsertWithWhere$|^exists$|^findOne$|^findById$|^deleteById$|^updateAttributes$|^updateAll$|^count$|^createChangeStream$)/)) { return; } + if (!model.sharedClass.ctor.settings.sdk.blacklist[methodName]) { ngdocForMethod(modelName, methodName, action, httpVerb, fullPath); - if (methodName === 'createChangeStream') { -%> - public createChangeStream(): Observable { - let _url: string = LoopBackConfig.getPath() + "/" + LoopBackConfig.getApiVersion() + - <%-: fullPath | q %>; - let subject = new Subject(); - if (typeof EventSource !== 'undefined') { - let emit = (msg: any) => subject.next(JSON.parse(msg.data)); - var source = new EventSource(_url); - source.addEventListener('data', emit); - source.onerror = emit; - } else { - console.warn('SDK Builder: EventSource is not supported'); - } - return subject.asObservable(); - }<% - return; - } - // SET URL PARAMS var urlParams = action.accepts; // SET POST BODY @@ -76,7 +56,8 @@ export class <%-: modelName %>Api extends BaseLoopBackApi { let result = this.request(_method, _url, _routeParams, _urlParams, _postBody)<% if (model.isUser && methodName === 'login') { %> .map( - (response: SDKToken) => { + (response: any) => { + response.ttl = parseInt(response.ttl); response.rememberMe = rememberMe; this.auth.setUser(response); this.auth.save(); @@ -236,7 +217,7 @@ if (httpVerb == 'POST' || httpVerb == 'PUT' || httpVerb == 'PATCH') { params.forEach(function(arg) { -%> * * @param <%- getJsDocType(arg) %> <%- arg.arg %> <%- -(arg.description || '').replace(/\n/g, '\n * ') %> +(arg.description ? (Array.isArray(arg.description) ? arg.description.join('\n') : arg.description) : '').replace(/\n/g, '\n * ') %> <% if (model.isUser && methodName === 'login' && arg.arg === 'include') { -%> * Default value: `user`. <% } -%> @@ -261,7 +242,7 @@ if (httpVerb == 'POST' || httpVerb == 'PUT' || httpVerb == 'PATCH') { postData.forEach(function(arg) { -%> * * - `<%- arg.arg %>` – `{<%- getJsDocType(arg) %>}` - <%- -(arg.description || '').replace(/\n/g, '\n * ') %> +(arg.description ? (Array.isArray(arg.description) ? arg.description.join('\n') : arg.description) : '').replace(/\n/g, '\n * ') %> <% }); } } -%> @@ -288,9 +269,9 @@ postData.forEach(function(arg) { -%> <% action.returns.forEach(function(arg) { -%> * * - `<%- arg.arg %>` – `{<%- getJsDocType(arg) %>}` - <%- -(arg.description || '').replace(/\n/g, '\n * ') %> +(arg.description ? (Array.isArray(arg.description) ? arg.description.join('\n') : arg.description) : '').replace(/\n/g, '\n * ') %> <% }); } -%> */ -<% } // end of ngdocForMethod -%> \ No newline at end of file +<% } // end of ngdocForMethod -%> diff --git a/lib/angular2/shared/sockets/connections.ejs b/lib/angular2/shared/sockets/connections.ejs deleted file mode 100644 index 42e9f1fe..00000000 --- a/lib/angular2/shared/sockets/connections.ejs +++ /dev/null @@ -1,53 +0,0 @@ -/* tslint:disable */ -/** -* @author Jonathan Casarrubias -* @module SocketConnections -* @license MTI -* @description -* This module handle socket connections and return singleton instances for each -* connection, it will use the SDK Socket Driver Available currently supporting -* Angular 2 for web and NativeScript 2. -**/ -import { SocketDriver } from './socket.driver'; -import { AccessToken } from '../models'; -export class SocketConnections { - private static connections: any = {}; - private static configured: boolean = false; - static getHandler(url: string, token: AccessToken) { - if (!SocketConnections.connections[url]) { - console.log('Creating a new connection with: ', url); - let config: any = { log: false, secure: false, forceWebsockets: true }; - SocketConnections.connections[url] = SocketDriver.connect(url, config); - SocketConnections.connections[url].on('connect', () => { - if (!SocketConnections.configured) - SocketConnections.setupConnection(url, token, config); - }); - let forceConfig: any = setInterval(() => { - if (!SocketConnections.configured && SocketConnections.connections[url].connected) { - console.info('Forcing IO Configuration'); - SocketConnections.setupConnection(url, token, config); - clearInterval(forceConfig); - } else if (SocketConnections.configured) { - clearInterval(forceConfig); - } - }, 1000) - } else { - console.log('Reusing existing connection: ', url); - } - return SocketConnections.connections[url]; - } - - private static setupConnection(url: string, token: AccessToken, config: any): void { - SocketConnections.configured = true; - console.log('Connected to %s', url); - if(token.id) { - SocketConnections.connections[url].emit('authentication', token); - } - SocketConnections.connections[url].on('unauthorized', (res: any) => console.error('Unauthenticated', res)); - setInterval(() => SocketConnections.connections[url].emit('lb-ping'), 15000); - SocketConnections.connections[url].on('lb-pong', (data: any) => console.info('Heartbeat: ', data)); - SocketConnections.connections[url].on('disconnect', (data: any) => { - console.info('Unexpected disconnection from IO - Socket IO will try to reconnect'); - }); - } -} diff --git a/lib/angular2/shared/sockets/connections.ts b/lib/angular2/shared/sockets/connections.ts new file mode 100644 index 00000000..85a9361e --- /dev/null +++ b/lib/angular2/shared/sockets/connections.ts @@ -0,0 +1,56 @@ +/* tslint:disable */ +import { Injectable, Inject } from '@angular/core'; +import { SocketDriver } from './socket.driver'; +import { AccessToken } from '../models'; +/** +* @author Jonathan Casarrubias +* @module SocketConnections +* @license MTI +* @description +* This module handle socket connections and return singleton instances for each +* connection, it will use the SDK Socket Driver Available currently supporting +* Angular 2 for web and NativeScript 2. +**/ +@Injectable() +export class SocketConnections { + private connections: any = {}; + private configured: boolean = false; + constructor(@Inject(SocketDriver) private driver: SocketDriver) {} + getHandler(url: string, token: AccessToken) { + if (!this.connections[url]) { + console.log('Creating a new connection with: ', url); + let config: any = { log: false, secure: false, forceWebsockets: true }; + this.connections[url] = this.driver.connect(url, config); + this.connections[url].on('connect', () => { + if (!this.configured) + this.setupConnection(url, token, config); + }); + let forceConfig: any = setInterval(() => { + if (!this.configured && this.connections[url].connected) { + console.info('Forcing IO Configuration'); + this.setupConnection(url, token, config); + clearInterval(forceConfig); + } else if (this.configured) { + clearInterval(forceConfig); + } + }, 1000) + } else { + console.log('Reusing existing connection: ', url); + } + return this.connections[url]; + } + + private setupConnection(url: string, token: AccessToken, config: any): void { + this.configured = true; + console.log('Connected to %s', url); + if(token.id) { + this.connections[url].emit('authentication', token); + } + this.connections[url].on('unauthorized', (res: any) => console.error('Unauthenticated', res)); + setInterval(() => this.connections[url].emit('lb-ping'), 15000); + this.connections[url].on('lb-pong', (data: any) => console.info('Heartbeat: ', data)); + this.connections[url].on('disconnect', (data: any) => { + console.info('Unexpected disconnection from IO - Socket IO will try to reconnect'); + }); + } +} diff --git a/lib/angular2/shared/sockets/index.ejs b/lib/angular2/shared/sockets/index.ejs deleted file mode 100644 index a45e85f9..00000000 --- a/lib/angular2/shared/sockets/index.ejs +++ /dev/null @@ -1,2 +0,0 @@ -export * from './socket.driver'; -export * from './socket.connections'; diff --git a/lib/angular2/drivers/ng4web/socket.driver.ejs b/lib/angular2/shared/sockets/socket.browser.ts similarity index 57% rename from lib/angular2/drivers/ng4web/socket.driver.ejs rename to lib/angular2/shared/sockets/socket.browser.ts index 19d007e3..3cf06e96 100644 --- a/lib/angular2/drivers/ng4web/socket.driver.ejs +++ b/lib/angular2/shared/sockets/socket.browser.ts @@ -1,7 +1,7 @@ /* tslint:disable */ import * as io from 'socket.io-client'; -export class SocketDriver { - static connect(url: any, options: any) { +export class SocketBrowser { + connect(url: any, options: any) { return io(url, options); } } diff --git a/lib/angular2/shared/sockets/socket.driver.ts b/lib/angular2/shared/sockets/socket.driver.ts new file mode 100644 index 00000000..69b5c7bc --- /dev/null +++ b/lib/angular2/shared/sockets/socket.driver.ts @@ -0,0 +1,11 @@ +/** + * @module SocketDriver + * @author Jonathan Casarrubias + * @license MIT + * @description + * The SocketDriver class is used for dependency injection swapping. + * It will be provided using factory method from different sources. + **/ +export class SocketDriver { + connect(url: any, options: any) {} +} diff --git a/lib/angular2/shared/sockets/socket.native.ts b/lib/angular2/shared/sockets/socket.native.ts new file mode 100644 index 00000000..1f0232bd --- /dev/null +++ b/lib/angular2/shared/sockets/socket.native.ts @@ -0,0 +1,7 @@ +/* tslint:disable */ +var SocketIO = require('nativescript-socket.io'); +export class SocketNative { + connect(url: any, options: any) { + return SocketIO.connect(url, options); + } +} diff --git a/lib/angular2/shared/sockets/socket.node.ts b/lib/angular2/shared/sockets/socket.node.ts new file mode 100644 index 00000000..16abf4d4 --- /dev/null +++ b/lib/angular2/shared/sockets/socket.node.ts @@ -0,0 +1,7 @@ +/* tslint:disable */ +import * as io from 'socket.io-client'; +export class SocketNode { + connect(url: any, options: any) { + return io(url, options); + } +} diff --git a/lib/angular2/shared/storage/cookie.browser.ts b/lib/angular2/shared/storage/cookie.browser.ts new file mode 100644 index 00000000..baf0ad04 --- /dev/null +++ b/lib/angular2/shared/storage/cookie.browser.ts @@ -0,0 +1,44 @@ +import { Injectable } from '@angular/core'; +/** +* @module CookieBrowser +* @author Jonathan Casarrubias +* @license MIT +* @description +* Stand-alone cookie service for browsers +**/ +@Injectable() +export class CookieBrowser { + private cookies: { [key: string]: any } = {}; + get(key: string): any { + if (!this.cookies[key]) { + let cookie = window.document + .cookie.split('; ') + .filter((item: any) => item.split('=')[0] === key).pop(); + if (!cookie) { + return null; + } + + this.cookies[key] = this.parse(cookie.split('=').pop()); + } + + return this.cookies[key]; + } + + set(key: string, value: any, expires?: Date) { + this.cookies[key] = value; + let cookie = `${key}=${value}${expires ? `; expires=${ expires.toUTCString() }` : ''}`; + window.document.cookie = cookie; + } + + remove(key: string) { + document.cookie = key + '=; expires=Thu, 01 Jan 1970 00:00:01 GMT;'; + } + + private parse(value: any) { + try { + return JSON.parse(value); + } catch (e) { + return value; + } + } +} diff --git a/lib/angular2/shared/storage/cookie.node.ts b/lib/angular2/shared/storage/cookie.node.ts new file mode 100644 index 00000000..58b4bb91 --- /dev/null +++ b/lib/angular2/shared/storage/cookie.node.ts @@ -0,0 +1,19 @@ +declare var Zone: any; +import { Injectable } from '@angular/core'; + +@Injectable() +export class CookieNode { + + get(key: string) { + let cookies: { [key: string]: number } = Zone.current.get('req').cookies; + return cookies[key]; + } + + set(key: string, value: any): any { + Zone.current.get('res').cookies(key, value).send('Cookie is set'); + } + // Will this be really needed? + remove(key: string, value: any): any { + Zone.current.get('res').cookies(key, '; expires=Thu, 01 Jan 1970 00:00:01 GMT;').send('Cookie is removed'); + } +} diff --git a/lib/angular2/shared/storage/internal.storage.ts b/lib/angular2/shared/storage/internal.storage.ts new file mode 100644 index 00000000..ea25828c --- /dev/null +++ b/lib/angular2/shared/storage/internal.storage.ts @@ -0,0 +1,13 @@ +/** + * @module InternalStorage + * @author Jonathan Casarrubias + * @license MIT + * @description + * The InternalStorage class is used for dependency injection swapping. + * It will be provided using factory method from different sources. + **/ +export class InternalStorage { + get(key: string): any {} + set(key: string, value: any): any {} + remove(key: string): any {} +} diff --git a/lib/angular2/drivers/nativescript2/storage.driver.ejs b/lib/angular2/shared/storage/storage.native.ts similarity index 64% rename from lib/angular2/drivers/nativescript2/storage.driver.ejs rename to lib/angular2/shared/storage/storage.native.ts index be40f383..3368a31d 100644 --- a/lib/angular2/drivers/nativescript2/storage.driver.ejs +++ b/lib/angular2/shared/storage/storage.native.ts @@ -1,13 +1,16 @@ /* tslint:disable */ import * as AppSettings from 'application-settings'; -export class StorageDriver { - static set(key: string, value: any) { +import { Injectable } from '@angular/core'; + +@Injectable() +export class StorageNative { + set(key: string, value: any) { AppSettings.setString(key, String(value)); } - static get(key: string): any { + get(key: string): any { return AppSettings.getString(key); } - static remove(key: string): any { + remove(key: string): any { if (AppSettings.hasKey(key)) { AppSettings.remove(key); } else { diff --git a/package.json b/package.json index cc186dca..ba0b23d8 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@mean-expert/loopback-sdk-builder", - "version": "2.1.0-beta.17", + "version": "2.1.0-rc.1", "description": "Tool for auto-generating Software Development Kits (SDKs) for LoopBack", "bin": { "lb-sdk": "bin/lb-sdk" @@ -60,6 +60,21 @@ "name": "Miguel Serrano", "email": "miguelangelserrano4@gmail.com", "url": "https://github.com/Serranom4" + }, + { + "name": "Julien Ledun", + "email": "j.ledun@iosystems.fr", + "url": "https://github.com/jledun" + }, + { + "name": "Paul Robinson", + "email": "probinson@nextfaze.com", + "url": "https://github.com/viki53" + }, + { + "name": "Corentin Hatte", + "email": "contact@corentin-hatte.eu", + "url": "https://github.com/viki53" } ], "license": "MIT", @@ -74,7 +89,9 @@ "mkdirp": "0.5.1", "optimist": "0.6.1", "rimraf": "2.5.3", - "semver": "4.3.2" + "semver": "4.3.2", + "underscore": "^1.8.3", + "underscore.inflections": "^0.2.1" }, "devDependencies": {} } diff --git a/tests/angular2/common/models/account.json b/tests/angular2/common/models/account.json index d7d13307..cd839485 100644 --- a/tests/angular2/common/models/account.json +++ b/tests/angular2/common/models/account.json @@ -1,6 +1,7 @@ { "name": "Account", "base": "User", + "plural": "accounts", "idInjection": true, "options": { "validateUpsert": true diff --git a/tests/angular2/common/models/application-credential.json b/tests/angular2/common/models/application-credential.json index 8c1b09af..d8d8cd4d 100644 --- a/tests/angular2/common/models/application-credential.json +++ b/tests/angular2/common/models/application-credential.json @@ -11,10 +11,12 @@ "default": "authScheme" }, "authScheme": { - "type": "string" + "type": "string", + "default": "" }, "credentials": { - "type": "string" + "type": "string", + "default": "" }, "created": { "type": "date" diff --git a/tests/angular2/common/models/category.json b/tests/angular2/common/models/category.json index 75cfdedb..5fa66e08 100644 --- a/tests/angular2/common/models/category.json +++ b/tests/angular2/common/models/category.json @@ -7,7 +7,8 @@ }, "properties": { "name": { - "type": "string" + "type": "string", + "default": "test" } }, "validations": [], diff --git a/tests/angular2/common/models/message.json b/tests/angular2/common/models/message.json index 0d6aaf34..97188ce0 100644 --- a/tests/angular2/common/models/message.json +++ b/tests/angular2/common/models/message.json @@ -9,7 +9,8 @@ "properties": { "text": { "type": "string", - "required": true + "required": true, + "default": "" } }, "validations": [], diff --git a/tests/angular2/common/models/room.js b/tests/angular2/common/models/room.js index d3d30146..a6c9a501 100644 --- a/tests/angular2/common/models/room.js +++ b/tests/angular2/common/models/room.js @@ -1,5 +1,11 @@ module.exports = function (Room) { + Room.getPropertyValues = (property, filter, next) => { + let obj = {}; + obj[property] = filter; + next(null, obj); + }; + Room.greetRoute = greet; Room.remoteMethod( diff --git a/tests/angular2/common/models/room.json b/tests/angular2/common/models/room.json index 61a80b58..b5078f82 100644 --- a/tests/angular2/common/models/room.json +++ b/tests/angular2/common/models/room.json @@ -12,7 +12,8 @@ "properties": { "name": { "type": "string", - "required": true + "required": true, + "default": "" } }, "validations": [], @@ -46,5 +47,33 @@ } }, "acls": [], - "methods": {} + "methods": { + "getPropertyValues": { + "isStatic": true, + "accepts": [ + { + "arg": "property", + "type": "string", + "required": true, + "description": "Property name to lookup values for." + }, + { + "arg": "filter", + "type": "object", + "description": "Filter defining fields, where, include, order, offset, and limit" + } + ], + "returns": { + "type": [ + "String" + ], + "root": true + }, + "description": "Gets list of all unique values used for a given property.", + "http": { + "path": "/propertyValues", + "verb": "get" + } + } + } } diff --git a/tests/angular2/common/models/user-credential.json b/tests/angular2/common/models/user-credential.json index a7742527..28f76676 100644 --- a/tests/angular2/common/models/user-credential.json +++ b/tests/angular2/common/models/user-credential.json @@ -11,23 +11,27 @@ "default": "authScheme" }, "authScheme": { - "type": "string" + "type": "string", + "default": "" }, "externalId": { "type": "string", "default": "" }, "profile": { - "type": "object" + "type": "object", + "default": "" }, "credentials": { - "type": "string" + "type": "string", + "default": "" }, "created": { "type": "date" }, "modified": { - "type": "date" + "type": "date", + "default": "" }, "userId": { "type": "any" diff --git a/tests/angular2/common/models/user-identity.json b/tests/angular2/common/models/user-identity.json index fe80bfac..6bce1a3f 100644 --- a/tests/angular2/common/models/user-identity.json +++ b/tests/angular2/common/models/user-identity.json @@ -11,17 +11,20 @@ "default": "authScheme" }, "authScheme": { - "type": "string" + "type": "string", + "default": "" }, "externalId": { "type": "string", "default": "" }, "profile": { - "type": "object" + "type": "object", + "default": "" }, "credentials": { - "type": "string" + "type": "string", + "default": "" }, "created": { "type": "date" diff --git a/tests/angular2/loopback/config.json b/tests/angular2/loopback/config.json index 25353f74..e5854797 100644 --- a/tests/angular2/loopback/config.json +++ b/tests/angular2/loopback/config.json @@ -1,6 +1,5 @@ { - "restApiRoot": "/api", - "host": "0.0.0.0", + "host": "127.0.0.1", "port": 3000, "remoting": { "context": { diff --git a/tests/angular2/loopback/config.local.js b/tests/angular2/loopback/config.local.js new file mode 100644 index 00000000..1d4c9e4a --- /dev/null +++ b/tests/angular2/loopback/config.local.js @@ -0,0 +1,5 @@ +var p = require('../package.json'); +module.exports = { + "restApiRoot": `/${ p.version.split('.').shift() }`, + "port": 3002 +} diff --git a/tests/angular2/package.json b/tests/angular2/package.json index ac4034ca..7b600f7d 100644 --- a/tests/angular2/package.json +++ b/tests/angular2/package.json @@ -1,6 +1,6 @@ { "name": "angular2", - "version": "0.0.0", + "version": "2.1.0", "license": "MIT", "angular-cli": {}, "scripts": { @@ -10,7 +10,7 @@ "e2e": "protractor", "pretest": "ng lint", "test": "ng test --watch=false", - "build:sdk": "./node_modules/.bin/lb-sdk loopback/server.js src/app/shared/sdk -i enabled -w enabled" + "build:sdk": "./node_modules/.bin/lb-sdk loopback/server.js src/app/shared/sdk -i enabled -w enabled -v enabled -f disabled" }, "private": true, "dependencies": { @@ -22,7 +22,7 @@ "@angular/platform-browser": "2.0.0", "@angular/platform-browser-dynamic": "2.0.0", "@angular/router": "3.0.0", - "@mean-expert/loopback-component-realtime": "1.0.0-beta.8", + "@mean-expert/loopback-component-realtime": "^1.0.0-rc.1", "@types/socket.io-client": "^1.4.27", "compression": "^1.0.3", "config-chain": "^1.1.10", diff --git a/tests/angular2/src/app/access/access.component.ts b/tests/angular2/src/app/access/access.component.ts index 31826c7f..961d7553 100644 --- a/tests/angular2/src/app/access/access.component.ts +++ b/tests/angular2/src/app/access/access.component.ts @@ -35,7 +35,7 @@ export class AccessComponent implements OnInit { login() { this.accountApi.login(this.account, 'user', this.rememberMe).subscribe((token: AccessToken) => - this.router.navigate(['/room']) + this.router.navigate(['/']) ); } } diff --git a/tests/angular2/src/app/app.module.ts b/tests/angular2/src/app/app.module.ts index 99f27c21..d036543c 100644 --- a/tests/angular2/src/app/app.module.ts +++ b/tests/angular2/src/app/app.module.ts @@ -2,7 +2,7 @@ import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { FormsModule } from '@angular/forms'; import { AppComponent } from './app.component'; -import { SDKModule } from './shared/sdk/index'; +import { SDKBrowserModule } from './shared/sdk/index'; import { routing, appRoutingProviders } from './app.routing'; @NgModule({ @@ -12,7 +12,7 @@ import { routing, appRoutingProviders } from './app.routing'; imports: [ BrowserModule, FormsModule, - SDKModule.forRoot(), + SDKBrowserModule.forRoot(), routing ], providers : [ appRoutingProviders ], diff --git a/tests/angular2/src/app/app.routing.ts b/tests/angular2/src/app/app.routing.ts index 0a1849a0..c42658f8 100644 --- a/tests/angular2/src/app/app.routing.ts +++ b/tests/angular2/src/app/app.routing.ts @@ -8,7 +8,7 @@ const appRoutes: Routes = [ loadChildren: 'app/access/access.module#AccessModule' }, { - path: 'room', + path: '', loadChildren: 'app/room/room.module#RoomModule' } ]; diff --git a/tests/angular2/src/app/room-service.service.spec.ts b/tests/angular2/src/app/room-service.service.spec.ts index b87cabff..e254225a 100644 --- a/tests/angular2/src/app/room-service.service.spec.ts +++ b/tests/angular2/src/app/room-service.service.spec.ts @@ -1,7 +1,7 @@ /* tslint:disable:no-unused-variable */ import { TestBed, async, inject } from '@angular/core/testing'; -import { SDKModule } from './shared/sdk'; +import { SDKBrowserModule } from './shared/sdk'; import { Room, Category, Message, FireLoopRef } from './shared/sdk/models'; import { RoomApi, CategoryApi, MessageApi, RealTime } from './shared/sdk/services'; @@ -9,7 +9,7 @@ describe('Service: Room Service', () => { beforeEach(() => { TestBed.configureTestingModule({ imports: [ - SDKModule.forRoot() + SDKBrowserModule.forRoot() ] }); }); @@ -32,8 +32,7 @@ describe('Service: Room Service', () => { let room: Room = new Room(); room.name = Date.now().toString(); let ref: FireLoopRef = realTime.FireLoop.ref(Room); - let subscription = ref.on('child_added').subscribe((result: Room) => { - console.log(result); + let subscription = ref.on('child_added', { where: room }).subscribe((result: Room) => { expect(result.id).toBeTruthy(); expect(result.name).toBe(room.name); subscription.unsubscribe(); @@ -162,6 +161,16 @@ describe('Service: Room Service', () => { }) )); + it('should property and filter params', + async(inject([RoomApi], (roomApi: RoomApi) => { + let filter = { where: 'Yo' }; + return roomApi.getPropertyValues('newfilter', filter) + .subscribe((result: { newfilter: { where: string }}) => { + expect(filter.where).toBe(result.newfilter.where); + }); + }) + )); + it('should fetch greetings from route params', async(inject([RoomApi], (roomApi: RoomApi) => { let params = ['Hi', 'My Name Is', 'What']; diff --git a/tests/angular2/src/app/room/room.component.css b/tests/angular2/src/app/room/room.component.css deleted file mode 100644 index e69de29b..00000000 diff --git a/tests/angular2/src/app/room/room.component.html b/tests/angular2/src/app/room/room.component.html index 36ff7993..f6c6f925 100644 --- a/tests/angular2/src/app/room/room.component.html +++ b/tests/angular2/src/app/room/room.component.html @@ -1,21 +1,24 @@ - -

Update Email

-
- - -
-

Room Name

-
- - or -
+Return to rooms list +

Room Name {{ room.name }}

Messages

- - + +
    -
  • - {{ message.text }} +
  • + Message: {{ _message.text }} +
    + + +
    +
    ----------------------------------------------------
    + No Replies Added +
      +
    • + {{ _reply.text }} +
    • +
    +
    ===============================
\ No newline at end of file diff --git a/tests/angular2/src/app/room/room.component.ts b/tests/angular2/src/app/room/room.component.ts index 636b6750..77ca3727 100644 --- a/tests/angular2/src/app/room/room.component.ts +++ b/tests/angular2/src/app/room/room.component.ts @@ -1,73 +1,79 @@ -import { Component, OnInit } from '@angular/core'; -import { Room, Account, FireLoopRef } from '../shared/sdk/models'; -import { AccountApi, RoomApi, LoggerService, RealTime } from '../shared/sdk/services'; -import { Router } from '@angular/router'; +import { Component, OnInit, OnDestroy } from '@angular/core'; +import { Room, Message, FireLoopRef } from '../shared/sdk/models'; +import { LoggerService, RealTime, SDKModels } from '../shared/sdk/services'; +import { Router, ActivatedRoute } from '@angular/router'; import { Subscription } from 'rxjs'; @Component({ selector: 'app-room', templateUrl: 'room.component.html' }) -export class RoomComponent implements OnInit { +export class RoomComponent implements OnInit, OnDestroy { - private logged: Account; - private accountRef: FireLoopRef; + private roomRef: FireLoopRef; + private message: Message = new Message(); + private messageRef: FireLoopRef; + private replyRefs: { [key: number]: FireLoopRef } = {}; private room: Room = new Room(); - private subscription: Subscription; + private subscriptions: Subscription[] = new Array(); constructor( - private accountApi: AccountApi, - private roomApi: RoomApi, + private route: ActivatedRoute, private router: Router, private logger: LoggerService, - private realTime: RealTime + private realTime: RealTime, + private models: SDKModels ) { this.logger.info('Room Module Loaded'); - this.logged = this.accountApi.getCachedCurrent(); - this.accountRef = this.realTime.FireLoop.ref(Account); + this.roomRef = realTime.FireLoop.ref(Room); } - ngOnInit() {} - - logout(): void { - this.accountApi.logout().subscribe(res => this.router.navigate(['/access'])); + ngOnInit() { + this.route.params.subscribe((room: Room) => { + this.subscriptions.push(this.roomRef.on('value', { + where: { id: room.id } + }).subscribe((list: Room[]) => { + this.room = list.pop(); + this.messageRef = this.roomRef.make(this.room).child('messages'); + this.listenMessages(); + }, err => alert(err.message))); + }); } - update(): void { - this.accountRef.upsert(this.logged).subscribe(res => console.log(res)); + ngOnDestroy() { + this.subscriptions.forEach((subscription: Subscription) => subscription.unsubscribe()); + this.roomRef = null; + this.messageRef = null; + this.replyRefs = {}; } - create(): void { - this.roomApi.create(this.room).subscribe((room: Room) => { - this.room = room; - this.listen(); - }); + send(): void { + this.messageRef.create(this.message).subscribe((instance: Message) => { + this.logger.info('Message stored'); + this.replyRefs[instance.id] = this.messageRef.make(instance).child('replies'); + this.message = new Message(); + }).unsubscribe(); } - join(): void { - this.roomApi.findOne({ - where: { name: this.room.name }, - include: 'messages' - }).subscribe((room: Room) => { - this.room = room; - this.listen(); - }, err => alert(err.message)); - } - // We usually would use a Message model, but for testing purposes... The Message model - // is private, therefore is not exposed to the SDK, that is expected in this test app - // to address that use case. I don't recommend to follow the below as an example as I - // would normally use the Message model exposed, like we did with Room. (JC)' - send(message: string): void { - this.roomApi.createMessages(this.room.id, { - text: message - }).subscribe(instance => this.logger.info('Message stored')); + sendReply(parent: Message, text: string): void { + this.replyRefs[parent.id].create(new Message({ text: text })).subscribe((instance: Message) => { + this.logger.info('Reply stored'); + text = ''; + }).unsubscribe(); } - listen() { - if (this.subscription) { this.subscription.unsubscribe(); } - this.subscription = this.roomApi.onCreateMessages(this.room.id).subscribe((message: any) => { - this.room.messages = Array.isArray(this.room.messages) ? this.room.messages : []; - this.room.messages.push(message); - }); + listenMessages() { + this.subscriptions.push( + this.messageRef.on('change') + .subscribe((messages: Message[]) => { + this.room.messages = messages; + this.room.messages.forEach((message: Message) => { + this.replyRefs[message.id] = this.messageRef.make(message).child('replies'); + this.subscriptions.push(this.replyRefs[message.id].on('change').subscribe((replies: Message[]) => { + message.replies = replies; + })); + }); + }) + ); } } diff --git a/tests/angular2/src/app/room/room.list.component.html b/tests/angular2/src/app/room/room.list.component.html new file mode 100644 index 00000000..39aab7f7 --- /dev/null +++ b/tests/angular2/src/app/room/room.list.component.html @@ -0,0 +1,17 @@ + +

Update Email

+
+ + +
+

Room Name {{ room.name }}

+
+ + +
+

Rooms

+
    +
  • + {{ _room.name }} +
  • +
\ No newline at end of file diff --git a/tests/angular2/src/app/room/room.list.component.ts b/tests/angular2/src/app/room/room.list.component.ts new file mode 100644 index 00000000..44b58499 --- /dev/null +++ b/tests/angular2/src/app/room/room.list.component.ts @@ -0,0 +1,64 @@ +import { Component, OnInit, OnDestroy } from '@angular/core'; +import { Room, Account, FireLoopRef } from '../shared/sdk/models'; +// import { AccountApi, RoomApi, LoggerService, RealTime } from '../shared/sdk/services'; +import { AccountApi, RoomApi, LoggerService, RealTime, SDKModels } from '../shared/sdk/services'; +import { Router } from '@angular/router'; +import { Subscription } from 'rxjs'; +@Component({ + selector: 'app-room', + templateUrl: 'room.list.component.html' +}) + +export class RoomListComponent implements OnInit, OnDestroy { + + private logged: Account; + private accountRef: FireLoopRef; + private roomRef: FireLoopRef; + private room: Room = new Room(); + private rooms: Room[]; + private subscriptions: Subscription[] = new Array(); + + constructor( + private accountApi: AccountApi, + private roomApi: RoomApi, + private router: Router, + private logger: LoggerService, + private realTime: RealTime, + private models: SDKModels + ) { + this.logger.info('Room Module Loaded'); + this.logged = this.accountApi.getCachedCurrent(); + this.accountRef = this.realTime.FireLoop.ref(Account); + this.roomRef = this.realTime.FireLoop.ref(Room); + } + + ngOnInit() { + console.log('here'); + this.subscriptions.push(this.roomRef.on('change').subscribe((rooms: Room[]) => this.rooms = rooms)); + this.subscriptions.push(this.roomRef.on('child_added').subscribe((child: Room) => { + console.log('CHILD ADDED: ', child); + })); + } + + ngOnDestroy() { + this.subscriptions.forEach((subscription: Subscription) => subscription.unsubscribe()); + } + + logout(): void { + this.accountApi.logout().subscribe(res => this.router.navigate(['/access'])); + } + + update(): void { + this.accountRef.upsert(this.logged).subscribe(res => console.log(res)); + } + + create(): void { + this.roomRef.create(this.room).subscribe((room: Room) => { + this.room = new Room(); + }); + } + + join(_room): void { + this.router.navigate(['/room', _room.id]); + } +} diff --git a/tests/angular2/src/app/room/room.module.ts b/tests/angular2/src/app/room/room.module.ts index 5f0f0b69..22c1ab4a 100644 --- a/tests/angular2/src/app/room/room.module.ts +++ b/tests/angular2/src/app/room/room.module.ts @@ -1,5 +1,6 @@ import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; +import { RoomListComponent } from './room.list.component'; import { RoomComponent } from './room.component'; import { roomRouting } from './room.routing'; import { FormsModule } from '@angular/forms'; @@ -10,6 +11,6 @@ import { FormsModule } from '@angular/forms'; FormsModule, roomRouting ], - declarations: [RoomComponent] + declarations: [ RoomListComponent, RoomComponent ] }) export class RoomModule { } diff --git a/tests/angular2/src/app/room/room.routing.ts b/tests/angular2/src/app/room/room.routing.ts index 736ca8d8..391d88a3 100644 --- a/tests/angular2/src/app/room/room.routing.ts +++ b/tests/angular2/src/app/room/room.routing.ts @@ -1,11 +1,17 @@ import { ModuleWithProviders } from '@angular/core'; import { Routes, RouterModule } from '@angular/router'; +import { RoomListComponent } from './room.list.component'; import { RoomComponent } from './room.component'; import { AuthGuard } from '../shared/auth.guard'; const roomRoutes: Routes = [ { path: '', + component: RoomListComponent, + canActivate: [ AuthGuard ] + }, + { + path: 'room/:id', component: RoomComponent, canActivate: [ AuthGuard ] } diff --git a/tests/angular2/src/app/shared/sdk/index.ts b/tests/angular2/src/app/shared/sdk/index.ts index d95c157a..a5f88034 100644 --- a/tests/angular2/src/app/shared/sdk/index.ts +++ b/tests/angular2/src/app/shared/sdk/index.ts @@ -1,7 +1,8 @@ /** * @module SDKModule * @author Jonathan Casarrubias -* @license MTI 2016 Jonathan Casarrubias +* @license MIT 2016 Jonathan Casarrubias +* @version 2.1.0 * @description * The SDKModule is a generated Software Development Kit automatically built by * the LoopBack SDK Builder open source module. @@ -36,9 +37,15 @@ import { JSONSearchParams } from './services/core/search.params'; import { ErrorHandler } from './services/core/error.service'; import { LoopBackAuth } from './services/core/auth.service'; import { LoggerService } from './services/custom/logger.service'; +import { SDKModels } from './services/custom/SDKModels'; +import { InternalStorage } from './storage/internal.storage'; +import { SocketDriver } from './sockets/socket.driver'; +import { SocketConnections } from './sockets/socket.connections'; import { HttpModule } from '@angular/http'; import { CommonModule } from '@angular/common'; import { NgModule, ModuleWithProviders } from '@angular/core'; +import { CookieBrowser } from './storage/cookie.browser'; +import { SocketBrowser } from './sockets/socket.browser'; import { RealTime } from './services/core/real.time'; import { UserApi } from './services/custom/User'; import { RoomApi } from './services/custom/Room'; @@ -51,24 +58,34 @@ import { AccountApi } from './services/custom/Account'; import { RoomAccountApi } from './services/custom/RoomAccount'; import { StorageApi } from './services/custom/Storage'; import { CoreApi } from './services/custom/Core'; - +/** +* @module SDKBrowserModule +* @description +* This module should be imported when building a Web Application in the following scenarios: +* +* 1.- Regular web application +* 2.- Angular universal application (Browser Portion) +* 3.- Progressive applications (Angular Mobile, Ionic, WebViews, etc) +**/ @NgModule({ imports: [ CommonModule, HttpModule ], declarations: [ ], exports: [ ], - providers: [ ] + providers: [ + ErrorHandler, + SocketConnections + ] }) - -export class SDKModule { +export class SDKBrowserModule { static forRoot(): ModuleWithProviders { return { - ngModule: SDKModule, - providers: [ - RealTime, + ngModule : SDKBrowserModule, + providers : [ LoopBackAuth, - ErrorHandler, LoggerService, JSONSearchParams, + SDKModels, + RealTime, UserApi, RoomApi, MessageApi, @@ -79,13 +96,18 @@ export class SDKModule { AccountApi, RoomAccountApi, StorageApi, - CoreApi + CoreApi, + { provide: InternalStorage, useClass: CookieBrowser }, + { provide: SocketDriver, useClass: SocketBrowser } ] }; } } - +/** +* Have Fun!!! +* - Jon +**/ export * from './models/index'; export * from './services/index'; export * from './lb.config'; -export * from './sockets/index'; + diff --git a/tests/angular2/src/app/shared/sdk/lb.config.ts b/tests/angular2/src/app/shared/sdk/lb.config.ts index c73d7757..7439e0c5 100644 --- a/tests/angular2/src/app/shared/sdk/lb.config.ts +++ b/tests/angular2/src/app/shared/sdk/lb.config.ts @@ -20,8 +20,8 @@ * } **/ export class LoopBackConfig { - private static path: string = '//0.0.0.0:3000'; - private static version: string | number = 'api'; + private static path: string = '//127.0.0.1:3002'; + private static version: string | number = '2'; private static authPrefix: string = ''; private static debug: boolean = true; diff --git a/tests/angular2/src/app/shared/sdk/models/Account.ts b/tests/angular2/src/app/shared/sdk/models/Account.ts index 23713c17..11addff0 100644 --- a/tests/angular2/src/app/shared/sdk/models/Account.ts +++ b/tests/angular2/src/app/shared/sdk/models/Account.ts @@ -22,22 +22,22 @@ export interface AccountInterface { } export class Account implements AccountInterface { - realm: string; - username: string; - password: string; - challenges: any; - email: string; - emailVerified: boolean; - verificationToken: string; - status: string; - created: Date; - lastUpdated: Date; - id: number; - accessTokens: Array; - rooms: Array; - administrations: Array; - constructor(instance?: AccountInterface) { - Object.assign(this, instance); + realm: string = ''; + username: string = ''; + password: string = ''; + challenges: any = null; + email: string = ''; + emailVerified: boolean = false; + verificationToken: string = ''; + status: string = ''; + created: Date = new Date(0); + lastUpdated: Date = new Date(0); + id: number = 0; + accessTokens: Array = []; + rooms: Array = []; + administrations: Array = []; + constructor(data?: AccountInterface) { + Object.assign(this, data); } /** * The name of the model represented by this $resource, @@ -46,4 +46,93 @@ export class Account implements AccountInterface { public static getModelName() { return "Account"; } + /** + * @method factory + * @author Jonathan Casarrubias + * @license MIT + * This method creates an instance of Account for dynamic purposes. + **/ + public static factory(data: AccountInterface): Account{ + return new Account(data); + } + /** + * @method getModelDefinition + * @author Julien Ledun + * @license MIT + * This method returns an object that represents some of the model + * definitions. + **/ + public static getModelDefinition() { + return { + name: 'Account', + plural: 'accounts', + properties: { + realm: { + name: 'realm', + type: 'string' + }, + username: { + name: 'username', + type: 'string' + }, + password: { + name: 'password', + type: 'string' + }, + credentials: { + name: 'credentials', + type: 'any' + }, + challenges: { + name: 'challenges', + type: 'any' + }, + email: { + name: 'email', + type: 'string' + }, + emailVerified: { + name: 'emailVerified', + type: 'boolean' + }, + verificationToken: { + name: 'verificationToken', + type: 'string' + }, + status: { + name: 'status', + type: 'string' + }, + created: { + name: 'created', + type: 'Date' + }, + lastUpdated: { + name: 'lastUpdated', + type: 'Date' + }, + id: { + name: 'id', + type: 'number' + }, + }, + relations: { + accessTokens: { + name: 'accessTokens', + type: 'Array', + model: '' + }, + rooms: { + name: 'rooms', + type: 'Array', + model: 'Room' + }, + administrations: { + name: 'administrations', + type: 'Array', + model: 'Room' + }, + } + } + } } diff --git a/tests/angular2/src/app/shared/sdk/models/ApplicationCredential.ts b/tests/angular2/src/app/shared/sdk/models/ApplicationCredential.ts index 62896242..2ef56018 100644 --- a/tests/angular2/src/app/shared/sdk/models/ApplicationCredential.ts +++ b/tests/angular2/src/app/shared/sdk/models/ApplicationCredential.ts @@ -12,15 +12,15 @@ export interface ApplicationCredentialInterface { } export class ApplicationCredential implements ApplicationCredentialInterface { - provider: string; - authScheme: string; - credentials: string; - created: Date; - modified: Date; - userId: any; - id: number; - constructor(instance?: ApplicationCredentialInterface) { - Object.assign(this, instance); + provider: string = 'authScheme'; + authScheme: string = ''; + credentials: string = ''; + created: Date = new Date(0); + modified: Date = new Date(0); + userId: any = null; + id: number = 0; + constructor(data?: ApplicationCredentialInterface) { + Object.assign(this, data); } /** * The name of the model represented by this $resource, @@ -29,4 +29,61 @@ export class ApplicationCredential implements ApplicationCredentialInterface { public static getModelName() { return "ApplicationCredential"; } + /** + * @method factory + * @author Jonathan Casarrubias + * @license MIT + * This method creates an instance of ApplicationCredential for dynamic purposes. + **/ + public static factory(data: ApplicationCredentialInterface): ApplicationCredential{ + return new ApplicationCredential(data); + } + /** + * @method getModelDefinition + * @author Julien Ledun + * @license MIT + * This method returns an object that represents some of the model + * definitions. + **/ + public static getModelDefinition() { + return { + name: 'ApplicationCredential', + plural: 'ApplicationCredentials', + properties: { + provider: { + name: 'provider', + type: 'string', + default: 'authScheme' + }, + authScheme: { + name: 'authScheme', + type: 'string', + default: '' + }, + credentials: { + name: 'credentials', + type: 'string', + default: '' + }, + created: { + name: 'created', + type: 'Date' + }, + modified: { + name: 'modified', + type: 'Date' + }, + userId: { + name: 'userId', + type: 'any' + }, + id: { + name: 'id', + type: 'number' + }, + }, + relations: { + } + } + } } diff --git a/tests/angular2/src/app/shared/sdk/models/BaseModels.ts b/tests/angular2/src/app/shared/sdk/models/BaseModels.ts index 9a6cabd2..29605fe4 100644 --- a/tests/angular2/src/app/shared/sdk/models/BaseModels.ts +++ b/tests/angular2/src/app/shared/sdk/models/BaseModels.ts @@ -14,6 +14,7 @@ export interface LoopBackFilter { export interface AccessTokenInterface { id?: string; ttl?: number; + issuedAt?: any; created?: any; userId?: string; rememberMe?: boolean; @@ -22,9 +23,11 @@ export interface AccessTokenInterface { export class AccessToken implements AccessTokenInterface { id:string; ttl: number; - created: any; + issuedAt?: any; + created?: any; userId: string; user: any; + rememberMe: boolean = null; constructor(instance?: AccessToken) { Object.assign(this, instance); } @@ -33,7 +36,8 @@ export class AccessToken implements AccessTokenInterface { export class SDKToken extends AccessToken { id: any = null; ttl: number = null; - created: any = null; + issuedAt?: any = null; + created?: any = null; userId: any = null; user: any = null; rememberMe: boolean = null; @@ -54,5 +58,5 @@ export interface StatFilter { end: string }, where?: {}, - groypBy?: string + groupBy?: string } diff --git a/tests/angular2/src/app/shared/sdk/models/Category.ts b/tests/angular2/src/app/shared/sdk/models/Category.ts index 0024be95..07b510ff 100644 --- a/tests/angular2/src/app/shared/sdk/models/Category.ts +++ b/tests/angular2/src/app/shared/sdk/models/Category.ts @@ -11,11 +11,11 @@ export interface CategoryInterface { } export class Category implements CategoryInterface { - name: string; - id: number; - rooms: Array; - constructor(instance?: CategoryInterface) { - Object.assign(this, instance); + name: string = 'test'; + id: number = 0; + rooms: Array = []; + constructor(data?: CategoryInterface) { + Object.assign(this, data); } /** * The name of the model represented by this $resource, @@ -24,4 +24,44 @@ export class Category implements CategoryInterface { public static getModelName() { return "Category"; } + /** + * @method factory + * @author Jonathan Casarrubias + * @license MIT + * This method creates an instance of Category for dynamic purposes. + **/ + public static factory(data: CategoryInterface): Category{ + return new Category(data); + } + /** + * @method getModelDefinition + * @author Julien Ledun + * @license MIT + * This method returns an object that represents some of the model + * definitions. + **/ + public static getModelDefinition() { + return { + name: 'Category', + plural: 'Categories', + properties: { + name: { + name: 'name', + type: 'string', + default: 'test' + }, + id: { + name: 'id', + type: 'number' + }, + }, + relations: { + rooms: { + name: 'rooms', + type: 'Array', + model: 'Room' + }, + } + } + } } diff --git a/tests/angular2/src/app/shared/sdk/models/Core.ts b/tests/angular2/src/app/shared/sdk/models/Core.ts index b69e88e2..94421943 100644 --- a/tests/angular2/src/app/shared/sdk/models/Core.ts +++ b/tests/angular2/src/app/shared/sdk/models/Core.ts @@ -6,9 +6,9 @@ export interface CoreInterface { } export class Core implements CoreInterface { - id: number; - constructor(instance?: CoreInterface) { - Object.assign(this, instance); + id: number = 0; + constructor(data?: CoreInterface) { + Object.assign(this, data); } /** * The name of the model represented by this $resource, @@ -17,4 +17,34 @@ export class Core implements CoreInterface { public static getModelName() { return "Core"; } + /** + * @method factory + * @author Jonathan Casarrubias + * @license MIT + * This method creates an instance of Core for dynamic purposes. + **/ + public static factory(data: CoreInterface): Core{ + return new Core(data); + } + /** + * @method getModelDefinition + * @author Julien Ledun + * @license MIT + * This method returns an object that represents some of the model + * definitions. + **/ + public static getModelDefinition() { + return { + name: 'Core', + plural: 'cores', + properties: { + id: { + name: 'id', + type: 'number' + }, + }, + relations: { + } + } + } } diff --git a/tests/angular2/src/app/shared/sdk/models/FireLoop.ts b/tests/angular2/src/app/shared/sdk/models/FireLoop.ts index 327a839a..f19d4ade 100644 --- a/tests/angular2/src/app/shared/sdk/models/FireLoop.ts +++ b/tests/angular2/src/app/shared/sdk/models/FireLoop.ts @@ -1,20 +1,16 @@ -import { LoopBackConfig } from '../lb.config'; -import { AccessToken, FireLoopRef } from './index'; -import { SocketConnections } from '../sockets/socket.connections'; +import { FireLoopRef } from './index'; export class FireLoop { - private socket: any; private references: any = {}; - constructor(token: AccessToken) { - this.socket = SocketConnections.getHandler(LoopBackConfig.getPath(), token); - } + constructor(private socket: any, private models: { get: Function }) {} - public ref(model: { getModelName(): string }): FireLoopRef { + public ref(model: any): FireLoopRef { let name: string = model.getModelName(); if (this.references[name]) { return this.references[name]; } - this.references[name] = new FireLoopRef(name, this.socket); + model.models = this.models; + this.references[name] = new FireLoopRef(model, this.socket); return this.references[name]; } } diff --git a/tests/angular2/src/app/shared/sdk/models/FireLoopRef.ts b/tests/angular2/src/app/shared/sdk/models/FireLoopRef.ts index bcf9bf2a..72ecc87b 100644 --- a/tests/angular2/src/app/shared/sdk/models/FireLoopRef.ts +++ b/tests/angular2/src/app/shared/sdk/models/FireLoopRef.ts @@ -1,126 +1,228 @@ import { Subject } from 'rxjs/Subject'; -import { Observable } from 'rxjs/Observable'; +import { Observable } from 'rxjs/Rx'; import { LoopBackFilter, StatFilter } from './index'; - +/** + * @class FireLoopRef + * @author Jonathan Casarrubias + * @license MIT + * @description + * This class allows to create FireLoop References which will be in sync with + * Server. It also allows to create FireLoop Reference Childs, that allows to + * persist data according the generic model relationships. + **/ export class FireLoopRef { - + // Reference ID + private id: number = Date.now() + this.buildId(); + // Model Instance (For child references, empty on root references) private instance: any; - private socket: any; - private name: string; - private current: { name: string }; - private parent: FireLoopRef; + // Model Childs private childs: any = {}; - private observables: any = {}; - - constructor(name: string, socket: any, parent: FireLoopRef = null, current = null) { - this.name = name; - this.current = current; - this.parent = parent; - this.socket = socket; - return this; - } - - private operation(event: string, data: any): Observable { - let id: number = Math.floor(Math.random() * 100800) * - Math.floor(Math.random() * 100700) * - Math.floor(Math.random() * 198500); - let subject: Subject = new Subject(); - let config: {id: any, data: any, current: any, parent: any } = { - id: id, - data: data, - current: this.current, - parent: this.parent && this.parent.instance ? this.parent.instance : null - }; - if (!this.parent || (this.parent && this.current)) { - this.socket.emit(`${this.name}.${event}`, config); - } else { - let interval = setInterval(() => { - if (this.current) { - config.current = this.current; - this.socket.emit(`${this.name}.${event}`, config); - clearInterval(interval); - } - }, 500); - } - this.socket.on(`${this.name}.value.result.${id}`, (res: any) => - subject.next(res.error ? Observable.throw(res.error) : res) + /** + * @method constructor + * @param model + * @param socket + * @param parent + * @param relationship + * @description + * The constructor will receive the required parameters and then will register this reference + * into the server, needed to allow multiple references for the same model. + * This ids are referenced into this specific client connection and won't have issues + * with other client ids. + **/ + constructor( + private model: any, + private socket: any, + private parent: any = null, + private relationship: any = null + ) { + this.socket.emit( + `Subscribe.${ !parent ? model.getModelName() : parent.model.getModelName() }`, + { id : this.id, scope: model.getModelName(), relationship: relationship } ); - return subject.asObservable(); + return this; } - + /** + * @method upsert + * @param data + * @description + * Operation wrapper for upsert function. + **/ public upsert(data: any): Observable { return this.operation('upsert', data); } - + /** + * @method upsert + * @param data + * @description + * Operation wrapper for create function. + **/ public create(data: any): Observable { return this.operation('create', data); } - + /** + * @method upsert + * @param data + * @description + * Operation wrapper for remove function. + **/ public remove(data: any): Observable { return this.operation('remove', data); } - + /** + * @method on + * @param event + * @param filter + * @description + * Listener for different type of events. Valid events are: + * - change (Triggers on any model change -create, update, remove-) + * - value (Triggers on new entries) + * - child_added (Triggers when a child is added) + * - child_updated (Triggers when a child is updated) + * - child_removed (Triggers when a child is removed) + **/ public on(event: string, filter: LoopBackFilter = { limit: 100, order: 'id DESC' }): Observable { - event = `${this.name}.${event}`; - if (this.observables[event]) { return this.observables[event]; } - let subject: Subject = new Subject(); + let request: any; + if (!this.relationship) { + event = `${ this.model.getModelName() }.${event}`; + request = { filter }; + } else { + event = `${ this.parent.model.getModelName() }.${ this.relationship }.${event}`; + request = { filter, parent: this.parent.instance }; + } if (event.match(/(value|change|stats)/)) { - this.pull(event, filter, subject); + return Observable.merge( + this.pull(event, request), + this.broadcasts(event, request) + ); + } else { + return this.broadcasts(event, request); } - // Listen for broadcast announces - this.socket.on( - // When there is a broadcast announce - `${event}.broadcast.announce`, - // We send a request containing the filtering options - () => this.socket.emit(`${event}.broadcast.request`, filter) - ); - // Once processed our request will return a unique result - this.socket.on(`${event}.broadcast`, (res: any) => subject.next(res)); - this.observables[event] = subject.asObservable(); - return this.observables[event]; - } + } + /** + * @method stats + * @param filter + * @description + * Listener for real-time statistics, will trigger on every + * statistic modification. + * TIP: You can improve performance by adding memcached to LoopBack models. + **/ public stats(filter?: StatFilter): Observable { - let event = `${this.name}.stats`; - if (this.observables[event]) { return this.observables[event]; } - let subject: Subject = new Subject(); - this.pull(event, filter, subject); + let event = `${this.model.getModelName()}.stats`; + let src_pull: Observable = this.pull(event, filter); // Listen for broadcast announces - this.socket.on( - // When there is a broadcast announce - `${event}.broadcast.announce`, - // We send a request containing the filtering options - () => this.socket.emit(`${event}.broadcast.request`, filter) - ); - // Once processed our request will return a unique result - this.socket.on(`${event}.broadcast`, (res: any) => subject.next(res)); - this.observables[event] = subject.asObservable(); - return this.observables[event]; - } - - private pull(event: string, filter: any, subject: Subject): void { - this.socket.emit(`${event}.pull.request`, filter); - this.socket.on(`${event}.pull.requested`, (res: any) => subject.next(res)); + let src_request: Observable = Observable.fromEvent(this.socket, `${event}.broadcast.announce`); + src_request.subscribe((res: T) => this.socket.emit(`${event}.broadcast.request`, filter)); + // Listen for broadcasted results + let src_broadcast: Observable = Observable.fromEvent(this.socket, `${event}.broadcast`); + return Observable.merge(src_pull, src_broadcast); } - + /** + * @method make + * @param instance + * @description + * This method will set a model instance into this current FireLoop Reference. + * This allows to persiste parentship when creating related instances. + **/ public make(instance: any): FireLoopRef { - this.instance = instance; - return this; + let reference: FireLoopRef = new FireLoopRef(this.model, this.socket); + reference.instance = instance; + return reference; } - - public child(name: string): FireLoopRef { - if (!this.parent) { - let childName = `${this.name}.${name}`; - if (this.childs[childName]) { return this.childs[childName]; } - this.socket.emit(`${this.name}.relation.request`, { relation: name }); - this.socket.on(`${this.name}.relation.request.result`, (Model: { name: string }) => { - this.childs[childName].current = Model; - }); - this.childs[childName] = new FireLoopRef(childName, this.socket, this); - return this.childs[childName]; + /** + * @method child + * @param relationship + * @description + * This method creates child references, which will persist related model + * instances. e.g. Room.messages, where messages belongs to a specific Room. + **/ + public child(relationship: string): FireLoopRef { + // Return singleton instance + if (this.childs[relationship]) { return this.childs[relationship]; } + // Try to get relation settings from current model + let settings: any = this.model.getModelDefinition().relations[relationship]; + // Verify the relationship actually exists + if (!settings) { + throw new Error(`Invalid model relationship ${ this.model.getModelName() } <-> ${ relationship }, verify your model settings.`); + } + // Verify if the relationship model is public + if (settings.model === '') { + throw new Error(`Relationship model is private, cam't use ${ relationship } unless you set your model as public.`); + } + // Lets get a model reference and add a reference for all of the models + let model: any = this.model.models.get(settings.model); + model.models = this.model.models; + // If everything goes well, we will store a child reference and return it. + this.childs[relationship] = new FireLoopRef(model, this.socket, this, relationship); + return this.childs[relationship]; + } + /** + * @method pull + * @param relationship + * @description + * This method will pull initial data from server + **/ + private pull(event: string, request: any): Observable { + let sbj: Subject = new Subject(); + let that: FireLoopRef = this; + let nowEvent: any = `${event}.pull.requested.${ this.id }`; + this.socket.emit(`${event}.pull.request.${ this.id }`, request); + function pullNow(data) { + that.socket.removeListener(nowEvent, pullNow); + sbj.next(data); + }; + this.socket.on(nowEvent, pullNow); + return sbj.asObservable(); + } + /** + * @method operation + * @param relationship + * @description + * This internal method will run operations depending on current context + **/ + private broadcasts(event: string, request: any): Observable { + let sbj: Subject = new Subject(); + this.socket.on( + `${event}.broadcast.announce.${ this.id }`, + (res: T) => + this.socket.emit(`${event}.broadcast.request.${ this.id }`, request) + ); + this.socket.on(`${ event }.broadcast.${ this.id }`, (data) => sbj.next(data)); + return sbj.asObservable(); + } + /** + * @method operation + * @param event + * @param data + * @description + * This internal method will run operations depending on current context + **/ + private operation(event: string, data: any): Observable { + if (!this.relationship) { + event = `${ this.model.getModelName() }.${event}.${ this.id }`; } else { - console.warn('Only 1 child level is supported'); - // TODO ADD UNLIMITED LEVELS + event = `${ this.parent.model.getModelName() }.${ this.relationship }.${ event }.${ this.id }`; } + let subject: Subject = new Subject(); + let config: { data: any, parent: any } = { + data, + parent: this.parent && this.parent.instance ? this.parent.instance : null + }; + this.socket.emit(event, config); + this.socket.on(`${ this.model.getModelName() }.value.result.${ this.id }`, (res: any) => + subject.next(res.error ? Observable.throw(res.error) : res) + ); + return subject.asObservable(); + } + /** + * @method buildId + * @description + * This internal method build an ID for this reference, this allows to have + * multiple references for the same model or relationships. + **/ + private buildId(): number { + return Math.floor(Math.random() * 100800) * + Math.floor(Math.random() * 100700) * + Math.floor(Math.random() * 198500); } } diff --git a/tests/angular2/src/app/shared/sdk/models/Message.ts b/tests/angular2/src/app/shared/sdk/models/Message.ts index 03d31514..4f20d847 100644 --- a/tests/angular2/src/app/shared/sdk/models/Message.ts +++ b/tests/angular2/src/app/shared/sdk/models/Message.ts @@ -16,16 +16,16 @@ export interface MessageInterface { } export class Message implements MessageInterface { - text: string; - id: number; - roomId: number; - parentId: number; - room: Room; - replies: Array; - parent: Message; - likes: Array; - constructor(instance?: MessageInterface) { - Object.assign(this, instance); + text: string = ''; + id: number = 0; + roomId: number = 0; + parentId: number = 0; + room: Room = null; + replies: Array = []; + parent: Message = null; + likes: Array = []; + constructor(data?: MessageInterface) { + Object.assign(this, data); } /** * The name of the model represented by this $resource, @@ -34,4 +34,67 @@ export class Message implements MessageInterface { public static getModelName() { return "Message"; } + /** + * @method factory + * @author Jonathan Casarrubias + * @license MIT + * This method creates an instance of Message for dynamic purposes. + **/ + public static factory(data: MessageInterface): Message{ + return new Message(data); + } + /** + * @method getModelDefinition + * @author Julien Ledun + * @license MIT + * This method returns an object that represents some of the model + * definitions. + **/ + public static getModelDefinition() { + return { + name: 'Message', + plural: 'messages', + properties: { + text: { + name: 'text', + type: 'string', + default: '' + }, + id: { + name: 'id', + type: 'number' + }, + roomId: { + name: 'roomId', + type: 'number' + }, + parentId: { + name: 'parentId', + type: 'number' + }, + }, + relations: { + room: { + name: 'room', + type: 'Room', + model: 'Room' + }, + replies: { + name: 'replies', + type: 'Array', + model: 'Message' + }, + parent: { + name: 'parent', + type: 'Message', + model: 'Message' + }, + likes: { + name: 'likes', + type: 'Array', + model: '' + }, + } + } + } } diff --git a/tests/angular2/src/app/shared/sdk/models/Room.ts b/tests/angular2/src/app/shared/sdk/models/Room.ts index 5a0ac122..608218c1 100644 --- a/tests/angular2/src/app/shared/sdk/models/Room.ts +++ b/tests/angular2/src/app/shared/sdk/models/Room.ts @@ -17,15 +17,15 @@ export interface RoomInterface { } export class Room implements RoomInterface { - name: string; - id: number; - messages: Array; - likes: Array; - categories: Array; - accounts: Array; - admins: Array; - constructor(instance?: RoomInterface) { - Object.assign(this, instance); + name: string = ''; + id: number = 0; + messages: Array = []; + likes: Array = []; + categories: Array = []; + accounts: Array = []; + admins: Array = []; + constructor(data?: RoomInterface) { + Object.assign(this, data); } /** * The name of the model represented by this $resource, @@ -34,4 +34,64 @@ export class Room implements RoomInterface { public static getModelName() { return "Room"; } + /** + * @method factory + * @author Jonathan Casarrubias + * @license MIT + * This method creates an instance of Room for dynamic purposes. + **/ + public static factory(data: RoomInterface): Room{ + return new Room(data); + } + /** + * @method getModelDefinition + * @author Julien Ledun + * @license MIT + * This method returns an object that represents some of the model + * definitions. + **/ + public static getModelDefinition() { + return { + name: 'Room', + plural: 'rooms', + properties: { + name: { + name: 'name', + type: 'string', + default: '' + }, + id: { + name: 'id', + type: 'number' + }, + }, + relations: { + messages: { + name: 'messages', + type: 'Array', + model: 'Message' + }, + likes: { + name: 'likes', + type: 'Array', + model: '' + }, + categories: { + name: 'categories', + type: 'Array', + model: 'Category' + }, + accounts: { + name: 'accounts', + type: 'Array', + model: 'Account' + }, + admins: { + name: 'admins', + type: 'Array', + model: 'Account' + }, + } + } + } } diff --git a/tests/angular2/src/app/shared/sdk/models/RoomAccount.ts b/tests/angular2/src/app/shared/sdk/models/RoomAccount.ts index 644d38b9..2ccb1e29 100644 --- a/tests/angular2/src/app/shared/sdk/models/RoomAccount.ts +++ b/tests/angular2/src/app/shared/sdk/models/RoomAccount.ts @@ -14,13 +14,13 @@ export interface RoomAccountInterface { } export class RoomAccount implements RoomAccountInterface { - id: number; - accountId: number; - roomId: number; - account: Account; - room: Room; - constructor(instance?: RoomAccountInterface) { - Object.assign(this, instance); + id: number = 0; + accountId: number = 0; + roomId: number = 0; + account: Account = null; + room: Room = null; + constructor(data?: RoomAccountInterface) { + Object.assign(this, data); } /** * The name of the model represented by this $resource, @@ -29,4 +29,52 @@ export class RoomAccount implements RoomAccountInterface { public static getModelName() { return "RoomAccount"; } + /** + * @method factory + * @author Jonathan Casarrubias + * @license MIT + * This method creates an instance of RoomAccount for dynamic purposes. + **/ + public static factory(data: RoomAccountInterface): RoomAccount{ + return new RoomAccount(data); + } + /** + * @method getModelDefinition + * @author Julien Ledun + * @license MIT + * This method returns an object that represents some of the model + * definitions. + **/ + public static getModelDefinition() { + return { + name: 'RoomAccount', + plural: 'room-accounts', + properties: { + id: { + name: 'id', + type: 'number' + }, + accountId: { + name: 'accountId', + type: 'number' + }, + roomId: { + name: 'roomId', + type: 'number' + }, + }, + relations: { + account: { + name: 'account', + type: 'Account', + model: 'Account' + }, + room: { + name: 'room', + type: 'Room', + model: 'Room' + }, + } + } + } } diff --git a/tests/angular2/src/app/shared/sdk/models/Storage.ts b/tests/angular2/src/app/shared/sdk/models/Storage.ts index 54bc1d46..324ec852 100644 --- a/tests/angular2/src/app/shared/sdk/models/Storage.ts +++ b/tests/angular2/src/app/shared/sdk/models/Storage.ts @@ -6,9 +6,9 @@ export interface StorageInterface { } export class Storage implements StorageInterface { - id: number; - constructor(instance?: StorageInterface) { - Object.assign(this, instance); + id: number = 0; + constructor(data?: StorageInterface) { + Object.assign(this, data); } /** * The name of the model represented by this $resource, @@ -17,4 +17,34 @@ export class Storage implements StorageInterface { public static getModelName() { return "Storage"; } + /** + * @method factory + * @author Jonathan Casarrubias + * @license MIT + * This method creates an instance of Storage for dynamic purposes. + **/ + public static factory(data: StorageInterface): Storage{ + return new Storage(data); + } + /** + * @method getModelDefinition + * @author Julien Ledun + * @license MIT + * This method returns an object that represents some of the model + * definitions. + **/ + public static getModelDefinition() { + return { + name: 'Storage', + plural: 'storages', + properties: { + id: { + name: 'id', + type: 'number' + }, + }, + relations: { + } + } + } } diff --git a/tests/angular2/src/app/shared/sdk/models/User.ts b/tests/angular2/src/app/shared/sdk/models/User.ts index 89a0c1d4..2c8486b3 100644 --- a/tests/angular2/src/app/shared/sdk/models/User.ts +++ b/tests/angular2/src/app/shared/sdk/models/User.ts @@ -17,20 +17,20 @@ export interface UserInterface { } export class User implements UserInterface { - realm: string; - username: string; - password: string; - challenges: any; - email: string; - emailVerified: boolean; - verificationToken: string; - status: string; - created: Date; - lastUpdated: Date; - id: number; - accessTokens: Array; - constructor(instance?: UserInterface) { - Object.assign(this, instance); + realm: string = ''; + username: string = ''; + password: string = ''; + challenges: any = null; + email: string = ''; + emailVerified: boolean = false; + verificationToken: string = ''; + status: string = ''; + created: Date = new Date(0); + lastUpdated: Date = new Date(0); + id: number = 0; + accessTokens: Array = []; + constructor(data?: UserInterface) { + Object.assign(this, data); } /** * The name of the model represented by this $resource, @@ -39,4 +39,83 @@ export class User implements UserInterface { public static getModelName() { return "User"; } + /** + * @method factory + * @author Jonathan Casarrubias + * @license MIT + * This method creates an instance of User for dynamic purposes. + **/ + public static factory(data: UserInterface): User{ + return new User(data); + } + /** + * @method getModelDefinition + * @author Julien Ledun + * @license MIT + * This method returns an object that represents some of the model + * definitions. + **/ + public static getModelDefinition() { + return { + name: 'User', + plural: 'Users', + properties: { + realm: { + name: 'realm', + type: 'string' + }, + username: { + name: 'username', + type: 'string' + }, + password: { + name: 'password', + type: 'string' + }, + credentials: { + name: 'credentials', + type: 'any' + }, + challenges: { + name: 'challenges', + type: 'any' + }, + email: { + name: 'email', + type: 'string' + }, + emailVerified: { + name: 'emailVerified', + type: 'boolean' + }, + verificationToken: { + name: 'verificationToken', + type: 'string' + }, + status: { + name: 'status', + type: 'string' + }, + created: { + name: 'created', + type: 'Date' + }, + lastUpdated: { + name: 'lastUpdated', + type: 'Date' + }, + id: { + name: 'id', + type: 'number' + }, + }, + relations: { + accessTokens: { + name: 'accessTokens', + type: 'Array', + model: '' + }, + } + } + } } diff --git a/tests/angular2/src/app/shared/sdk/models/UserCredential.ts b/tests/angular2/src/app/shared/sdk/models/UserCredential.ts index 43911031..18ad6846 100644 --- a/tests/angular2/src/app/shared/sdk/models/UserCredential.ts +++ b/tests/angular2/src/app/shared/sdk/models/UserCredential.ts @@ -14,17 +14,17 @@ export interface UserCredentialInterface { } export class UserCredential implements UserCredentialInterface { - provider: string; - authScheme: string; - externalId: string; - profile: any; - credentials: string; - created: Date; - modified: Date; - userId: any; - id: number; - constructor(instance?: UserCredentialInterface) { - Object.assign(this, instance); + provider: string = 'authScheme'; + authScheme: string = ''; + externalId: string = ''; + profile: any = null; + credentials: string = ''; + created: Date = new Date(0); + modified: Date = new Date(0); + userId: any = null; + id: number = 0; + constructor(data?: UserCredentialInterface) { + Object.assign(this, data); } /** * The name of the model represented by this $resource, @@ -33,4 +33,72 @@ export class UserCredential implements UserCredentialInterface { public static getModelName() { return "UserCredential"; } + /** + * @method factory + * @author Jonathan Casarrubias + * @license MIT + * This method creates an instance of UserCredential for dynamic purposes. + **/ + public static factory(data: UserCredentialInterface): UserCredential{ + return new UserCredential(data); + } + /** + * @method getModelDefinition + * @author Julien Ledun + * @license MIT + * This method returns an object that represents some of the model + * definitions. + **/ + public static getModelDefinition() { + return { + name: 'UserCredential', + plural: 'UserCredentials', + properties: { + provider: { + name: 'provider', + type: 'string', + default: 'authScheme' + }, + authScheme: { + name: 'authScheme', + type: 'string', + default: '' + }, + externalId: { + name: 'externalId', + type: 'string', + default: '' + }, + profile: { + name: 'profile', + type: 'any', + default: null + }, + credentials: { + name: 'credentials', + type: 'string', + default: '' + }, + created: { + name: 'created', + type: 'Date' + }, + modified: { + name: 'modified', + type: 'Date', + default: new Date(0) + }, + userId: { + name: 'userId', + type: 'any' + }, + id: { + name: 'id', + type: 'number' + }, + }, + relations: { + } + } + } } diff --git a/tests/angular2/src/app/shared/sdk/models/UserIdentity.ts b/tests/angular2/src/app/shared/sdk/models/UserIdentity.ts index 68f7d323..dc5e6b34 100644 --- a/tests/angular2/src/app/shared/sdk/models/UserIdentity.ts +++ b/tests/angular2/src/app/shared/sdk/models/UserIdentity.ts @@ -18,18 +18,18 @@ export interface UserIdentityInterface { } export class UserIdentity implements UserIdentityInterface { - provider: string; - authScheme: string; - externalId: string; - profile: any; - credentials: string; - created: Date; - modified: Date; - userId: number; - id: number; - user: User; - constructor(instance?: UserIdentityInterface) { - Object.assign(this, instance); + provider: string = 'authScheme'; + authScheme: string = ''; + externalId: string = ''; + profile: any = null; + credentials: string = ''; + created: Date = new Date(0); + modified: Date = new Date(0); + userId: number = 0; + id: number = 0; + user: User = null; + constructor(data?: UserIdentityInterface) { + Object.assign(this, data); } /** * The name of the model represented by this $resource, @@ -38,4 +38,76 @@ export class UserIdentity implements UserIdentityInterface { public static getModelName() { return "UserIdentity"; } + /** + * @method factory + * @author Jonathan Casarrubias + * @license MIT + * This method creates an instance of UserIdentity for dynamic purposes. + **/ + public static factory(data: UserIdentityInterface): UserIdentity{ + return new UserIdentity(data); + } + /** + * @method getModelDefinition + * @author Julien Ledun + * @license MIT + * This method returns an object that represents some of the model + * definitions. + **/ + public static getModelDefinition() { + return { + name: 'UserIdentity', + plural: 'UserIdentities', + properties: { + provider: { + name: 'provider', + type: 'string', + default: 'authScheme' + }, + authScheme: { + name: 'authScheme', + type: 'string', + default: '' + }, + externalId: { + name: 'externalId', + type: 'string', + default: '' + }, + profile: { + name: 'profile', + type: 'any', + default: null + }, + credentials: { + name: 'credentials', + type: 'string', + default: '' + }, + created: { + name: 'created', + type: 'Date' + }, + modified: { + name: 'modified', + type: 'Date' + }, + userId: { + name: 'userId', + type: 'number' + }, + id: { + name: 'id', + type: 'number' + }, + }, + relations: { + user: { + name: 'user', + type: 'User', + model: 'User' + }, + } + } + } } diff --git a/tests/angular2/src/app/shared/sdk/services/core/auth.service.ts b/tests/angular2/src/app/shared/sdk/services/core/auth.service.ts index 8c540189..e178f56f 100644 --- a/tests/angular2/src/app/shared/sdk/services/core/auth.service.ts +++ b/tests/angular2/src/app/shared/sdk/services/core/auth.service.ts @@ -1,7 +1,7 @@ /* tslint:disable */ declare var Object: any; -import { Injectable } from '@angular/core'; -import { StorageDriver } from '../../storage/storage.driver'; +import { Injectable, Inject } from '@angular/core'; +import { InternalStorage } from '../../storage/internal.storage'; import { SDKToken, AccessToken } from '../../models/BaseModels'; /** @@ -17,10 +17,13 @@ export class LoopBackAuth { private token: SDKToken = new SDKToken(); protected prefix: string = '$LoopBackSDK$'; - constructor() { + constructor(@Inject(InternalStorage) protected storage: InternalStorage) { this.token.id = this.load('id'); this.token.user = this.load('user'); this.token.userId = this.load('userId'); + this.token.issuedAt = this.load('issuedAt'); + this.token.created = this.load('created'); + this.token.ttl = this.load('ttl'); this.token.rememberMe = this.load('rememberMe'); } @@ -49,6 +52,9 @@ export class LoopBackAuth { this.persist('id', this.token.id); this.persist('user', this.token.user); this.persist('userId', this.token.userId); + this.persist('issuedAt', this.token.issuedAt); + this.persist('created', this.token.created); + this.persist('ttl', this.token.ttl); this.persist('rememberMe', this.token.rememberMe); } }; @@ -58,11 +64,11 @@ export class LoopBackAuth { } protected load(prop: string): any { - return StorageDriver.get(`${this.prefix}${prop}`); + return this.storage.get(`${this.prefix}${prop}`); } public clear(): void { - Object.keys(this.token).forEach((prop: string) => StorageDriver.remove(`${this.prefix}${prop}`)); + Object.keys(this.token).forEach((prop: string) => this.storage.remove(`${this.prefix}${prop}`)); this.token = new SDKToken(); } // I do not persist everything in 1 value because I want @@ -70,7 +76,7 @@ export class LoopBackAuth { // expected and will be easier to handle as will perform better. protected persist(prop: string, value: any): void { try { - StorageDriver.set( + this.storage.set( `${this.prefix}${prop}`, (typeof value === 'object') ? JSON.stringify(value) : value ); diff --git a/tests/angular2/src/app/shared/sdk/services/core/base.service.ts b/tests/angular2/src/app/shared/sdk/services/core/base.service.ts index eac19124..d5d76c74 100644 --- a/tests/angular2/src/app/shared/sdk/services/core/base.service.ts +++ b/tests/angular2/src/app/shared/sdk/services/core/base.service.ts @@ -6,13 +6,16 @@ import { JSONSearchParams } from './search.params'; import { ErrorHandler } from './error.service'; import { LoopBackAuth } from './auth.service'; import { LoopBackConfig } from '../../lb.config'; -import { AccessToken } from '../../models/index'; +import { LoopBackFilter, SDKToken, AccessToken } from '../../models/BaseModels'; +import { SDKModels } from '../custom/SDKModels'; import { Observable } from 'rxjs/Observable'; import { ErrorObservable } from 'rxjs/observable/ErrorObservable'; import 'rxjs/add/operator/catch'; import 'rxjs/add/operator/map'; import { Subject } from 'rxjs/Subject'; import { SocketConnections } from '../../sockets/socket.connections'; +// Making Sure EventSource Type is available to avoid compilation issues. +declare var EventSource: any; /** * @module BaseLoopBackApi * @author Nikolay Matiushenkov @@ -28,13 +31,18 @@ import { SocketConnections } from '../../sockets/socket.connections'; export abstract class BaseLoopBackApi { protected path: string; + protected model: any; constructor( @Inject(Http) protected http: Http, + @Inject(SocketConnections) protected connections: SocketConnections, + @Inject(SDKModels) protected models: SDKModels, @Inject(LoopBackAuth) protected auth: LoopBackAuth, @Inject(JSONSearchParams) protected searchParams: JSONSearchParams, @Optional() @Inject(ErrorHandler) protected errorHandler: ErrorHandler - ) {} + ) { + this.model = this.models.get(this.getModelName()); + } /** * Process request @@ -50,7 +58,7 @@ export abstract class BaseLoopBackApi { url : string, routeParams : any = {}, urlParams : any = {}, - postBody : any = null, + postBody : any = {}, isio : boolean = false ): Observable { @@ -83,7 +91,7 @@ export abstract class BaseLoopBackApi { let token: AccessToken = new AccessToken(); token.id = this.auth.getAccessTokenId(); token.userId = this.auth.getCurrentUserId(); - let socket: any = SocketConnections.getHandler(LoopBackConfig.getPath(), token); + let socket: any = this.connections.getHandler(LoopBackConfig.getPath(), token); socket.on(event, (res: any) => subject.next(res)); return subject.asObservable(); } @@ -98,13 +106,19 @@ export abstract class BaseLoopBackApi { } else { body = postBody; } + // Separate filter object from url params + let filter: string = ''; + if (urlParams.filter) { + filter = `?filter=${ encodeURI(JSON.stringify(urlParams.filter))}`; + delete urlParams.filter; + } + this.searchParams.setJSON(urlParams); let request: Request = new Request({ headers : headers, method : method, - url : urlParams.filter ? `${requestUrl}?filter=${ encodeURI(JSON.stringify(urlParams.filter))}` - : requestUrl, - search : !urlParams.filter && Object.keys(urlParams).length > 0 + url : `${requestUrl}${filter}`, + search : Object.keys(urlParams).length > 0 ? this.searchParams.getURLSearchParams() : null, body : body ? JSON.stringify(body) : undefined }); @@ -112,4 +126,253 @@ export abstract class BaseLoopBackApi { .map((res: any) => (res.text() != "" ? res.json() : {})) .catch(this.errorHandler.handleError); } + /** + * @method create + * @author Jonathan Casarrubias + * @license MIT + * @description + * Generic create method + */ + public create(data: any = {}): Observable { + return this.request('POST', [ + LoopBackConfig.getPath(), + LoopBackConfig.getApiVersion(), + this.model.getModelDefinition().plural + ].join('/'), undefined, undefined, { data }).map((data: T) => this.model.factory(data)); + } + /** + * @method create + * @author Jonathan Casarrubias + * @license MIT + * @description + * Generic create method + */ + public createMany(data: any = {}): Observable { + return this.request('POST', [ + LoopBackConfig.getPath(), + LoopBackConfig.getApiVersion(), + this.model.getModelDefinition().plural + ].join('/'), undefined, undefined, { data }) + .map((datum: T[]) => datum.map((data: T) => this.model.factory(data))); + } + /** + * @method findById + * @author Jonathan Casarrubias + * @license MIT + * @description + * Generic findById method + */ + public findById(id: any, filter: LoopBackFilter = {}): Observable { + let _urlParams: any = {}; + if (filter) _urlParams.filter = filter; + return this.request('GET', [ + LoopBackConfig.getPath(), + LoopBackConfig.getApiVersion(), + this.model.getModelDefinition().plural, + ':id' + ].join('/'), { id }, _urlParams, undefined).map((data: T) => this.model.factory(data)); + } + /** + * @method find + * @author Jonathan Casarrubias + * @license MIT + * @description + * Generic find method + */ + public find(filter: LoopBackFilter = {}): Observable { + return this.request('GET', [ + LoopBackConfig.getPath(), + LoopBackConfig.getApiVersion(), + this.model.getModelDefinition().plural + ].join('/'), undefined, { filter }, undefined) + .map((datum: T[]) => datum.map((data: T) => this.model.factory(data))); + } + /** + * @method exists + * @author Jonathan Casarrubias + * @license MIT + * @description + * Generic exists method + */ + public exists(id: any): Observable { + return this.request('GET', [ + LoopBackConfig.getPath(), + LoopBackConfig.getApiVersion(), + this.model.getModelDefinition().plural, + 'exists' + ].join('/'), { id }, undefined, undefined); + } + /** + * @method findOne + * @author Jonathan Casarrubias + * @license MIT + * @description + * Generic findOne method + */ + public findOne(filter: LoopBackFilter = {}): Observable { + return this.request('GET', [ + LoopBackConfig.getPath(), + LoopBackConfig.getApiVersion(), + this.model.getModelDefinition().plural, + 'findOne' + ].join('/'), undefined, { filter }, undefined).map((data: T) => this.model.factory(data)); + } + /** + * @method updateAll + * @author Jonathan Casarrubias + * @license MIT + * @description + * Generic updateAll method + */ + public updateAll(where: any = {}, data: T): Observable { + let _urlParams: any = {}; + if (where) _urlParams.where = where; + return this.request('POST', [ + LoopBackConfig.getPath(), + LoopBackConfig.getApiVersion(), + this.model.getModelDefinition().plural, + 'update' + ].join('/'), undefined, _urlParams, { data }) + .map((datum: T[]) => datum.map((data: T) => this.model.factory(data))); + } + /** + * @method deleteById + * @author Jonathan Casarrubias + * @license MIT + * @description + * Generic deleteById method + */ + public deleteById(id: any): Observable { + return this.request('DELETE', [ + LoopBackConfig.getPath(), + LoopBackConfig.getApiVersion(), + this.model.getModelDefinition().plural, + ':id' + ].join('/'), { id }, undefined, undefined).map((data: T) => this.model.factory(data)); + } + /** + * @method count + * @author Jonathan Casarrubias + * @license MIT + * @description + * Generic count method + */ + public count(where: any = {}): Observable<{ count: number }> { + let _urlParams: any = {}; + if (where) _urlParams.where = where; + return this.request('GET', [ + LoopBackConfig.getPath(), + LoopBackConfig.getApiVersion(), + this.model.getModelDefinition().plural, + 'count' + ].join('/'), undefined, _urlParams, undefined); + } + /** + * @method updateAttributes + * @author Jonathan Casarrubias + * @license MIT + * @description + * Generic updateAttributes method + */ + public updateAttributes(id: any, data: T): Observable { + return this.request('PUT', [ + LoopBackConfig.getPath(), + LoopBackConfig.getApiVersion(), + this.model.getModelDefinition().plural, + ':id' + ].join('/'), { id }, undefined, { data }).map((data: T) => this.model.factory(data)); + } + /** + * @method upsert + * @author Jonathan Casarrubias + * @license MIT + * @description + * Generic upsert method + */ + public upsert(data: any = {}): Observable { + return this.request('PUT', [ + LoopBackConfig.getPath(), + LoopBackConfig.getApiVersion(), + this.model.getModelDefinition().plural, + ].join('/'), undefined, undefined, { data }).map((data: T) => this.model.factory(data)); + } + /** + * @method upsertWithWhere + * @author Jonathan Casarrubias + * @license MIT + * @description + * Generic upsertWithWhere method + */ + public upsertWithWhere(where: any = {}, data: any = {}): Observable { + let _urlParams: any = {}; + if (where) _urlParams.where = where; + return this.request('PUT', [ + LoopBackConfig.getPath(), + LoopBackConfig.getApiVersion(), + this.model.getModelDefinition().plural, + 'upsertWithWhere' + ].join('/'), undefined, _urlParams, { data }).map((data: T) => this.model.factory(data)); + } + /** + * @method replaceOrCreate + * @author Jonathan Casarrubias + * @license MIT + * @description + * Generic replaceOrCreate method + */ + public replaceOrCreate(data: any = {}): Observable { + return this.request('PUT', [ + LoopBackConfig.getPath(), + LoopBackConfig.getApiVersion(), + this.model.getModelDefinition().plural, + 'replaceOrCreate' + ].join('/'), undefined, undefined, { data }).map((data: T) => this.model.factory(data)); + } + /** + * @method replaceById + * @author Jonathan Casarrubias + * @license MIT + * @description + * Generic replaceById method + */ + public replaceById(id: any, data: any = {}): Observable { + return this.request('POST', [ + LoopBackConfig.getPath(), + LoopBackConfig.getApiVersion(), + this.model.getModelDefinition().plural, + ':id', 'replace' + ].join('/'), undefined, undefined, { data }).map((data: T) => this.model.factory(data)); + } + /** + * @method createChangeStream + * @author Jonathan Casarrubias + * @license MIT + * @description + * Generic createChangeStream method + */ + public createChangeStream(): Observable { + let subject = new Subject(); + if (typeof EventSource !== 'undefined') { + let emit = (msg: any) => subject.next(JSON.parse(msg.data)); + var source = new EventSource([ + LoopBackConfig.getPath(), + LoopBackConfig.getApiVersion(), + this.model.getModelDefinition().plural, + 'change-stream' + ].join('/')); + source.addEventListener('data', emit); + source.onerror = emit; + } else { + console.warn('SDK Builder: EventSource is not supported'); + } + return subject.asObservable(); + } + /** + * @method getModelName + * @author Jonathan Casarrubias + * @license MIT + * @description + * Abstract getModelName method + */ + abstract getModelName(): string; } diff --git a/tests/angular2/src/app/shared/sdk/services/core/io.service.ts b/tests/angular2/src/app/shared/sdk/services/core/io.service.ts index 785e90dd..7f775a12 100644 --- a/tests/angular2/src/app/shared/sdk/services/core/io.service.ts +++ b/tests/angular2/src/app/shared/sdk/services/core/io.service.ts @@ -1,17 +1,12 @@ import { Subject } from 'rxjs/Subject'; import { Observable } from 'rxjs/Observable'; -import { AccessToken } from '../../models'; -import { LoopBackConfig } from '../../lb.config'; -import { SocketConnections } from '../../sockets/socket.connections'; export class IO { private socket: any; private observables: any = {}; - constructor(token: AccessToken) { - this.socket = SocketConnections.getHandler(LoopBackConfig.getPath(), token); - } + constructor(socket: any) { this.socket = socket; } emit(event: string, data: any): void { this.socket.emit('ME:RT:1://event', { diff --git a/tests/angular2/src/app/shared/sdk/services/core/real.time.ts b/tests/angular2/src/app/shared/sdk/services/core/real.time.ts index 18bf25de..f3fe65aa 100644 --- a/tests/angular2/src/app/shared/sdk/services/core/real.time.ts +++ b/tests/angular2/src/app/shared/sdk/services/core/real.time.ts @@ -2,8 +2,10 @@ import { Injectable, Inject } from '@angular/core'; import { IO } from './io.service'; import { JSONSearchParams } from './search.params'; import { LoopBackAuth } from './auth.service'; -import { AccessToken } from '../../models'; +import { LoopBackConfig } from '../../lb.config'; import { FireLoop } from '../../models/FireLoop'; +import { SocketConnections } from '../../sockets/socket.connections'; +import { SDKModels } from '../custom/SDKModels'; @Injectable() export class RealTime { @@ -12,11 +14,17 @@ export class RealTime { public FireLoop: FireLoop; constructor( + @Inject(SocketConnections) protected connections: SocketConnections, + @Inject(SDKModels) protected models: SDKModels, @Inject(LoopBackAuth) protected auth: LoopBackAuth, @Inject(JSONSearchParams) protected searchParams: JSONSearchParams ) { - let token: AccessToken = this.auth.getToken(); - this.IO = new IO(token); - this.FireLoop = new FireLoop(token); + let socket: any = this.getConnection(); + this.IO = new IO(socket); + this.FireLoop = new FireLoop(socket, models); + } + + getConnection(): void { + return this.connections.getHandler(LoopBackConfig.getPath(), this.auth.getToken()); } } diff --git a/tests/angular2/src/app/shared/sdk/services/custom/Account.ts b/tests/angular2/src/app/shared/sdk/services/custom/Account.ts index 81c64675..188ea46f 100644 --- a/tests/angular2/src/app/shared/sdk/services/custom/Account.ts +++ b/tests/angular2/src/app/shared/sdk/services/custom/Account.ts @@ -1,9 +1,11 @@ /* tslint:disable */ import { Injectable, Inject, Optional } from '@angular/core'; import { Http, Response } from '@angular/http'; +import { SDKModels } from './SDKModels'; import { BaseLoopBackApi } from '../core/base.service'; import { LoopBackConfig } from '../../lb.config'; import { LoopBackAuth } from '../core/auth.service'; +import { SocketConnections } from '../../sockets/socket.connections'; import { LoopBackFilter, SDKToken, AccessToken } from '../../models/BaseModels'; import { JSONSearchParams } from '../core/search.params'; import { ErrorHandler } from '../core/error.service'; @@ -14,8 +16,6 @@ import { Account } from '../../models/Account'; import { RoomAccount } from '../../models/RoomAccount'; import { Room } from '../../models/Room'; -// Making Sure EventSource Type is available to avoid compilation issues. -declare var EventSource: any; /** * Api services for the `Account` model. @@ -24,12 +24,14 @@ declare var EventSource: any; export class AccountApi extends BaseLoopBackApi { constructor( - @Inject(Http) http: Http, - @Inject(LoopBackAuth) protected auth: LoopBackAuth, - @Inject(JSONSearchParams) protected searchParams: JSONSearchParams, - @Optional() @Inject(ErrorHandler) errorHandler: ErrorHandler + @Inject(Http) protected http: Http, + @Inject(SocketConnections) protected connections: SocketConnections, + @Inject(SDKModels) protected models: SDKModels, + @Inject(LoopBackAuth) protected auth: LoopBackAuth, + @Inject(JSONSearchParams) protected searchParams: JSONSearchParams, + @Optional() @Inject(ErrorHandler) protected errorHandler: ErrorHandler ) { - super(http, auth, searchParams, errorHandler); + super(http, connections, models, auth, searchParams, errorHandler); } /** @@ -51,7 +53,7 @@ export class AccountApi extends BaseLoopBackApi { public findByIdAccessTokens(id: any, fk: any): Observable { let _method: string = "GET"; let _url: string = LoopBackConfig.getPath() + "/" + LoopBackConfig.getApiVersion() + - "/Accounts/:id/accessTokens/:fk"; + "/accounts/:id/accessTokens/:fk"; let _routeParams: any = { id: id, fk: fk @@ -78,7 +80,7 @@ export class AccountApi extends BaseLoopBackApi { public destroyByIdAccessTokens(id: any, fk: any): Observable { let _method: string = "DELETE"; let _url: string = LoopBackConfig.getPath() + "/" + LoopBackConfig.getApiVersion() + - "/Accounts/:id/accessTokens/:fk"; + "/accounts/:id/accessTokens/:fk"; let _routeParams: any = { id: id, fk: fk @@ -92,7 +94,7 @@ export class AccountApi extends BaseLoopBackApi { public onDestroyByIdAccessTokens(id: any): Observable { let _method: string = "DELETE"; let _url: string = "/" + LoopBackConfig.getApiVersion() + - "/Accounts/:id/accessTokens/:fk"; + "/accounts/:id/accessTokens/:fk"; let _routeParams: any = { id: id }; @@ -126,7 +128,7 @@ export class AccountApi extends BaseLoopBackApi { public updateByIdAccessTokens(id: any, fk: any, data: any = {}): Observable { let _method: string = "PUT"; let _url: string = LoopBackConfig.getPath() + "/" + LoopBackConfig.getApiVersion() + - "/Accounts/:id/accessTokens/:fk"; + "/accounts/:id/accessTokens/:fk"; let _routeParams: any = { id: id, fk: fk @@ -142,7 +144,7 @@ export class AccountApi extends BaseLoopBackApi { public onUpdateByIdAccessTokens(id: any): Observable { let _method: string = "PUT"; let _url: string = "/" + LoopBackConfig.getApiVersion() + - "/Accounts/:id/accessTokens/:fk"; + "/accounts/:id/accessTokens/:fk"; let _routeParams: any = { id: id }; @@ -172,7 +174,7 @@ export class AccountApi extends BaseLoopBackApi { public findByIdRooms(id: any, fk: any): Observable { let _method: string = "GET"; let _url: string = LoopBackConfig.getPath() + "/" + LoopBackConfig.getApiVersion() + - "/Accounts/:id/rooms/:fk"; + "/accounts/:id/rooms/:fk"; let _routeParams: any = { id: id, fk: fk @@ -199,7 +201,7 @@ export class AccountApi extends BaseLoopBackApi { public destroyByIdRooms(id: any, fk: any): Observable { let _method: string = "DELETE"; let _url: string = LoopBackConfig.getPath() + "/" + LoopBackConfig.getApiVersion() + - "/Accounts/:id/rooms/:fk"; + "/accounts/:id/rooms/:fk"; let _routeParams: any = { id: id, fk: fk @@ -213,7 +215,7 @@ export class AccountApi extends BaseLoopBackApi { public onDestroyByIdRooms(id: any): Observable { let _method: string = "DELETE"; let _url: string = "/" + LoopBackConfig.getApiVersion() + - "/Accounts/:id/rooms/:fk"; + "/accounts/:id/rooms/:fk"; let _routeParams: any = { id: id }; @@ -247,7 +249,7 @@ export class AccountApi extends BaseLoopBackApi { public updateByIdRooms(id: any, fk: any, data: any = {}): Observable { let _method: string = "PUT"; let _url: string = LoopBackConfig.getPath() + "/" + LoopBackConfig.getApiVersion() + - "/Accounts/:id/rooms/:fk"; + "/accounts/:id/rooms/:fk"; let _routeParams: any = { id: id, fk: fk @@ -263,7 +265,7 @@ export class AccountApi extends BaseLoopBackApi { public onUpdateByIdRooms(id: any): Observable { let _method: string = "PUT"; let _url: string = "/" + LoopBackConfig.getApiVersion() + - "/Accounts/:id/rooms/:fk"; + "/accounts/:id/rooms/:fk"; let _routeParams: any = { id: id }; @@ -297,7 +299,7 @@ export class AccountApi extends BaseLoopBackApi { public linkRooms(id: any, fk: any, data: any = {}): Observable { let _method: string = "PUT"; let _url: string = LoopBackConfig.getPath() + "/" + LoopBackConfig.getApiVersion() + - "/Accounts/:id/rooms/rel/:fk"; + "/accounts/:id/rooms/rel/:fk"; let _routeParams: any = { id: id, fk: fk @@ -313,7 +315,7 @@ export class AccountApi extends BaseLoopBackApi { public onLinkRooms(id: any): Observable { let _method: string = "PUT"; let _url: string = "/" + LoopBackConfig.getApiVersion() + - "/Accounts/:id/rooms/rel/:fk"; + "/accounts/:id/rooms/rel/:fk"; let _routeParams: any = { id: id }; @@ -340,7 +342,7 @@ export class AccountApi extends BaseLoopBackApi { public unlinkRooms(id: any, fk: any): Observable { let _method: string = "DELETE"; let _url: string = LoopBackConfig.getPath() + "/" + LoopBackConfig.getApiVersion() + - "/Accounts/:id/rooms/rel/:fk"; + "/accounts/:id/rooms/rel/:fk"; let _routeParams: any = { id: id, fk: fk @@ -354,7 +356,7 @@ export class AccountApi extends BaseLoopBackApi { public onUnlinkRooms(id: any): Observable { let _method: string = "DELETE"; let _url: string = "/" + LoopBackConfig.getApiVersion() + - "/Accounts/:id/rooms/rel/:fk"; + "/accounts/:id/rooms/rel/:fk"; let _routeParams: any = { id: id }; @@ -384,7 +386,7 @@ export class AccountApi extends BaseLoopBackApi { public existsRooms(id: any, fk: any): Observable { let _method: string = "HEAD"; let _url: string = LoopBackConfig.getPath() + "/" + LoopBackConfig.getApiVersion() + - "/Accounts/:id/rooms/rel/:fk"; + "/accounts/:id/rooms/rel/:fk"; let _routeParams: any = { id: id, fk: fk @@ -414,7 +416,7 @@ export class AccountApi extends BaseLoopBackApi { public findByIdAdministrations(id: any, fk: any): Observable { let _method: string = "GET"; let _url: string = LoopBackConfig.getPath() + "/" + LoopBackConfig.getApiVersion() + - "/Accounts/:id/administrations/:fk"; + "/accounts/:id/administrations/:fk"; let _routeParams: any = { id: id, fk: fk @@ -441,7 +443,7 @@ export class AccountApi extends BaseLoopBackApi { public destroyByIdAdministrations(id: any, fk: any): Observable { let _method: string = "DELETE"; let _url: string = LoopBackConfig.getPath() + "/" + LoopBackConfig.getApiVersion() + - "/Accounts/:id/administrations/:fk"; + "/accounts/:id/administrations/:fk"; let _routeParams: any = { id: id, fk: fk @@ -455,7 +457,7 @@ export class AccountApi extends BaseLoopBackApi { public onDestroyByIdAdministrations(id: any): Observable { let _method: string = "DELETE"; let _url: string = "/" + LoopBackConfig.getApiVersion() + - "/Accounts/:id/administrations/:fk"; + "/accounts/:id/administrations/:fk"; let _routeParams: any = { id: id }; @@ -489,7 +491,7 @@ export class AccountApi extends BaseLoopBackApi { public updateByIdAdministrations(id: any, fk: any, data: any = {}): Observable { let _method: string = "PUT"; let _url: string = LoopBackConfig.getPath() + "/" + LoopBackConfig.getApiVersion() + - "/Accounts/:id/administrations/:fk"; + "/accounts/:id/administrations/:fk"; let _routeParams: any = { id: id, fk: fk @@ -505,7 +507,7 @@ export class AccountApi extends BaseLoopBackApi { public onUpdateByIdAdministrations(id: any): Observable { let _method: string = "PUT"; let _url: string = "/" + LoopBackConfig.getApiVersion() + - "/Accounts/:id/administrations/:fk"; + "/accounts/:id/administrations/:fk"; let _routeParams: any = { id: id }; @@ -539,7 +541,7 @@ export class AccountApi extends BaseLoopBackApi { public linkAdministrations(id: any, fk: any, data: any = {}): Observable { let _method: string = "PUT"; let _url: string = LoopBackConfig.getPath() + "/" + LoopBackConfig.getApiVersion() + - "/Accounts/:id/administrations/rel/:fk"; + "/accounts/:id/administrations/rel/:fk"; let _routeParams: any = { id: id, fk: fk @@ -555,7 +557,7 @@ export class AccountApi extends BaseLoopBackApi { public onLinkAdministrations(id: any): Observable { let _method: string = "PUT"; let _url: string = "/" + LoopBackConfig.getApiVersion() + - "/Accounts/:id/administrations/rel/:fk"; + "/accounts/:id/administrations/rel/:fk"; let _routeParams: any = { id: id }; @@ -582,7 +584,7 @@ export class AccountApi extends BaseLoopBackApi { public unlinkAdministrations(id: any, fk: any): Observable { let _method: string = "DELETE"; let _url: string = LoopBackConfig.getPath() + "/" + LoopBackConfig.getApiVersion() + - "/Accounts/:id/administrations/rel/:fk"; + "/accounts/:id/administrations/rel/:fk"; let _routeParams: any = { id: id, fk: fk @@ -596,7 +598,7 @@ export class AccountApi extends BaseLoopBackApi { public onUnlinkAdministrations(id: any): Observable { let _method: string = "DELETE"; let _url: string = "/" + LoopBackConfig.getApiVersion() + - "/Accounts/:id/administrations/rel/:fk"; + "/accounts/:id/administrations/rel/:fk"; let _routeParams: any = { id: id }; @@ -626,7 +628,7 @@ export class AccountApi extends BaseLoopBackApi { public existsAdministrations(id: any, fk: any): Observable { let _method: string = "HEAD"; let _url: string = LoopBackConfig.getPath() + "/" + LoopBackConfig.getApiVersion() + - "/Accounts/:id/administrations/rel/:fk"; + "/accounts/:id/administrations/rel/:fk"; let _routeParams: any = { id: id, fk: fk @@ -656,7 +658,7 @@ export class AccountApi extends BaseLoopBackApi { public getAccessTokens(id: any, filter: LoopBackFilter = {}): Observable { let _method: string = "GET"; let _url: string = LoopBackConfig.getPath() + "/" + LoopBackConfig.getApiVersion() + - "/Accounts/:id/accessTokens"; + "/accounts/:id/accessTokens"; let _routeParams: any = { id: id }; @@ -688,7 +690,7 @@ export class AccountApi extends BaseLoopBackApi { public createAccessTokens(id: any, data: any = {}): Observable { let _method: string = "POST"; let _url: string = LoopBackConfig.getPath() + "/" + LoopBackConfig.getApiVersion() + - "/Accounts/:id/accessTokens"; + "/accounts/:id/accessTokens"; let _routeParams: any = { id: id }; @@ -703,7 +705,7 @@ export class AccountApi extends BaseLoopBackApi { public onCreateAccessTokens(id: any): Observable { let _method: string = "POST"; let _url: string = "/" + LoopBackConfig.getApiVersion() + - "/Accounts/:id/accessTokens"; + "/accounts/:id/accessTokens"; let _routeParams: any = { id: id }; @@ -728,7 +730,7 @@ export class AccountApi extends BaseLoopBackApi { public deleteAccessTokens(id: any): Observable { let _method: string = "DELETE"; let _url: string = LoopBackConfig.getPath() + "/" + LoopBackConfig.getApiVersion() + - "/Accounts/:id/accessTokens"; + "/accounts/:id/accessTokens"; let _routeParams: any = { id: id }; @@ -741,7 +743,7 @@ export class AccountApi extends BaseLoopBackApi { public onDeleteAccessTokens(id: any): Observable { let _method: string = "DELETE"; let _url: string = "/" + LoopBackConfig.getApiVersion() + - "/Accounts/:id/accessTokens"; + "/accounts/:id/accessTokens"; let _routeParams: any = { id: id }; @@ -770,7 +772,7 @@ export class AccountApi extends BaseLoopBackApi { public countAccessTokens(id: any, where: any = {}): Observable { let _method: string = "GET"; let _url: string = LoopBackConfig.getPath() + "/" + LoopBackConfig.getApiVersion() + - "/Accounts/:id/accessTokens/count"; + "/accounts/:id/accessTokens/count"; let _routeParams: any = { id: id }; @@ -800,7 +802,7 @@ export class AccountApi extends BaseLoopBackApi { public getRooms(id: any, filter: LoopBackFilter = {}): Observable { let _method: string = "GET"; let _url: string = LoopBackConfig.getPath() + "/" + LoopBackConfig.getApiVersion() + - "/Accounts/:id/rooms"; + "/accounts/:id/rooms"; let _routeParams: any = { id: id }; @@ -832,7 +834,7 @@ export class AccountApi extends BaseLoopBackApi { public createRooms(id: any, data: any = {}): Observable { let _method: string = "POST"; let _url: string = LoopBackConfig.getPath() + "/" + LoopBackConfig.getApiVersion() + - "/Accounts/:id/rooms"; + "/accounts/:id/rooms"; let _routeParams: any = { id: id }; @@ -847,7 +849,7 @@ export class AccountApi extends BaseLoopBackApi { public onCreateRooms(id: any): Observable { let _method: string = "POST"; let _url: string = "/" + LoopBackConfig.getApiVersion() + - "/Accounts/:id/rooms"; + "/accounts/:id/rooms"; let _routeParams: any = { id: id }; @@ -872,7 +874,7 @@ export class AccountApi extends BaseLoopBackApi { public deleteRooms(id: any): Observable { let _method: string = "DELETE"; let _url: string = LoopBackConfig.getPath() + "/" + LoopBackConfig.getApiVersion() + - "/Accounts/:id/rooms"; + "/accounts/:id/rooms"; let _routeParams: any = { id: id }; @@ -885,7 +887,7 @@ export class AccountApi extends BaseLoopBackApi { public onDeleteRooms(id: any): Observable { let _method: string = "DELETE"; let _url: string = "/" + LoopBackConfig.getApiVersion() + - "/Accounts/:id/rooms"; + "/accounts/:id/rooms"; let _routeParams: any = { id: id }; @@ -914,7 +916,7 @@ export class AccountApi extends BaseLoopBackApi { public countRooms(id: any, where: any = {}): Observable { let _method: string = "GET"; let _url: string = LoopBackConfig.getPath() + "/" + LoopBackConfig.getApiVersion() + - "/Accounts/:id/rooms/count"; + "/accounts/:id/rooms/count"; let _routeParams: any = { id: id }; @@ -944,7 +946,7 @@ export class AccountApi extends BaseLoopBackApi { public getAdministrations(id: any, filter: LoopBackFilter = {}): Observable { let _method: string = "GET"; let _url: string = LoopBackConfig.getPath() + "/" + LoopBackConfig.getApiVersion() + - "/Accounts/:id/administrations"; + "/accounts/:id/administrations"; let _routeParams: any = { id: id }; @@ -976,7 +978,7 @@ export class AccountApi extends BaseLoopBackApi { public createAdministrations(id: any, data: any = {}): Observable { let _method: string = "POST"; let _url: string = LoopBackConfig.getPath() + "/" + LoopBackConfig.getApiVersion() + - "/Accounts/:id/administrations"; + "/accounts/:id/administrations"; let _routeParams: any = { id: id }; @@ -991,7 +993,7 @@ export class AccountApi extends BaseLoopBackApi { public onCreateAdministrations(id: any): Observable { let _method: string = "POST"; let _url: string = "/" + LoopBackConfig.getApiVersion() + - "/Accounts/:id/administrations"; + "/accounts/:id/administrations"; let _routeParams: any = { id: id }; @@ -1016,7 +1018,7 @@ export class AccountApi extends BaseLoopBackApi { public deleteAdministrations(id: any): Observable { let _method: string = "DELETE"; let _url: string = LoopBackConfig.getPath() + "/" + LoopBackConfig.getApiVersion() + - "/Accounts/:id/administrations"; + "/accounts/:id/administrations"; let _routeParams: any = { id: id }; @@ -1029,7 +1031,7 @@ export class AccountApi extends BaseLoopBackApi { public onDeleteAdministrations(id: any): Observable { let _method: string = "DELETE"; let _url: string = "/" + LoopBackConfig.getApiVersion() + - "/Accounts/:id/administrations"; + "/accounts/:id/administrations"; let _routeParams: any = { id: id }; @@ -1058,7 +1060,7 @@ export class AccountApi extends BaseLoopBackApi { public countAdministrations(id: any, where: any = {}): Observable { let _method: string = "GET"; let _url: string = LoopBackConfig.getPath() + "/" + LoopBackConfig.getApiVersion() + - "/Accounts/:id/administrations/count"; + "/accounts/:id/administrations/count"; let _routeParams: any = { id: id }; @@ -1069,513 +1071,6 @@ export class AccountApi extends BaseLoopBackApi { return result; } - /** - * Create a new instance of the model and persist it into the data source. - * - * @param object data Request data. - * - * This method expects a subset of model properties as request parameters. - * - * @returns object An empty reference that will be - * populated with the actual data once the response is returned - * from the server. - * - * - * (The remote method definition does not provide any description. - * This usually means the response is a `Account` object.) - * - */ - public create(data: any = {}): Observable { - let _method: string = "POST"; - let _url: string = LoopBackConfig.getPath() + "/" + LoopBackConfig.getApiVersion() + - "/Accounts"; - let _routeParams: any = {}; - let _postBody: any = { - data: data - }; - let _urlParams: any = {}; - let result = this.request(_method, _url, _routeParams, _urlParams, _postBody); - return result.map((instance: Account) => new Account(instance)); - } - - public onCreate(): Observable { - let _method: string = "POST"; - let _url: string = "/" + LoopBackConfig.getApiVersion() + - "/Accounts"; - let _routeParams: any = {}; - let _postBody: any = {}; - let _urlParams: any = {}; - let result = this.request(_method, _url, _routeParams, _urlParams, _postBody, true); - - return result.map((instance: Account) => new Account(instance)); - } - - /** - * Patch an existing model instance or insert a new one into the data source. - * - * @param object data Request data. - * - * This method expects a subset of model properties as request parameters. - * - * @returns object An empty reference that will be - * populated with the actual data once the response is returned - * from the server. - * - * - * (The remote method definition does not provide any description. - * This usually means the response is a `Account` object.) - * - */ - public upsert(data: any = {}): Observable { - let _method: string = "PUT"; - let _url: string = LoopBackConfig.getPath() + "/" + LoopBackConfig.getApiVersion() + - "/Accounts"; - let _routeParams: any = {}; - let _postBody: any = { - data: data - }; - let _urlParams: any = {}; - let result = this.request(_method, _url, _routeParams, _urlParams, _postBody); - return result.map((instance: Account) => new Account(instance)); - } - - public onUpsert(): Observable { - let _method: string = "PUT"; - let _url: string = "/" + LoopBackConfig.getApiVersion() + - "/Accounts"; - let _routeParams: any = {}; - let _postBody: any = {}; - let _urlParams: any = {}; - let result = this.request(_method, _url, _routeParams, _urlParams, _postBody, true); - - return result.map((instance: Account) => new Account(instance)); - } - - /** - * Replace an existing model instance or insert a new one into the data source. - * - * @param object data Request data. - * - * This method expects a subset of model properties as request parameters. - * - * @returns object An empty reference that will be - * populated with the actual data once the response is returned - * from the server. - * - * - * (The remote method definition does not provide any description. - * This usually means the response is a `Account` object.) - * - */ - public replaceOrCreate(data: any = {}): Observable { - let _method: string = "POST"; - let _url: string = LoopBackConfig.getPath() + "/" + LoopBackConfig.getApiVersion() + - "/Accounts/replaceOrCreate"; - let _routeParams: any = {}; - let _postBody: any = { - data: data - }; - let _urlParams: any = {}; - let result = this.request(_method, _url, _routeParams, _urlParams, _postBody); - return result; - } - - public onReplaceOrCreate(): Observable { - let _method: string = "POST"; - let _url: string = "/" + LoopBackConfig.getApiVersion() + - "/Accounts/replaceOrCreate"; - let _routeParams: any = {}; - let _postBody: any = {}; - let _urlParams: any = {}; - let result = this.request(_method, _url, _routeParams, _urlParams, _postBody, true); - ; - return result; - } - - /** - * Update an existing model instance or insert a new one into the data source based on the where criteria. - * - * @param object where Criteria to match model instances - * - * @param object data Request data. - * - * This method expects a subset of model properties as request parameters. - * - * @returns object An empty reference that will be - * populated with the actual data once the response is returned - * from the server. - * - * - * (The remote method definition does not provide any description. - * This usually means the response is a `Account` object.) - * - */ - public upsertWithWhere(where: any = {}, data: any = {}): Observable { - let _method: string = "POST"; - let _url: string = LoopBackConfig.getPath() + "/" + LoopBackConfig.getApiVersion() + - "/Accounts/upsertWithWhere"; - let _routeParams: any = {}; - let _postBody: any = { - data: data - }; - let _urlParams: any = {}; - if (where) _urlParams.where = where; - let result = this.request(_method, _url, _routeParams, _urlParams, _postBody); - return result.map((instance: Account) => new Account(instance)); - } - - public onUpsertWithWhere(where: any = {}): Observable { - let _method: string = "POST"; - let _url: string = "/" + LoopBackConfig.getApiVersion() + - "/Accounts/upsertWithWhere"; - let _routeParams: any = {}; - let _postBody: any = {}; - let _urlParams: any = {}; - let result = this.request(_method, _url, _routeParams, _urlParams, _postBody, true); - - return result.map((instance: Account) => new Account(instance)); - } - - /** - * Check whether a model instance exists in the data source. - * - * @param any id Model id - * - * @returns object An empty reference that will be - * populated with the actual data once the response is returned - * from the server. - * - * Data properties: - * - * - `exists` – `{boolean}` - - */ - public exists(id: any): Observable { - let _method: string = "GET"; - let _url: string = LoopBackConfig.getPath() + "/" + LoopBackConfig.getApiVersion() + - "/Accounts/:id/exists"; - let _routeParams: any = { - id: id - }; - let _postBody: any = {}; - let _urlParams: any = {}; - let result = this.request(_method, _url, _routeParams, _urlParams, _postBody); - return result; - } - - /** - * Find a model instance by {{id}} from the data source. - * - * @param any id Model id - * - * @param object filter Filter defining fields and include - * - * @returns object An empty reference that will be - * populated with the actual data once the response is returned - * from the server. - * - * - * (The remote method definition does not provide any description. - * This usually means the response is a `Account` object.) - * - */ - public findById(id: any, filter: LoopBackFilter = {}): Observable { - let _method: string = "GET"; - let _url: string = LoopBackConfig.getPath() + "/" + LoopBackConfig.getApiVersion() + - "/Accounts/:id"; - let _routeParams: any = { - id: id - }; - let _postBody: any = {}; - let _urlParams: any = {}; - if (filter) _urlParams.filter = filter; - let result = this.request(_method, _url, _routeParams, _urlParams, _postBody); - return result.map((instance: Account) => new Account(instance)); - } - - /** - * Replace attributes for a model instance and persist it into the data source. - * - * @param any id Model id - * - * @param object data Request data. - * - * This method expects a subset of model properties as request parameters. - * - * @returns object An empty reference that will be - * populated with the actual data once the response is returned - * from the server. - * - * - * (The remote method definition does not provide any description. - * This usually means the response is a `Account` object.) - * - */ - public replaceById(id: any, data: any = {}): Observable { - let _method: string = "POST"; - let _url: string = LoopBackConfig.getPath() + "/" + LoopBackConfig.getApiVersion() + - "/Accounts/:id/replace"; - let _routeParams: any = { - id: id - }; - let _postBody: any = { - data: data - }; - let _urlParams: any = {}; - let result = this.request(_method, _url, _routeParams, _urlParams, _postBody); - return result; - } - - public onReplaceById(id: any): Observable { - let _method: string = "POST"; - let _url: string = "/" + LoopBackConfig.getApiVersion() + - "/Accounts/:id/replace"; - let _routeParams: any = { - id: id - }; - let _postBody: any = {}; - let _urlParams: any = {}; - let result = this.request(_method, _url, _routeParams, _urlParams, _postBody, true); - ; - return result; - } - - /** - * Find all instances of the model matched by filter from the data source. - * - * @param object filter Filter defining fields, where, include, order, offset, and limit - * - * @returns object[] An empty reference that will be - * populated with the actual data once the response is returned - * from the server. - * - * - * (The remote method definition does not provide any description. - * This usually means the response is a `Account` object.) - * - */ - public find(filter: LoopBackFilter = {}): Observable> { - let _method: string = "GET"; - let _url: string = LoopBackConfig.getPath() + "/" + LoopBackConfig.getApiVersion() + - "/Accounts"; - let _routeParams: any = {}; - let _postBody: any = {}; - let _urlParams: any = {}; - if (filter) _urlParams.filter = filter; - let result = this.request(_method, _url, _routeParams, _urlParams, _postBody); - return result.map((instances: Array) => - instances.map((instance: Account) => new Account(instance)) - ); - } - - /** - * Find first instance of the model matched by filter from the data source. - * - * @param object filter Filter defining fields, where, include, order, offset, and limit - * - * @returns object An empty reference that will be - * populated with the actual data once the response is returned - * from the server. - * - * - * (The remote method definition does not provide any description. - * This usually means the response is a `Account` object.) - * - */ - public findOne(filter: LoopBackFilter = {}): Observable { - let _method: string = "GET"; - let _url: string = LoopBackConfig.getPath() + "/" + LoopBackConfig.getApiVersion() + - "/Accounts/findOne"; - let _routeParams: any = {}; - let _postBody: any = {}; - let _urlParams: any = {}; - if (filter) _urlParams.filter = filter; - let result = this.request(_method, _url, _routeParams, _urlParams, _postBody); - return result.map((instance: Account) => new Account(instance)); - } - - /** - * Update instances of the model matched by {{where}} from the data source. - * - * @param object where Criteria to match model instances - * - * @param object data Request data. - * - * This method expects a subset of model properties as request parameters. - * - * @returns object An empty reference that will be - * populated with the actual data once the response is returned - * from the server. - * - * The number of instances updated - */ - public updateAll(where: any = {}, data: any = {}): Observable { - let _method: string = "POST"; - let _url: string = LoopBackConfig.getPath() + "/" + LoopBackConfig.getApiVersion() + - "/Accounts/update"; - let _routeParams: any = {}; - let _postBody: any = { - data: data - }; - let _urlParams: any = {}; - if (where) _urlParams.where = where; - let result = this.request(_method, _url, _routeParams, _urlParams, _postBody); - return result; - } - - public onUpdateAll(where: any = {}): Observable { - let _method: string = "POST"; - let _url: string = "/" + LoopBackConfig.getApiVersion() + - "/Accounts/update"; - let _routeParams: any = {}; - let _postBody: any = {}; - let _urlParams: any = {}; - let result = this.request(_method, _url, _routeParams, _urlParams, _postBody, true); - ; - return result; - } - - /** - * Delete a model instance by {{id}} from the data source. - * - * @param any id Model id - * - * @returns object An empty reference that will be - * populated with the actual data once the response is returned - * from the server. - * - * - * (The remote method definition does not provide any description. - * This usually means the response is a `Account` object.) - * - */ - public deleteById(id: any): Observable { - let _method: string = "DELETE"; - let _url: string = LoopBackConfig.getPath() + "/" + LoopBackConfig.getApiVersion() + - "/Accounts/:id"; - let _routeParams: any = { - id: id - }; - let _postBody: any = {}; - let _urlParams: any = {}; - let result = this.request(_method, _url, _routeParams, _urlParams, _postBody); - return result; - } - - public onDeleteById(id: any): Observable { - let _method: string = "DELETE"; - let _url: string = "/" + LoopBackConfig.getApiVersion() + - "/Accounts/:id"; - let _routeParams: any = { - id: id - }; - let _postBody: any = {}; - let _urlParams: any = {}; - let result = this.request(_method, _url, _routeParams, _urlParams, _postBody, true); - ; - return result; - } - - /** - * Count instances of the model matched by where from the data source. - * - * @param object where Criteria to match model instances - * - * @returns object An empty reference that will be - * populated with the actual data once the response is returned - * from the server. - * - * Data properties: - * - * - `count` – `{number}` - - */ - public count(where: any = {}): Observable { - let _method: string = "GET"; - let _url: string = LoopBackConfig.getPath() + "/" + LoopBackConfig.getApiVersion() + - "/Accounts/count"; - let _routeParams: any = {}; - let _postBody: any = {}; - let _urlParams: any = {}; - if (where) _urlParams.where = where; - let result = this.request(_method, _url, _routeParams, _urlParams, _postBody); - return result; - } - - /** - * Patch attributes for a model instance and persist it into the data source. - * - * @param any id User id - * - * @param object data Request data. - * - * This method expects a subset of model properties as request parameters. - * - * @returns object An empty reference that will be - * populated with the actual data once the response is returned - * from the server. - * - * - * (The remote method definition does not provide any description. - * This usually means the response is a `Account` object.) - * - */ - public updateAttributes(id: any, data: any = {}): Observable { - let _method: string = "PUT"; - let _url: string = LoopBackConfig.getPath() + "/" + LoopBackConfig.getApiVersion() + - "/Accounts/:id"; - let _routeParams: any = { - id: id - }; - let _postBody: any = { - data: data - }; - let _urlParams: any = {}; - let result = this.request(_method, _url, _routeParams, _urlParams, _postBody); - return result; - } - - public onUpdateAttributes(id: any): Observable { - let _method: string = "PUT"; - let _url: string = "/" + LoopBackConfig.getApiVersion() + - "/Accounts/:id"; - let _routeParams: any = { - id: id - }; - let _postBody: any = {}; - let _urlParams: any = {}; - let result = this.request(_method, _url, _routeParams, _urlParams, _postBody, true); - ; - return result; - } - - /** - * Create a change stream. - * - * @param object data Request data. - * - * - `options` – `{object}` - - * - * @returns object An empty reference that will be - * populated with the actual data once the response is returned - * from the server. - * - * Data properties: - * - * - `changes` – `{ReadableStream}` - - */ - public createChangeStream(): Observable { - let _url: string = LoopBackConfig.getPath() + "/" + LoopBackConfig.getApiVersion() + - "/Accounts/change-stream"; - let subject = new Subject(); - if (typeof EventSource !== 'undefined') { - let emit = (msg: any) => subject.next(JSON.parse(msg.data)); - var source = new EventSource(_url); - source.addEventListener('data', emit); - source.onerror = emit; - } else { - console.warn('SDK Builder: EventSource is not supported'); - } - return subject.asObservable(); - } /** * Login a user with username/email and password. * @@ -1604,7 +1099,7 @@ export class AccountApi extends BaseLoopBackApi { public login(credentials: any, include: any = 'user', rememberMe: boolean = true): Observable { let _method: string = "POST"; let _url: string = LoopBackConfig.getPath() + "/" + LoopBackConfig.getApiVersion() + - "/Accounts/login"; + "/accounts/login"; let _routeParams: any = {}; let _postBody: any = { credentials: credentials @@ -1613,7 +1108,8 @@ export class AccountApi extends BaseLoopBackApi { if (include) _urlParams.include = include; let result = this.request(_method, _url, _routeParams, _urlParams, _postBody) .map( - (response: SDKToken) => { + (response: any) => { + response.ttl = parseInt(response.ttl); response.rememberMe = rememberMe; this.auth.setUser(response); this.auth.save(); @@ -1640,7 +1136,7 @@ export class AccountApi extends BaseLoopBackApi { public logout(): Observable { let _method: string = "POST"; let _url: string = LoopBackConfig.getPath() + "/" + LoopBackConfig.getApiVersion() + - "/Accounts/logout"; + "/accounts/logout"; let _routeParams: any = {}; let _postBody: any = {}; let _urlParams: any = {}; @@ -1668,7 +1164,7 @@ export class AccountApi extends BaseLoopBackApi { public confirm(uid: any, token: any, redirect: any = {}): Observable { let _method: string = "GET"; let _url: string = LoopBackConfig.getPath() + "/" + LoopBackConfig.getApiVersion() + - "/Accounts/confirm"; + "/accounts/confirm"; let _routeParams: any = {}; let _postBody: any = {}; let _urlParams: any = {}; @@ -1695,7 +1191,7 @@ export class AccountApi extends BaseLoopBackApi { public resetPassword(options: any): Observable { let _method: string = "POST"; let _url: string = LoopBackConfig.getPath() + "/" + LoopBackConfig.getApiVersion() + - "/Accounts/reset"; + "/accounts/reset"; let _routeParams: any = {}; let _postBody: any = { options: options @@ -1726,7 +1222,7 @@ export class AccountApi extends BaseLoopBackApi { public createManyAccessTokens(id: any, data: Array = []): Observable { let _method: string = "POST"; let _url: string = LoopBackConfig.getPath() + "/" + LoopBackConfig.getApiVersion() + - "/Accounts/:id/accessTokens"; + "/accounts/:id/accessTokens"; let _routeParams: any = { id: id }; @@ -1741,7 +1237,7 @@ export class AccountApi extends BaseLoopBackApi { public onCreateManyAccessTokens(id: any): Observable { let _method: string = "POST"; let _url: string = "/" + LoopBackConfig.getApiVersion() + - "/Accounts/:id/accessTokens"; + "/accounts/:id/accessTokens"; let _routeParams: any = { id: id }; @@ -1773,7 +1269,7 @@ export class AccountApi extends BaseLoopBackApi { public createManyRooms(id: any, data: Array = []): Observable { let _method: string = "POST"; let _url: string = LoopBackConfig.getPath() + "/" + LoopBackConfig.getApiVersion() + - "/Accounts/:id/rooms"; + "/accounts/:id/rooms"; let _routeParams: any = { id: id }; @@ -1788,7 +1284,7 @@ export class AccountApi extends BaseLoopBackApi { public onCreateManyRooms(id: any): Observable { let _method: string = "POST"; let _url: string = "/" + LoopBackConfig.getApiVersion() + - "/Accounts/:id/rooms"; + "/accounts/:id/rooms"; let _routeParams: any = { id: id }; @@ -1820,7 +1316,7 @@ export class AccountApi extends BaseLoopBackApi { public createManyAdministrations(id: any, data: Array = []): Observable { let _method: string = "POST"; let _url: string = LoopBackConfig.getPath() + "/" + LoopBackConfig.getApiVersion() + - "/Accounts/:id/administrations"; + "/accounts/:id/administrations"; let _routeParams: any = { id: id }; @@ -1835,7 +1331,7 @@ export class AccountApi extends BaseLoopBackApi { public onCreateManyAdministrations(id: any): Observable { let _method: string = "POST"; let _url: string = "/" + LoopBackConfig.getApiVersion() + - "/Accounts/:id/administrations"; + "/accounts/:id/administrations"; let _routeParams: any = { id: id }; @@ -1845,51 +1341,6 @@ export class AccountApi extends BaseLoopBackApi { ; return result; } - - /** - * Create a new instance of the model and persist it into the data source. - * - * @param object data Request data. - * - * This method expects a subset of model properties as request parameters. - * - * @returns object[] An empty reference that will be - * populated with the actual data once the response is returned - * from the server. - * - * - * (The remote method definition does not provide any description. - * This usually means the response is a `Account` object.) - * - */ - public createMany(data: Array = []): Observable> { - let _method: string = "POST"; - let _url: string = LoopBackConfig.getPath() + "/" + LoopBackConfig.getApiVersion() + - "/Accounts"; - let _routeParams: any = {}; - let _postBody: any = { - data: data - }; - let _urlParams: any = {}; - let result = this.request(_method, _url, _routeParams, _urlParams, _postBody); - return result.map((instances: Array) => - instances.map((instance: Account) => new Account(instance)) - ); - } - - public onCreateMany(): Observable> { - let _method: string = "POST"; - let _url: string = "/" + LoopBackConfig.getApiVersion() + - "/Accounts"; - let _routeParams: any = {}; - let _postBody: any = {}; - let _urlParams: any = {}; - let result = this.request(_method, _url, _routeParams, _urlParams, _postBody, true); - ; - return result.map((instances: Array) => - instances.map((instance: Account) => new Account(instance)) - ); - } /** * @ngdoc method * @name sdk.Account#getCurrent @@ -1906,7 +1357,7 @@ export class AccountApi extends BaseLoopBackApi { */ public getCurrent(): any { let _method: string = "GET"; - let _url: string = LoopBackConfig.getPath() + "/" + LoopBackConfig.getApiVersion() + "/Accounts" + "/:id"; + let _url: string = LoopBackConfig.getPath() + "/" + LoopBackConfig.getApiVersion() + "/accounts" + "/:id"; let id: any = this.auth.getCurrentUserId(); if (id == null) id = '__anonymous__'; diff --git a/tests/angular2/src/app/shared/sdk/services/custom/ApplicationCredential.ts b/tests/angular2/src/app/shared/sdk/services/custom/ApplicationCredential.ts index 9224deac..519f8cb5 100644 --- a/tests/angular2/src/app/shared/sdk/services/custom/ApplicationCredential.ts +++ b/tests/angular2/src/app/shared/sdk/services/custom/ApplicationCredential.ts @@ -1,9 +1,11 @@ /* tslint:disable */ import { Injectable, Inject, Optional } from '@angular/core'; import { Http, Response } from '@angular/http'; +import { SDKModels } from './SDKModels'; import { BaseLoopBackApi } from '../core/base.service'; import { LoopBackConfig } from '../../lb.config'; import { LoopBackAuth } from '../core/auth.service'; +import { SocketConnections } from '../../sockets/socket.connections'; import { LoopBackFilter, } from '../../models/BaseModels'; import { JSONSearchParams } from '../core/search.params'; import { ErrorHandler } from '../core/error.service'; @@ -12,8 +14,6 @@ import { Observable } from 'rxjs/Observable'; import 'rxjs/add/operator/map'; import { ApplicationCredential } from '../../models/ApplicationCredential'; -// Making Sure EventSource Type is available to avoid compilation issues. -declare var EventSource: any; /** * Api services for the `ApplicationCredential` model. @@ -22,448 +22,14 @@ declare var EventSource: any; export class ApplicationCredentialApi extends BaseLoopBackApi { constructor( - @Inject(Http) http: Http, - @Inject(LoopBackAuth) protected auth: LoopBackAuth, - @Inject(JSONSearchParams) protected searchParams: JSONSearchParams, - @Optional() @Inject(ErrorHandler) errorHandler: ErrorHandler + @Inject(Http) protected http: Http, + @Inject(SocketConnections) protected connections: SocketConnections, + @Inject(SDKModels) protected models: SDKModels, + @Inject(LoopBackAuth) protected auth: LoopBackAuth, + @Inject(JSONSearchParams) protected searchParams: JSONSearchParams, + @Optional() @Inject(ErrorHandler) protected errorHandler: ErrorHandler ) { - super(http, auth, searchParams, errorHandler); - } - - /** - * Create a new instance of the model and persist it into the data source. - * - * @param object data Request data. - * - * This method expects a subset of model properties as request parameters. - * - * @returns object An empty reference that will be - * populated with the actual data once the response is returned - * from the server. - * - * - * (The remote method definition does not provide any description. - * This usually means the response is a `ApplicationCredential` object.) - * - */ - public create(data: any = {}): Observable { - let _method: string = "POST"; - let _url: string = LoopBackConfig.getPath() + "/" + LoopBackConfig.getApiVersion() + - "/ApplicationCredentials"; - let _routeParams: any = {}; - let _postBody: any = { - data: data - }; - let _urlParams: any = {}; - let result = this.request(_method, _url, _routeParams, _urlParams, _postBody); - return result.map((instance: ApplicationCredential) => new ApplicationCredential(instance)); - } - - /** - * Patch an existing model instance or insert a new one into the data source. - * - * @param object data Request data. - * - * This method expects a subset of model properties as request parameters. - * - * @returns object An empty reference that will be - * populated with the actual data once the response is returned - * from the server. - * - * - * (The remote method definition does not provide any description. - * This usually means the response is a `ApplicationCredential` object.) - * - */ - public upsert(data: any = {}): Observable { - let _method: string = "PUT"; - let _url: string = LoopBackConfig.getPath() + "/" + LoopBackConfig.getApiVersion() + - "/ApplicationCredentials"; - let _routeParams: any = {}; - let _postBody: any = { - data: data - }; - let _urlParams: any = {}; - let result = this.request(_method, _url, _routeParams, _urlParams, _postBody); - return result.map((instance: ApplicationCredential) => new ApplicationCredential(instance)); - } - - /** - * Replace an existing model instance or insert a new one into the data source. - * - * @param object data Request data. - * - * This method expects a subset of model properties as request parameters. - * - * @returns object An empty reference that will be - * populated with the actual data once the response is returned - * from the server. - * - * - * (The remote method definition does not provide any description. - * This usually means the response is a `ApplicationCredential` object.) - * - */ - public replaceOrCreate(data: any = {}): Observable { - let _method: string = "POST"; - let _url: string = LoopBackConfig.getPath() + "/" + LoopBackConfig.getApiVersion() + - "/ApplicationCredentials/replaceOrCreate"; - let _routeParams: any = {}; - let _postBody: any = { - data: data - }; - let _urlParams: any = {}; - let result = this.request(_method, _url, _routeParams, _urlParams, _postBody); - return result; - } - - /** - * Update an existing model instance or insert a new one into the data source based on the where criteria. - * - * @param object where Criteria to match model instances - * - * @param object data Request data. - * - * This method expects a subset of model properties as request parameters. - * - * @returns object An empty reference that will be - * populated with the actual data once the response is returned - * from the server. - * - * - * (The remote method definition does not provide any description. - * This usually means the response is a `ApplicationCredential` object.) - * - */ - public upsertWithWhere(where: any = {}, data: any = {}): Observable { - let _method: string = "POST"; - let _url: string = LoopBackConfig.getPath() + "/" + LoopBackConfig.getApiVersion() + - "/ApplicationCredentials/upsertWithWhere"; - let _routeParams: any = {}; - let _postBody: any = { - data: data - }; - let _urlParams: any = {}; - if (where) _urlParams.where = where; - let result = this.request(_method, _url, _routeParams, _urlParams, _postBody); - return result.map((instance: ApplicationCredential) => new ApplicationCredential(instance)); - } - - /** - * Check whether a model instance exists in the data source. - * - * @param any id Model id - * - * @returns object An empty reference that will be - * populated with the actual data once the response is returned - * from the server. - * - * Data properties: - * - * - `exists` – `{boolean}` - - */ - public exists(id: any): Observable { - let _method: string = "GET"; - let _url: string = LoopBackConfig.getPath() + "/" + LoopBackConfig.getApiVersion() + - "/ApplicationCredentials/:id/exists"; - let _routeParams: any = { - id: id - }; - let _postBody: any = {}; - let _urlParams: any = {}; - let result = this.request(_method, _url, _routeParams, _urlParams, _postBody); - return result; - } - - /** - * Find a model instance by {{id}} from the data source. - * - * @param any id Model id - * - * @param object filter Filter defining fields and include - * - * @returns object An empty reference that will be - * populated with the actual data once the response is returned - * from the server. - * - * - * (The remote method definition does not provide any description. - * This usually means the response is a `ApplicationCredential` object.) - * - */ - public findById(id: any, filter: LoopBackFilter = {}): Observable { - let _method: string = "GET"; - let _url: string = LoopBackConfig.getPath() + "/" + LoopBackConfig.getApiVersion() + - "/ApplicationCredentials/:id"; - let _routeParams: any = { - id: id - }; - let _postBody: any = {}; - let _urlParams: any = {}; - if (filter) _urlParams.filter = filter; - let result = this.request(_method, _url, _routeParams, _urlParams, _postBody); - return result.map((instance: ApplicationCredential) => new ApplicationCredential(instance)); - } - - /** - * Replace attributes for a model instance and persist it into the data source. - * - * @param any id Model id - * - * @param object data Request data. - * - * This method expects a subset of model properties as request parameters. - * - * @returns object An empty reference that will be - * populated with the actual data once the response is returned - * from the server. - * - * - * (The remote method definition does not provide any description. - * This usually means the response is a `ApplicationCredential` object.) - * - */ - public replaceById(id: any, data: any = {}): Observable { - let _method: string = "POST"; - let _url: string = LoopBackConfig.getPath() + "/" + LoopBackConfig.getApiVersion() + - "/ApplicationCredentials/:id/replace"; - let _routeParams: any = { - id: id - }; - let _postBody: any = { - data: data - }; - let _urlParams: any = {}; - let result = this.request(_method, _url, _routeParams, _urlParams, _postBody); - return result; - } - - /** - * Find all instances of the model matched by filter from the data source. - * - * @param object filter Filter defining fields, where, include, order, offset, and limit - * - * @returns object[] An empty reference that will be - * populated with the actual data once the response is returned - * from the server. - * - * - * (The remote method definition does not provide any description. - * This usually means the response is a `ApplicationCredential` object.) - * - */ - public find(filter: LoopBackFilter = {}): Observable> { - let _method: string = "GET"; - let _url: string = LoopBackConfig.getPath() + "/" + LoopBackConfig.getApiVersion() + - "/ApplicationCredentials"; - let _routeParams: any = {}; - let _postBody: any = {}; - let _urlParams: any = {}; - if (filter) _urlParams.filter = filter; - let result = this.request(_method, _url, _routeParams, _urlParams, _postBody); - return result.map((instances: Array) => - instances.map((instance: ApplicationCredential) => new ApplicationCredential(instance)) - ); - } - - /** - * Find first instance of the model matched by filter from the data source. - * - * @param object filter Filter defining fields, where, include, order, offset, and limit - * - * @returns object An empty reference that will be - * populated with the actual data once the response is returned - * from the server. - * - * - * (The remote method definition does not provide any description. - * This usually means the response is a `ApplicationCredential` object.) - * - */ - public findOne(filter: LoopBackFilter = {}): Observable { - let _method: string = "GET"; - let _url: string = LoopBackConfig.getPath() + "/" + LoopBackConfig.getApiVersion() + - "/ApplicationCredentials/findOne"; - let _routeParams: any = {}; - let _postBody: any = {}; - let _urlParams: any = {}; - if (filter) _urlParams.filter = filter; - let result = this.request(_method, _url, _routeParams, _urlParams, _postBody); - return result.map((instance: ApplicationCredential) => new ApplicationCredential(instance)); - } - - /** - * Update instances of the model matched by {{where}} from the data source. - * - * @param object where Criteria to match model instances - * - * @param object data Request data. - * - * This method expects a subset of model properties as request parameters. - * - * @returns object An empty reference that will be - * populated with the actual data once the response is returned - * from the server. - * - * The number of instances updated - */ - public updateAll(where: any = {}, data: any = {}): Observable { - let _method: string = "POST"; - let _url: string = LoopBackConfig.getPath() + "/" + LoopBackConfig.getApiVersion() + - "/ApplicationCredentials/update"; - let _routeParams: any = {}; - let _postBody: any = { - data: data - }; - let _urlParams: any = {}; - if (where) _urlParams.where = where; - let result = this.request(_method, _url, _routeParams, _urlParams, _postBody); - return result; - } - - /** - * Delete a model instance by {{id}} from the data source. - * - * @param any id Model id - * - * @returns object An empty reference that will be - * populated with the actual data once the response is returned - * from the server. - * - * - * (The remote method definition does not provide any description. - * This usually means the response is a `ApplicationCredential` object.) - * - */ - public deleteById(id: any): Observable { - let _method: string = "DELETE"; - let _url: string = LoopBackConfig.getPath() + "/" + LoopBackConfig.getApiVersion() + - "/ApplicationCredentials/:id"; - let _routeParams: any = { - id: id - }; - let _postBody: any = {}; - let _urlParams: any = {}; - let result = this.request(_method, _url, _routeParams, _urlParams, _postBody); - return result; - } - - /** - * Count instances of the model matched by where from the data source. - * - * @param object where Criteria to match model instances - * - * @returns object An empty reference that will be - * populated with the actual data once the response is returned - * from the server. - * - * Data properties: - * - * - `count` – `{number}` - - */ - public count(where: any = {}): Observable { - let _method: string = "GET"; - let _url: string = LoopBackConfig.getPath() + "/" + LoopBackConfig.getApiVersion() + - "/ApplicationCredentials/count"; - let _routeParams: any = {}; - let _postBody: any = {}; - let _urlParams: any = {}; - if (where) _urlParams.where = where; - let result = this.request(_method, _url, _routeParams, _urlParams, _postBody); - return result; - } - - /** - * Patch attributes for a model instance and persist it into the data source. - * - * @param any id PersistedModel id - * - * @param object data Request data. - * - * This method expects a subset of model properties as request parameters. - * - * @returns object An empty reference that will be - * populated with the actual data once the response is returned - * from the server. - * - * - * (The remote method definition does not provide any description. - * This usually means the response is a `ApplicationCredential` object.) - * - */ - public updateAttributes(id: any, data: any = {}): Observable { - let _method: string = "PUT"; - let _url: string = LoopBackConfig.getPath() + "/" + LoopBackConfig.getApiVersion() + - "/ApplicationCredentials/:id"; - let _routeParams: any = { - id: id - }; - let _postBody: any = { - data: data - }; - let _urlParams: any = {}; - let result = this.request(_method, _url, _routeParams, _urlParams, _postBody); - return result; - } - - /** - * Create a change stream. - * - * @param object data Request data. - * - * - `options` – `{object}` - - * - * @returns object An empty reference that will be - * populated with the actual data once the response is returned - * from the server. - * - * Data properties: - * - * - `changes` – `{ReadableStream}` - - */ - public createChangeStream(): Observable { - let _url: string = LoopBackConfig.getPath() + "/" + LoopBackConfig.getApiVersion() + - "/ApplicationCredentials/change-stream"; - let subject = new Subject(); - if (typeof EventSource !== 'undefined') { - let emit = (msg: any) => subject.next(JSON.parse(msg.data)); - var source = new EventSource(_url); - source.addEventListener('data', emit); - source.onerror = emit; - } else { - console.warn('SDK Builder: EventSource is not supported'); - } - return subject.asObservable(); - } - /** - * Create a new instance of the model and persist it into the data source. - * - * @param object data Request data. - * - * This method expects a subset of model properties as request parameters. - * - * @returns object[] An empty reference that will be - * populated with the actual data once the response is returned - * from the server. - * - * - * (The remote method definition does not provide any description. - * This usually means the response is a `ApplicationCredential` object.) - * - */ - public createMany(data: Array = []): Observable> { - let _method: string = "POST"; - let _url: string = LoopBackConfig.getPath() + "/" + LoopBackConfig.getApiVersion() + - "/ApplicationCredentials"; - let _routeParams: any = {}; - let _postBody: any = { - data: data - }; - let _urlParams: any = {}; - let result = this.request(_method, _url, _routeParams, _urlParams, _postBody); - return result.map((instances: Array) => - instances.map((instance: ApplicationCredential) => new ApplicationCredential(instance)) - ); + super(http, connections, models, auth, searchParams, errorHandler); } /** diff --git a/tests/angular2/src/app/shared/sdk/services/custom/Category.ts b/tests/angular2/src/app/shared/sdk/services/custom/Category.ts index a6326990..d8d2956d 100644 --- a/tests/angular2/src/app/shared/sdk/services/custom/Category.ts +++ b/tests/angular2/src/app/shared/sdk/services/custom/Category.ts @@ -1,9 +1,11 @@ /* tslint:disable */ import { Injectable, Inject, Optional } from '@angular/core'; import { Http, Response } from '@angular/http'; +import { SDKModels } from './SDKModels'; import { BaseLoopBackApi } from '../core/base.service'; import { LoopBackConfig } from '../../lb.config'; import { LoopBackAuth } from '../core/auth.service'; +import { SocketConnections } from '../../sockets/socket.connections'; import { LoopBackFilter, } from '../../models/BaseModels'; import { JSONSearchParams } from '../core/search.params'; import { ErrorHandler } from '../core/error.service'; @@ -13,8 +15,6 @@ import 'rxjs/add/operator/map'; import { Category } from '../../models/Category'; import { Room } from '../../models/Room'; -// Making Sure EventSource Type is available to avoid compilation issues. -declare var EventSource: any; /** * Api services for the `Category` model. @@ -23,12 +23,14 @@ declare var EventSource: any; export class CategoryApi extends BaseLoopBackApi { constructor( - @Inject(Http) http: Http, - @Inject(LoopBackAuth) protected auth: LoopBackAuth, - @Inject(JSONSearchParams) protected searchParams: JSONSearchParams, - @Optional() @Inject(ErrorHandler) errorHandler: ErrorHandler + @Inject(Http) protected http: Http, + @Inject(SocketConnections) protected connections: SocketConnections, + @Inject(SDKModels) protected models: SDKModels, + @Inject(LoopBackAuth) protected auth: LoopBackAuth, + @Inject(JSONSearchParams) protected searchParams: JSONSearchParams, + @Optional() @Inject(ErrorHandler) protected errorHandler: ErrorHandler ) { - super(http, auth, searchParams, errorHandler); + super(http, connections, models, auth, searchParams, errorHandler); } /** @@ -333,411 +335,6 @@ export class CategoryApi extends BaseLoopBackApi { return result; } - /** - * Create a new instance of the model and persist it into the data source. - * - * @param object data Request data. - * - * This method expects a subset of model properties as request parameters. - * - * @returns object An empty reference that will be - * populated with the actual data once the response is returned - * from the server. - * - * - * (The remote method definition does not provide any description. - * This usually means the response is a `Category` object.) - * - */ - public create(data: any = {}): Observable { - let _method: string = "POST"; - let _url: string = LoopBackConfig.getPath() + "/" + LoopBackConfig.getApiVersion() + - "/Categories"; - let _routeParams: any = {}; - let _postBody: any = { - data: data - }; - let _urlParams: any = {}; - let result = this.request(_method, _url, _routeParams, _urlParams, _postBody); - return result.map((instance: Category) => new Category(instance)); - } - - /** - * Patch an existing model instance or insert a new one into the data source. - * - * @param object data Request data. - * - * This method expects a subset of model properties as request parameters. - * - * @returns object An empty reference that will be - * populated with the actual data once the response is returned - * from the server. - * - * - * (The remote method definition does not provide any description. - * This usually means the response is a `Category` object.) - * - */ - public upsert(data: any = {}): Observable { - let _method: string = "PUT"; - let _url: string = LoopBackConfig.getPath() + "/" + LoopBackConfig.getApiVersion() + - "/Categories"; - let _routeParams: any = {}; - let _postBody: any = { - data: data - }; - let _urlParams: any = {}; - let result = this.request(_method, _url, _routeParams, _urlParams, _postBody); - return result.map((instance: Category) => new Category(instance)); - } - - /** - * Replace an existing model instance or insert a new one into the data source. - * - * @param object data Request data. - * - * This method expects a subset of model properties as request parameters. - * - * @returns object An empty reference that will be - * populated with the actual data once the response is returned - * from the server. - * - * - * (The remote method definition does not provide any description. - * This usually means the response is a `Category` object.) - * - */ - public replaceOrCreate(data: any = {}): Observable { - let _method: string = "POST"; - let _url: string = LoopBackConfig.getPath() + "/" + LoopBackConfig.getApiVersion() + - "/Categories/replaceOrCreate"; - let _routeParams: any = {}; - let _postBody: any = { - data: data - }; - let _urlParams: any = {}; - let result = this.request(_method, _url, _routeParams, _urlParams, _postBody); - return result; - } - - /** - * Update an existing model instance or insert a new one into the data source based on the where criteria. - * - * @param object where Criteria to match model instances - * - * @param object data Request data. - * - * This method expects a subset of model properties as request parameters. - * - * @returns object An empty reference that will be - * populated with the actual data once the response is returned - * from the server. - * - * - * (The remote method definition does not provide any description. - * This usually means the response is a `Category` object.) - * - */ - public upsertWithWhere(where: any = {}, data: any = {}): Observable { - let _method: string = "POST"; - let _url: string = LoopBackConfig.getPath() + "/" + LoopBackConfig.getApiVersion() + - "/Categories/upsertWithWhere"; - let _routeParams: any = {}; - let _postBody: any = { - data: data - }; - let _urlParams: any = {}; - if (where) _urlParams.where = where; - let result = this.request(_method, _url, _routeParams, _urlParams, _postBody); - return result.map((instance: Category) => new Category(instance)); - } - - /** - * Check whether a model instance exists in the data source. - * - * @param any id Model id - * - * @returns object An empty reference that will be - * populated with the actual data once the response is returned - * from the server. - * - * Data properties: - * - * - `exists` – `{boolean}` - - */ - public exists(id: any): Observable { - let _method: string = "GET"; - let _url: string = LoopBackConfig.getPath() + "/" + LoopBackConfig.getApiVersion() + - "/Categories/:id/exists"; - let _routeParams: any = { - id: id - }; - let _postBody: any = {}; - let _urlParams: any = {}; - let result = this.request(_method, _url, _routeParams, _urlParams, _postBody); - return result; - } - - /** - * Find a model instance by {{id}} from the data source. - * - * @param any id Model id - * - * @param object filter Filter defining fields and include - * - * @returns object An empty reference that will be - * populated with the actual data once the response is returned - * from the server. - * - * - * (The remote method definition does not provide any description. - * This usually means the response is a `Category` object.) - * - */ - public findById(id: any, filter: LoopBackFilter = {}): Observable { - let _method: string = "GET"; - let _url: string = LoopBackConfig.getPath() + "/" + LoopBackConfig.getApiVersion() + - "/Categories/:id"; - let _routeParams: any = { - id: id - }; - let _postBody: any = {}; - let _urlParams: any = {}; - if (filter) _urlParams.filter = filter; - let result = this.request(_method, _url, _routeParams, _urlParams, _postBody); - return result.map((instance: Category) => new Category(instance)); - } - - /** - * Replace attributes for a model instance and persist it into the data source. - * - * @param any id Model id - * - * @param object data Request data. - * - * This method expects a subset of model properties as request parameters. - * - * @returns object An empty reference that will be - * populated with the actual data once the response is returned - * from the server. - * - * - * (The remote method definition does not provide any description. - * This usually means the response is a `Category` object.) - * - */ - public replaceById(id: any, data: any = {}): Observable { - let _method: string = "POST"; - let _url: string = LoopBackConfig.getPath() + "/" + LoopBackConfig.getApiVersion() + - "/Categories/:id/replace"; - let _routeParams: any = { - id: id - }; - let _postBody: any = { - data: data - }; - let _urlParams: any = {}; - let result = this.request(_method, _url, _routeParams, _urlParams, _postBody); - return result; - } - - /** - * Find all instances of the model matched by filter from the data source. - * - * @param object filter Filter defining fields, where, include, order, offset, and limit - * - * @returns object[] An empty reference that will be - * populated with the actual data once the response is returned - * from the server. - * - * - * (The remote method definition does not provide any description. - * This usually means the response is a `Category` object.) - * - */ - public find(filter: LoopBackFilter = {}): Observable> { - let _method: string = "GET"; - let _url: string = LoopBackConfig.getPath() + "/" + LoopBackConfig.getApiVersion() + - "/Categories"; - let _routeParams: any = {}; - let _postBody: any = {}; - let _urlParams: any = {}; - if (filter) _urlParams.filter = filter; - let result = this.request(_method, _url, _routeParams, _urlParams, _postBody); - return result.map((instances: Array) => - instances.map((instance: Category) => new Category(instance)) - ); - } - - /** - * Find first instance of the model matched by filter from the data source. - * - * @param object filter Filter defining fields, where, include, order, offset, and limit - * - * @returns object An empty reference that will be - * populated with the actual data once the response is returned - * from the server. - * - * - * (The remote method definition does not provide any description. - * This usually means the response is a `Category` object.) - * - */ - public findOne(filter: LoopBackFilter = {}): Observable { - let _method: string = "GET"; - let _url: string = LoopBackConfig.getPath() + "/" + LoopBackConfig.getApiVersion() + - "/Categories/findOne"; - let _routeParams: any = {}; - let _postBody: any = {}; - let _urlParams: any = {}; - if (filter) _urlParams.filter = filter; - let result = this.request(_method, _url, _routeParams, _urlParams, _postBody); - return result.map((instance: Category) => new Category(instance)); - } - - /** - * Update instances of the model matched by {{where}} from the data source. - * - * @param object where Criteria to match model instances - * - * @param object data Request data. - * - * This method expects a subset of model properties as request parameters. - * - * @returns object An empty reference that will be - * populated with the actual data once the response is returned - * from the server. - * - * The number of instances updated - */ - public updateAll(where: any = {}, data: any = {}): Observable { - let _method: string = "POST"; - let _url: string = LoopBackConfig.getPath() + "/" + LoopBackConfig.getApiVersion() + - "/Categories/update"; - let _routeParams: any = {}; - let _postBody: any = { - data: data - }; - let _urlParams: any = {}; - if (where) _urlParams.where = where; - let result = this.request(_method, _url, _routeParams, _urlParams, _postBody); - return result; - } - - /** - * Delete a model instance by {{id}} from the data source. - * - * @param any id Model id - * - * @returns object An empty reference that will be - * populated with the actual data once the response is returned - * from the server. - * - * - * (The remote method definition does not provide any description. - * This usually means the response is a `Category` object.) - * - */ - public deleteById(id: any): Observable { - let _method: string = "DELETE"; - let _url: string = LoopBackConfig.getPath() + "/" + LoopBackConfig.getApiVersion() + - "/Categories/:id"; - let _routeParams: any = { - id: id - }; - let _postBody: any = {}; - let _urlParams: any = {}; - let result = this.request(_method, _url, _routeParams, _urlParams, _postBody); - return result; - } - - /** - * Count instances of the model matched by where from the data source. - * - * @param object where Criteria to match model instances - * - * @returns object An empty reference that will be - * populated with the actual data once the response is returned - * from the server. - * - * Data properties: - * - * - `count` – `{number}` - - */ - public count(where: any = {}): Observable { - let _method: string = "GET"; - let _url: string = LoopBackConfig.getPath() + "/" + LoopBackConfig.getApiVersion() + - "/Categories/count"; - let _routeParams: any = {}; - let _postBody: any = {}; - let _urlParams: any = {}; - if (where) _urlParams.where = where; - let result = this.request(_method, _url, _routeParams, _urlParams, _postBody); - return result; - } - - /** - * Patch attributes for a model instance and persist it into the data source. - * - * @param any id PersistedModel id - * - * @param object data Request data. - * - * This method expects a subset of model properties as request parameters. - * - * @returns object An empty reference that will be - * populated with the actual data once the response is returned - * from the server. - * - * - * (The remote method definition does not provide any description. - * This usually means the response is a `Category` object.) - * - */ - public updateAttributes(id: any, data: any = {}): Observable { - let _method: string = "PUT"; - let _url: string = LoopBackConfig.getPath() + "/" + LoopBackConfig.getApiVersion() + - "/Categories/:id"; - let _routeParams: any = { - id: id - }; - let _postBody: any = { - data: data - }; - let _urlParams: any = {}; - let result = this.request(_method, _url, _routeParams, _urlParams, _postBody); - return result; - } - - /** - * Create a change stream. - * - * @param object data Request data. - * - * - `options` – `{object}` - - * - * @returns object An empty reference that will be - * populated with the actual data once the response is returned - * from the server. - * - * Data properties: - * - * - `changes` – `{ReadableStream}` - - */ - public createChangeStream(): Observable { - let _url: string = LoopBackConfig.getPath() + "/" + LoopBackConfig.getApiVersion() + - "/Categories/change-stream"; - let subject = new Subject(); - if (typeof EventSource !== 'undefined') { - let emit = (msg: any) => subject.next(JSON.parse(msg.data)); - var source = new EventSource(_url); - source.addEventListener('data', emit); - source.onerror = emit; - } else { - console.warn('SDK Builder: EventSource is not supported'); - } - return subject.asObservable(); - } /** * Creates a new instance in rooms of this model. * @@ -771,37 +368,6 @@ export class CategoryApi extends BaseLoopBackApi { return result; } - /** - * Create a new instance of the model and persist it into the data source. - * - * @param object data Request data. - * - * This method expects a subset of model properties as request parameters. - * - * @returns object[] An empty reference that will be - * populated with the actual data once the response is returned - * from the server. - * - * - * (The remote method definition does not provide any description. - * This usually means the response is a `Category` object.) - * - */ - public createMany(data: Array = []): Observable> { - let _method: string = "POST"; - let _url: string = LoopBackConfig.getPath() + "/" + LoopBackConfig.getApiVersion() + - "/Categories"; - let _routeParams: any = {}; - let _postBody: any = { - data: data - }; - let _urlParams: any = {}; - let result = this.request(_method, _url, _routeParams, _urlParams, _postBody); - return result.map((instances: Array) => - instances.map((instance: Category) => new Category(instance)) - ); - } - /** * The name of the model represented by this $resource, * i.e. `Category`. diff --git a/tests/angular2/src/app/shared/sdk/services/custom/Core.ts b/tests/angular2/src/app/shared/sdk/services/custom/Core.ts index 6d115f1d..346dbcd0 100644 --- a/tests/angular2/src/app/shared/sdk/services/custom/Core.ts +++ b/tests/angular2/src/app/shared/sdk/services/custom/Core.ts @@ -1,9 +1,11 @@ /* tslint:disable */ import { Injectable, Inject, Optional } from '@angular/core'; import { Http, Response } from '@angular/http'; +import { SDKModels } from './SDKModels'; import { BaseLoopBackApi } from '../core/base.service'; import { LoopBackConfig } from '../../lb.config'; import { LoopBackAuth } from '../core/auth.service'; +import { SocketConnections } from '../../sockets/socket.connections'; import { LoopBackFilter, } from '../../models/BaseModels'; import { JSONSearchParams } from '../core/search.params'; import { ErrorHandler } from '../core/error.service'; @@ -12,8 +14,6 @@ import { Observable } from 'rxjs/Observable'; import 'rxjs/add/operator/map'; import { Core } from '../../models/Core'; -// Making Sure EventSource Type is available to avoid compilation issues. -declare var EventSource: any; /** * Api services for the `Core` model. @@ -22,12 +22,14 @@ declare var EventSource: any; export class CoreApi extends BaseLoopBackApi { constructor( - @Inject(Http) http: Http, - @Inject(LoopBackAuth) protected auth: LoopBackAuth, - @Inject(JSONSearchParams) protected searchParams: JSONSearchParams, - @Optional() @Inject(ErrorHandler) errorHandler: ErrorHandler + @Inject(Http) protected http: Http, + @Inject(SocketConnections) protected connections: SocketConnections, + @Inject(SDKModels) protected models: SDKModels, + @Inject(LoopBackAuth) protected auth: LoopBackAuth, + @Inject(JSONSearchParams) protected searchParams: JSONSearchParams, + @Optional() @Inject(ErrorHandler) protected errorHandler: ErrorHandler ) { - super(http, auth, searchParams, errorHandler); + super(http, connections, models, auth, searchParams, errorHandler); } /** diff --git a/tests/angular2/src/app/shared/sdk/services/custom/Message.ts b/tests/angular2/src/app/shared/sdk/services/custom/Message.ts index fd9f12a3..873549b0 100644 --- a/tests/angular2/src/app/shared/sdk/services/custom/Message.ts +++ b/tests/angular2/src/app/shared/sdk/services/custom/Message.ts @@ -1,9 +1,11 @@ /* tslint:disable */ import { Injectable, Inject, Optional } from '@angular/core'; import { Http, Response } from '@angular/http'; +import { SDKModels } from './SDKModels'; import { BaseLoopBackApi } from '../core/base.service'; import { LoopBackConfig } from '../../lb.config'; import { LoopBackAuth } from '../core/auth.service'; +import { SocketConnections } from '../../sockets/socket.connections'; import { LoopBackFilter, } from '../../models/BaseModels'; import { JSONSearchParams } from '../core/search.params'; import { ErrorHandler } from '../core/error.service'; @@ -13,8 +15,6 @@ import 'rxjs/add/operator/map'; import { Message } from '../../models/Message'; import { Room } from '../../models/Room'; -// Making Sure EventSource Type is available to avoid compilation issues. -declare var EventSource: any; /** * Api services for the `Message` model. @@ -23,12 +23,14 @@ declare var EventSource: any; export class MessageApi extends BaseLoopBackApi { constructor( - @Inject(Http) http: Http, - @Inject(LoopBackAuth) protected auth: LoopBackAuth, - @Inject(JSONSearchParams) protected searchParams: JSONSearchParams, - @Optional() @Inject(ErrorHandler) errorHandler: ErrorHandler + @Inject(Http) protected http: Http, + @Inject(SocketConnections) protected connections: SocketConnections, + @Inject(SDKModels) protected models: SDKModels, + @Inject(LoopBackAuth) protected auth: LoopBackAuth, + @Inject(JSONSearchParams) protected searchParams: JSONSearchParams, + @Optional() @Inject(ErrorHandler) protected errorHandler: ErrorHandler ) { - super(http, auth, searchParams, errorHandler); + super(http, connections, models, auth, searchParams, errorHandler); } /** @@ -509,411 +511,6 @@ export class MessageApi extends BaseLoopBackApi { return result; } - /** - * Create a new instance of the model and persist it into the data source. - * - * @param object data Request data. - * - * This method expects a subset of model properties as request parameters. - * - * @returns object An empty reference that will be - * populated with the actual data once the response is returned - * from the server. - * - * - * (The remote method definition does not provide any description. - * This usually means the response is a `Message` object.) - * - */ - public create(data: any = {}): Observable { - let _method: string = "POST"; - let _url: string = LoopBackConfig.getPath() + "/" + LoopBackConfig.getApiVersion() + - "/messages"; - let _routeParams: any = {}; - let _postBody: any = { - data: data - }; - let _urlParams: any = {}; - let result = this.request(_method, _url, _routeParams, _urlParams, _postBody); - return result.map((instance: Message) => new Message(instance)); - } - - /** - * Patch an existing model instance or insert a new one into the data source. - * - * @param object data Request data. - * - * This method expects a subset of model properties as request parameters. - * - * @returns object An empty reference that will be - * populated with the actual data once the response is returned - * from the server. - * - * - * (The remote method definition does not provide any description. - * This usually means the response is a `Message` object.) - * - */ - public upsert(data: any = {}): Observable { - let _method: string = "PUT"; - let _url: string = LoopBackConfig.getPath() + "/" + LoopBackConfig.getApiVersion() + - "/messages"; - let _routeParams: any = {}; - let _postBody: any = { - data: data - }; - let _urlParams: any = {}; - let result = this.request(_method, _url, _routeParams, _urlParams, _postBody); - return result.map((instance: Message) => new Message(instance)); - } - - /** - * Replace an existing model instance or insert a new one into the data source. - * - * @param object data Request data. - * - * This method expects a subset of model properties as request parameters. - * - * @returns object An empty reference that will be - * populated with the actual data once the response is returned - * from the server. - * - * - * (The remote method definition does not provide any description. - * This usually means the response is a `Message` object.) - * - */ - public replaceOrCreate(data: any = {}): Observable { - let _method: string = "POST"; - let _url: string = LoopBackConfig.getPath() + "/" + LoopBackConfig.getApiVersion() + - "/messages/replaceOrCreate"; - let _routeParams: any = {}; - let _postBody: any = { - data: data - }; - let _urlParams: any = {}; - let result = this.request(_method, _url, _routeParams, _urlParams, _postBody); - return result; - } - - /** - * Update an existing model instance or insert a new one into the data source based on the where criteria. - * - * @param object where Criteria to match model instances - * - * @param object data Request data. - * - * This method expects a subset of model properties as request parameters. - * - * @returns object An empty reference that will be - * populated with the actual data once the response is returned - * from the server. - * - * - * (The remote method definition does not provide any description. - * This usually means the response is a `Message` object.) - * - */ - public upsertWithWhere(where: any = {}, data: any = {}): Observable { - let _method: string = "POST"; - let _url: string = LoopBackConfig.getPath() + "/" + LoopBackConfig.getApiVersion() + - "/messages/upsertWithWhere"; - let _routeParams: any = {}; - let _postBody: any = { - data: data - }; - let _urlParams: any = {}; - if (where) _urlParams.where = where; - let result = this.request(_method, _url, _routeParams, _urlParams, _postBody); - return result.map((instance: Message) => new Message(instance)); - } - - /** - * Check whether a model instance exists in the data source. - * - * @param any id Model id - * - * @returns object An empty reference that will be - * populated with the actual data once the response is returned - * from the server. - * - * Data properties: - * - * - `exists` – `{boolean}` - - */ - public exists(id: any): Observable { - let _method: string = "GET"; - let _url: string = LoopBackConfig.getPath() + "/" + LoopBackConfig.getApiVersion() + - "/messages/:id/exists"; - let _routeParams: any = { - id: id - }; - let _postBody: any = {}; - let _urlParams: any = {}; - let result = this.request(_method, _url, _routeParams, _urlParams, _postBody); - return result; - } - - /** - * Find a model instance by {{id}} from the data source. - * - * @param any id Model id - * - * @param object filter Filter defining fields and include - * - * @returns object An empty reference that will be - * populated with the actual data once the response is returned - * from the server. - * - * - * (The remote method definition does not provide any description. - * This usually means the response is a `Message` object.) - * - */ - public findById(id: any, filter: LoopBackFilter = {}): Observable { - let _method: string = "GET"; - let _url: string = LoopBackConfig.getPath() + "/" + LoopBackConfig.getApiVersion() + - "/messages/:id"; - let _routeParams: any = { - id: id - }; - let _postBody: any = {}; - let _urlParams: any = {}; - if (filter) _urlParams.filter = filter; - let result = this.request(_method, _url, _routeParams, _urlParams, _postBody); - return result.map((instance: Message) => new Message(instance)); - } - - /** - * Replace attributes for a model instance and persist it into the data source. - * - * @param any id Model id - * - * @param object data Request data. - * - * This method expects a subset of model properties as request parameters. - * - * @returns object An empty reference that will be - * populated with the actual data once the response is returned - * from the server. - * - * - * (The remote method definition does not provide any description. - * This usually means the response is a `Message` object.) - * - */ - public replaceById(id: any, data: any = {}): Observable { - let _method: string = "POST"; - let _url: string = LoopBackConfig.getPath() + "/" + LoopBackConfig.getApiVersion() + - "/messages/:id/replace"; - let _routeParams: any = { - id: id - }; - let _postBody: any = { - data: data - }; - let _urlParams: any = {}; - let result = this.request(_method, _url, _routeParams, _urlParams, _postBody); - return result; - } - - /** - * Find all instances of the model matched by filter from the data source. - * - * @param object filter Filter defining fields, where, include, order, offset, and limit - * - * @returns object[] An empty reference that will be - * populated with the actual data once the response is returned - * from the server. - * - * - * (The remote method definition does not provide any description. - * This usually means the response is a `Message` object.) - * - */ - public find(filter: LoopBackFilter = {}): Observable> { - let _method: string = "GET"; - let _url: string = LoopBackConfig.getPath() + "/" + LoopBackConfig.getApiVersion() + - "/messages"; - let _routeParams: any = {}; - let _postBody: any = {}; - let _urlParams: any = {}; - if (filter) _urlParams.filter = filter; - let result = this.request(_method, _url, _routeParams, _urlParams, _postBody); - return result.map((instances: Array) => - instances.map((instance: Message) => new Message(instance)) - ); - } - - /** - * Find first instance of the model matched by filter from the data source. - * - * @param object filter Filter defining fields, where, include, order, offset, and limit - * - * @returns object An empty reference that will be - * populated with the actual data once the response is returned - * from the server. - * - * - * (The remote method definition does not provide any description. - * This usually means the response is a `Message` object.) - * - */ - public findOne(filter: LoopBackFilter = {}): Observable { - let _method: string = "GET"; - let _url: string = LoopBackConfig.getPath() + "/" + LoopBackConfig.getApiVersion() + - "/messages/findOne"; - let _routeParams: any = {}; - let _postBody: any = {}; - let _urlParams: any = {}; - if (filter) _urlParams.filter = filter; - let result = this.request(_method, _url, _routeParams, _urlParams, _postBody); - return result.map((instance: Message) => new Message(instance)); - } - - /** - * Update instances of the model matched by {{where}} from the data source. - * - * @param object where Criteria to match model instances - * - * @param object data Request data. - * - * This method expects a subset of model properties as request parameters. - * - * @returns object An empty reference that will be - * populated with the actual data once the response is returned - * from the server. - * - * The number of instances updated - */ - public updateAll(where: any = {}, data: any = {}): Observable { - let _method: string = "POST"; - let _url: string = LoopBackConfig.getPath() + "/" + LoopBackConfig.getApiVersion() + - "/messages/update"; - let _routeParams: any = {}; - let _postBody: any = { - data: data - }; - let _urlParams: any = {}; - if (where) _urlParams.where = where; - let result = this.request(_method, _url, _routeParams, _urlParams, _postBody); - return result; - } - - /** - * Delete a model instance by {{id}} from the data source. - * - * @param any id Model id - * - * @returns object An empty reference that will be - * populated with the actual data once the response is returned - * from the server. - * - * - * (The remote method definition does not provide any description. - * This usually means the response is a `Message` object.) - * - */ - public deleteById(id: any): Observable { - let _method: string = "DELETE"; - let _url: string = LoopBackConfig.getPath() + "/" + LoopBackConfig.getApiVersion() + - "/messages/:id"; - let _routeParams: any = { - id: id - }; - let _postBody: any = {}; - let _urlParams: any = {}; - let result = this.request(_method, _url, _routeParams, _urlParams, _postBody); - return result; - } - - /** - * Count instances of the model matched by where from the data source. - * - * @param object where Criteria to match model instances - * - * @returns object An empty reference that will be - * populated with the actual data once the response is returned - * from the server. - * - * Data properties: - * - * - `count` – `{number}` - - */ - public count(where: any = {}): Observable { - let _method: string = "GET"; - let _url: string = LoopBackConfig.getPath() + "/" + LoopBackConfig.getApiVersion() + - "/messages/count"; - let _routeParams: any = {}; - let _postBody: any = {}; - let _urlParams: any = {}; - if (where) _urlParams.where = where; - let result = this.request(_method, _url, _routeParams, _urlParams, _postBody); - return result; - } - - /** - * Patch attributes for a model instance and persist it into the data source. - * - * @param any id PersistedModel id - * - * @param object data Request data. - * - * This method expects a subset of model properties as request parameters. - * - * @returns object An empty reference that will be - * populated with the actual data once the response is returned - * from the server. - * - * - * (The remote method definition does not provide any description. - * This usually means the response is a `Message` object.) - * - */ - public updateAttributes(id: any, data: any = {}): Observable { - let _method: string = "PUT"; - let _url: string = LoopBackConfig.getPath() + "/" + LoopBackConfig.getApiVersion() + - "/messages/:id"; - let _routeParams: any = { - id: id - }; - let _postBody: any = { - data: data - }; - let _urlParams: any = {}; - let result = this.request(_method, _url, _routeParams, _urlParams, _postBody); - return result; - } - - /** - * Create a change stream. - * - * @param object data Request data. - * - * - `options` – `{object}` - - * - * @returns object An empty reference that will be - * populated with the actual data once the response is returned - * from the server. - * - * Data properties: - * - * - `changes` – `{ReadableStream}` - - */ - public createChangeStream(): Observable { - let _url: string = LoopBackConfig.getPath() + "/" + LoopBackConfig.getApiVersion() + - "/messages/change-stream"; - let subject = new Subject(); - if (typeof EventSource !== 'undefined') { - let emit = (msg: any) => subject.next(JSON.parse(msg.data)); - var source = new EventSource(_url); - source.addEventListener('data', emit); - source.onerror = emit; - } else { - console.warn('SDK Builder: EventSource is not supported'); - } - return subject.asObservable(); - } /** * Creates a new instance in replies of this model. * @@ -980,37 +577,6 @@ export class MessageApi extends BaseLoopBackApi { return result; } - /** - * Create a new instance of the model and persist it into the data source. - * - * @param object data Request data. - * - * This method expects a subset of model properties as request parameters. - * - * @returns object[] An empty reference that will be - * populated with the actual data once the response is returned - * from the server. - * - * - * (The remote method definition does not provide any description. - * This usually means the response is a `Message` object.) - * - */ - public createMany(data: Array = []): Observable> { - let _method: string = "POST"; - let _url: string = LoopBackConfig.getPath() + "/" + LoopBackConfig.getApiVersion() + - "/messages"; - let _routeParams: any = {}; - let _postBody: any = { - data: data - }; - let _urlParams: any = {}; - let result = this.request(_method, _url, _routeParams, _urlParams, _postBody); - return result.map((instances: Array) => - instances.map((instance: Message) => new Message(instance)) - ); - } - /** * The name of the model represented by this $resource, * i.e. `Message`. diff --git a/tests/angular2/src/app/shared/sdk/services/custom/Room.ts b/tests/angular2/src/app/shared/sdk/services/custom/Room.ts index 12511952..62cff8c0 100644 --- a/tests/angular2/src/app/shared/sdk/services/custom/Room.ts +++ b/tests/angular2/src/app/shared/sdk/services/custom/Room.ts @@ -1,9 +1,11 @@ /* tslint:disable */ import { Injectable, Inject, Optional } from '@angular/core'; import { Http, Response } from '@angular/http'; +import { SDKModels } from './SDKModels'; import { BaseLoopBackApi } from '../core/base.service'; import { LoopBackConfig } from '../../lb.config'; import { LoopBackAuth } from '../core/auth.service'; +import { SocketConnections } from '../../sockets/socket.connections'; import { LoopBackFilter, } from '../../models/BaseModels'; import { JSONSearchParams } from '../core/search.params'; import { ErrorHandler } from '../core/error.service'; @@ -16,8 +18,6 @@ import { Category } from '../../models/Category'; import { RoomAccount } from '../../models/RoomAccount'; import { Account } from '../../models/Account'; -// Making Sure EventSource Type is available to avoid compilation issues. -declare var EventSource: any; /** * Api services for the `Room` model. @@ -26,12 +26,14 @@ declare var EventSource: any; export class RoomApi extends BaseLoopBackApi { constructor( - @Inject(Http) http: Http, - @Inject(LoopBackAuth) protected auth: LoopBackAuth, - @Inject(JSONSearchParams) protected searchParams: JSONSearchParams, - @Optional() @Inject(ErrorHandler) errorHandler: ErrorHandler + @Inject(Http) protected http: Http, + @Inject(SocketConnections) protected connections: SocketConnections, + @Inject(SDKModels) protected models: SDKModels, + @Inject(LoopBackAuth) protected auth: LoopBackAuth, + @Inject(JSONSearchParams) protected searchParams: JSONSearchParams, + @Optional() @Inject(ErrorHandler) protected errorHandler: ErrorHandler ) { - super(http, auth, searchParams, errorHandler); + super(http, connections, models, auth, searchParams, errorHandler); } /** @@ -1723,277 +1725,9 @@ export class RoomApi extends BaseLoopBackApi { } /** - * Create a new instance of the model and persist it into the data source. + * Gets list of all unique values used for a given property. * - * @param object data Request data. - * - * This method expects a subset of model properties as request parameters. - * - * @returns object An empty reference that will be - * populated with the actual data once the response is returned - * from the server. - * - * - * (The remote method definition does not provide any description. - * This usually means the response is a `Room` object.) - * - */ - public create(data: any = {}): Observable { - let _method: string = "POST"; - let _url: string = LoopBackConfig.getPath() + "/" + LoopBackConfig.getApiVersion() + - "/rooms"; - let _routeParams: any = {}; - let _postBody: any = { - data: data - }; - let _urlParams: any = {}; - let result = this.request(_method, _url, _routeParams, _urlParams, _postBody); - return result.map((instance: Room) => new Room(instance)); - } - - public onCreate(): Observable { - let _method: string = "POST"; - let _url: string = "/" + LoopBackConfig.getApiVersion() + - "/rooms"; - let _routeParams: any = {}; - let _postBody: any = {}; - let _urlParams: any = {}; - let result = this.request(_method, _url, _routeParams, _urlParams, _postBody, true); - - return result.map((instance: Room) => new Room(instance)); - } - - /** - * Patch an existing model instance or insert a new one into the data source. - * - * @param object data Request data. - * - * This method expects a subset of model properties as request parameters. - * - * @returns object An empty reference that will be - * populated with the actual data once the response is returned - * from the server. - * - * - * (The remote method definition does not provide any description. - * This usually means the response is a `Room` object.) - * - */ - public upsert(data: any = {}): Observable { - let _method: string = "PUT"; - let _url: string = LoopBackConfig.getPath() + "/" + LoopBackConfig.getApiVersion() + - "/rooms"; - let _routeParams: any = {}; - let _postBody: any = { - data: data - }; - let _urlParams: any = {}; - let result = this.request(_method, _url, _routeParams, _urlParams, _postBody); - return result.map((instance: Room) => new Room(instance)); - } - - public onUpsert(): Observable { - let _method: string = "PUT"; - let _url: string = "/" + LoopBackConfig.getApiVersion() + - "/rooms"; - let _routeParams: any = {}; - let _postBody: any = {}; - let _urlParams: any = {}; - let result = this.request(_method, _url, _routeParams, _urlParams, _postBody, true); - - return result.map((instance: Room) => new Room(instance)); - } - - /** - * Replace an existing model instance or insert a new one into the data source. - * - * @param object data Request data. - * - * This method expects a subset of model properties as request parameters. - * - * @returns object An empty reference that will be - * populated with the actual data once the response is returned - * from the server. - * - * - * (The remote method definition does not provide any description. - * This usually means the response is a `Room` object.) - * - */ - public replaceOrCreate(data: any = {}): Observable { - let _method: string = "POST"; - let _url: string = LoopBackConfig.getPath() + "/" + LoopBackConfig.getApiVersion() + - "/rooms/replaceOrCreate"; - let _routeParams: any = {}; - let _postBody: any = { - data: data - }; - let _urlParams: any = {}; - let result = this.request(_method, _url, _routeParams, _urlParams, _postBody); - return result; - } - - public onReplaceOrCreate(): Observable { - let _method: string = "POST"; - let _url: string = "/" + LoopBackConfig.getApiVersion() + - "/rooms/replaceOrCreate"; - let _routeParams: any = {}; - let _postBody: any = {}; - let _urlParams: any = {}; - let result = this.request(_method, _url, _routeParams, _urlParams, _postBody, true); - ; - return result; - } - - /** - * Update an existing model instance or insert a new one into the data source based on the where criteria. - * - * @param object where Criteria to match model instances - * - * @param object data Request data. - * - * This method expects a subset of model properties as request parameters. - * - * @returns object An empty reference that will be - * populated with the actual data once the response is returned - * from the server. - * - * - * (The remote method definition does not provide any description. - * This usually means the response is a `Room` object.) - * - */ - public upsertWithWhere(where: any = {}, data: any = {}): Observable { - let _method: string = "POST"; - let _url: string = LoopBackConfig.getPath() + "/" + LoopBackConfig.getApiVersion() + - "/rooms/upsertWithWhere"; - let _routeParams: any = {}; - let _postBody: any = { - data: data - }; - let _urlParams: any = {}; - if (where) _urlParams.where = where; - let result = this.request(_method, _url, _routeParams, _urlParams, _postBody); - return result.map((instance: Room) => new Room(instance)); - } - - public onUpsertWithWhere(where: any = {}): Observable { - let _method: string = "POST"; - let _url: string = "/" + LoopBackConfig.getApiVersion() + - "/rooms/upsertWithWhere"; - let _routeParams: any = {}; - let _postBody: any = {}; - let _urlParams: any = {}; - let result = this.request(_method, _url, _routeParams, _urlParams, _postBody, true); - - return result.map((instance: Room) => new Room(instance)); - } - - /** - * Check whether a model instance exists in the data source. - * - * @param any id Model id - * - * @returns object An empty reference that will be - * populated with the actual data once the response is returned - * from the server. - * - * Data properties: - * - * - `exists` – `{boolean}` - - */ - public exists(id: any): Observable { - let _method: string = "GET"; - let _url: string = LoopBackConfig.getPath() + "/" + LoopBackConfig.getApiVersion() + - "/rooms/:id/exists"; - let _routeParams: any = { - id: id - }; - let _postBody: any = {}; - let _urlParams: any = {}; - let result = this.request(_method, _url, _routeParams, _urlParams, _postBody); - return result; - } - - /** - * Find a model instance by {{id}} from the data source. - * - * @param any id Model id - * - * @param object filter Filter defining fields and include - * - * @returns object An empty reference that will be - * populated with the actual data once the response is returned - * from the server. - * - * - * (The remote method definition does not provide any description. - * This usually means the response is a `Room` object.) - * - */ - public findById(id: any, filter: LoopBackFilter = {}): Observable { - let _method: string = "GET"; - let _url: string = LoopBackConfig.getPath() + "/" + LoopBackConfig.getApiVersion() + - "/rooms/:id"; - let _routeParams: any = { - id: id - }; - let _postBody: any = {}; - let _urlParams: any = {}; - if (filter) _urlParams.filter = filter; - let result = this.request(_method, _url, _routeParams, _urlParams, _postBody); - return result.map((instance: Room) => new Room(instance)); - } - - /** - * Replace attributes for a model instance and persist it into the data source. - * - * @param any id Model id - * - * @param object data Request data. - * - * This method expects a subset of model properties as request parameters. - * - * @returns object An empty reference that will be - * populated with the actual data once the response is returned - * from the server. - * - * - * (The remote method definition does not provide any description. - * This usually means the response is a `Room` object.) - * - */ - public replaceById(id: any, data: any = {}): Observable { - let _method: string = "POST"; - let _url: string = LoopBackConfig.getPath() + "/" + LoopBackConfig.getApiVersion() + - "/rooms/:id/replace"; - let _routeParams: any = { - id: id - }; - let _postBody: any = { - data: data - }; - let _urlParams: any = {}; - let result = this.request(_method, _url, _routeParams, _urlParams, _postBody); - return result; - } - - public onReplaceById(id: any): Observable { - let _method: string = "POST"; - let _url: string = "/" + LoopBackConfig.getApiVersion() + - "/rooms/:id/replace"; - let _routeParams: any = { - id: id - }; - let _postBody: any = {}; - let _urlParams: any = {}; - let result = this.request(_method, _url, _routeParams, _urlParams, _postBody, true); - ; - return result; - } - - /** - * Find all instances of the model matched by filter from the data source. + * @param string property Property name to lookup values for. * * @param object filter Filter defining fields, where, include, order, offset, and limit * @@ -2006,229 +1740,19 @@ export class RoomApi extends BaseLoopBackApi { * This usually means the response is a `Room` object.) * */ - public find(filter: LoopBackFilter = {}): Observable> { + public getPropertyValues(property: any, filter: LoopBackFilter = {}): Observable { let _method: string = "GET"; let _url: string = LoopBackConfig.getPath() + "/" + LoopBackConfig.getApiVersion() + - "/rooms"; + "/rooms/propertyValues"; let _routeParams: any = {}; let _postBody: any = {}; let _urlParams: any = {}; + if (property) _urlParams.property = property; if (filter) _urlParams.filter = filter; let result = this.request(_method, _url, _routeParams, _urlParams, _postBody); - return result.map((instances: Array) => - instances.map((instance: Room) => new Room(instance)) - ); - } - - /** - * Find first instance of the model matched by filter from the data source. - * - * @param object filter Filter defining fields, where, include, order, offset, and limit - * - * @returns object An empty reference that will be - * populated with the actual data once the response is returned - * from the server. - * - * - * (The remote method definition does not provide any description. - * This usually means the response is a `Room` object.) - * - */ - public findOne(filter: LoopBackFilter = {}): Observable { - let _method: string = "GET"; - let _url: string = LoopBackConfig.getPath() + "/" + LoopBackConfig.getApiVersion() + - "/rooms/findOne"; - let _routeParams: any = {}; - let _postBody: any = {}; - let _urlParams: any = {}; - if (filter) _urlParams.filter = filter; - let result = this.request(_method, _url, _routeParams, _urlParams, _postBody); - return result.map((instance: Room) => new Room(instance)); - } - - /** - * Update instances of the model matched by {{where}} from the data source. - * - * @param object where Criteria to match model instances - * - * @param object data Request data. - * - * This method expects a subset of model properties as request parameters. - * - * @returns object An empty reference that will be - * populated with the actual data once the response is returned - * from the server. - * - * The number of instances updated - */ - public updateAll(where: any = {}, data: any = {}): Observable { - let _method: string = "POST"; - let _url: string = LoopBackConfig.getPath() + "/" + LoopBackConfig.getApiVersion() + - "/rooms/update"; - let _routeParams: any = {}; - let _postBody: any = { - data: data - }; - let _urlParams: any = {}; - if (where) _urlParams.where = where; - let result = this.request(_method, _url, _routeParams, _urlParams, _postBody); - return result; - } - - public onUpdateAll(where: any = {}): Observable { - let _method: string = "POST"; - let _url: string = "/" + LoopBackConfig.getApiVersion() + - "/rooms/update"; - let _routeParams: any = {}; - let _postBody: any = {}; - let _urlParams: any = {}; - let result = this.request(_method, _url, _routeParams, _urlParams, _postBody, true); - ; - return result; - } - - /** - * Delete a model instance by {{id}} from the data source. - * - * @param any id Model id - * - * @returns object An empty reference that will be - * populated with the actual data once the response is returned - * from the server. - * - * - * (The remote method definition does not provide any description. - * This usually means the response is a `Room` object.) - * - */ - public deleteById(id: any): Observable { - let _method: string = "DELETE"; - let _url: string = LoopBackConfig.getPath() + "/" + LoopBackConfig.getApiVersion() + - "/rooms/:id"; - let _routeParams: any = { - id: id - }; - let _postBody: any = {}; - let _urlParams: any = {}; - let result = this.request(_method, _url, _routeParams, _urlParams, _postBody); - return result; - } - - public onDeleteById(id: any): Observable { - let _method: string = "DELETE"; - let _url: string = "/" + LoopBackConfig.getApiVersion() + - "/rooms/:id"; - let _routeParams: any = { - id: id - }; - let _postBody: any = {}; - let _urlParams: any = {}; - let result = this.request(_method, _url, _routeParams, _urlParams, _postBody, true); - ; - return result; - } - - /** - * Count instances of the model matched by where from the data source. - * - * @param object where Criteria to match model instances - * - * @returns object An empty reference that will be - * populated with the actual data once the response is returned - * from the server. - * - * Data properties: - * - * - `count` – `{number}` - - */ - public count(where: any = {}): Observable { - let _method: string = "GET"; - let _url: string = LoopBackConfig.getPath() + "/" + LoopBackConfig.getApiVersion() + - "/rooms/count"; - let _routeParams: any = {}; - let _postBody: any = {}; - let _urlParams: any = {}; - if (where) _urlParams.where = where; - let result = this.request(_method, _url, _routeParams, _urlParams, _postBody); return result; } - /** - * Patch attributes for a model instance and persist it into the data source. - * - * @param any id PersistedModel id - * - * @param object data Request data. - * - * This method expects a subset of model properties as request parameters. - * - * @returns object An empty reference that will be - * populated with the actual data once the response is returned - * from the server. - * - * - * (The remote method definition does not provide any description. - * This usually means the response is a `Room` object.) - * - */ - public updateAttributes(id: any, data: any = {}): Observable { - let _method: string = "PUT"; - let _url: string = LoopBackConfig.getPath() + "/" + LoopBackConfig.getApiVersion() + - "/rooms/:id"; - let _routeParams: any = { - id: id - }; - let _postBody: any = { - data: data - }; - let _urlParams: any = {}; - let result = this.request(_method, _url, _routeParams, _urlParams, _postBody); - return result; - } - - public onUpdateAttributes(id: any): Observable { - let _method: string = "PUT"; - let _url: string = "/" + LoopBackConfig.getApiVersion() + - "/rooms/:id"; - let _routeParams: any = { - id: id - }; - let _postBody: any = {}; - let _urlParams: any = {}; - let result = this.request(_method, _url, _routeParams, _urlParams, _postBody, true); - ; - return result; - } - - /** - * Create a change stream. - * - * @param object data Request data. - * - * - `options` – `{object}` - - * - * @returns object An empty reference that will be - * populated with the actual data once the response is returned - * from the server. - * - * Data properties: - * - * - `changes` – `{ReadableStream}` - - */ - public createChangeStream(): Observable { - let _url: string = LoopBackConfig.getPath() + "/" + LoopBackConfig.getApiVersion() + - "/rooms/change-stream"; - let subject = new Subject(); - if (typeof EventSource !== 'undefined') { - let emit = (msg: any) => subject.next(JSON.parse(msg.data)); - var source = new EventSource(_url); - source.addEventListener('data', emit); - source.onerror = emit; - } else { - console.warn('SDK Builder: EventSource is not supported'); - } - return subject.asObservable(); - } /** * * (The remote method definition does not provide any description.) @@ -2708,51 +2232,6 @@ export class RoomApi extends BaseLoopBackApi { return result; } - /** - * Create a new instance of the model and persist it into the data source. - * - * @param object data Request data. - * - * This method expects a subset of model properties as request parameters. - * - * @returns object[] An empty reference that will be - * populated with the actual data once the response is returned - * from the server. - * - * - * (The remote method definition does not provide any description. - * This usually means the response is a `Room` object.) - * - */ - public createMany(data: Array = []): Observable> { - let _method: string = "POST"; - let _url: string = LoopBackConfig.getPath() + "/" + LoopBackConfig.getApiVersion() + - "/rooms"; - let _routeParams: any = {}; - let _postBody: any = { - data: data - }; - let _urlParams: any = {}; - let result = this.request(_method, _url, _routeParams, _urlParams, _postBody); - return result.map((instances: Array) => - instances.map((instance: Room) => new Room(instance)) - ); - } - - public onCreateMany(): Observable> { - let _method: string = "POST"; - let _url: string = "/" + LoopBackConfig.getApiVersion() + - "/rooms"; - let _routeParams: any = {}; - let _postBody: any = {}; - let _urlParams: any = {}; - let result = this.request(_method, _url, _routeParams, _urlParams, _postBody, true); - ; - return result.map((instances: Array) => - instances.map((instance: Room) => new Room(instance)) - ); - } - /** * The name of the model represented by this $resource, * i.e. `Room`. diff --git a/tests/angular2/src/app/shared/sdk/services/custom/RoomAccount.ts b/tests/angular2/src/app/shared/sdk/services/custom/RoomAccount.ts index 1fc0ab9c..b84b15c0 100644 --- a/tests/angular2/src/app/shared/sdk/services/custom/RoomAccount.ts +++ b/tests/angular2/src/app/shared/sdk/services/custom/RoomAccount.ts @@ -1,9 +1,11 @@ /* tslint:disable */ import { Injectable, Inject, Optional } from '@angular/core'; import { Http, Response } from '@angular/http'; +import { SDKModels } from './SDKModels'; import { BaseLoopBackApi } from '../core/base.service'; import { LoopBackConfig } from '../../lb.config'; import { LoopBackAuth } from '../core/auth.service'; +import { SocketConnections } from '../../sockets/socket.connections'; import { LoopBackFilter, } from '../../models/BaseModels'; import { JSONSearchParams } from '../core/search.params'; import { ErrorHandler } from '../core/error.service'; @@ -14,8 +16,6 @@ import { RoomAccount } from '../../models/RoomAccount'; import { Account } from '../../models/Account'; import { Room } from '../../models/Room'; -// Making Sure EventSource Type is available to avoid compilation issues. -declare var EventSource: any; /** * Api services for the `RoomAccount` model. @@ -24,12 +24,14 @@ declare var EventSource: any; export class RoomAccountApi extends BaseLoopBackApi { constructor( - @Inject(Http) http: Http, - @Inject(LoopBackAuth) protected auth: LoopBackAuth, - @Inject(JSONSearchParams) protected searchParams: JSONSearchParams, - @Optional() @Inject(ErrorHandler) errorHandler: ErrorHandler + @Inject(Http) protected http: Http, + @Inject(SocketConnections) protected connections: SocketConnections, + @Inject(SDKModels) protected models: SDKModels, + @Inject(LoopBackAuth) protected auth: LoopBackAuth, + @Inject(JSONSearchParams) protected searchParams: JSONSearchParams, + @Optional() @Inject(ErrorHandler) protected errorHandler: ErrorHandler ) { - super(http, auth, searchParams, errorHandler); + super(http, connections, models, auth, searchParams, errorHandler); } /** @@ -92,442 +94,6 @@ export class RoomAccountApi extends BaseLoopBackApi { return result; } - /** - * Create a new instance of the model and persist it into the data source. - * - * @param object data Request data. - * - * This method expects a subset of model properties as request parameters. - * - * @returns object An empty reference that will be - * populated with the actual data once the response is returned - * from the server. - * - * - * (The remote method definition does not provide any description. - * This usually means the response is a `RoomAccount` object.) - * - */ - public create(data: any = {}): Observable { - let _method: string = "POST"; - let _url: string = LoopBackConfig.getPath() + "/" + LoopBackConfig.getApiVersion() + - "/room-accounts"; - let _routeParams: any = {}; - let _postBody: any = { - data: data - }; - let _urlParams: any = {}; - let result = this.request(_method, _url, _routeParams, _urlParams, _postBody); - return result.map((instance: RoomAccount) => new RoomAccount(instance)); - } - - /** - * Patch an existing model instance or insert a new one into the data source. - * - * @param object data Request data. - * - * This method expects a subset of model properties as request parameters. - * - * @returns object An empty reference that will be - * populated with the actual data once the response is returned - * from the server. - * - * - * (The remote method definition does not provide any description. - * This usually means the response is a `RoomAccount` object.) - * - */ - public upsert(data: any = {}): Observable { - let _method: string = "PUT"; - let _url: string = LoopBackConfig.getPath() + "/" + LoopBackConfig.getApiVersion() + - "/room-accounts"; - let _routeParams: any = {}; - let _postBody: any = { - data: data - }; - let _urlParams: any = {}; - let result = this.request(_method, _url, _routeParams, _urlParams, _postBody); - return result.map((instance: RoomAccount) => new RoomAccount(instance)); - } - - /** - * Replace an existing model instance or insert a new one into the data source. - * - * @param object data Request data. - * - * This method expects a subset of model properties as request parameters. - * - * @returns object An empty reference that will be - * populated with the actual data once the response is returned - * from the server. - * - * - * (The remote method definition does not provide any description. - * This usually means the response is a `RoomAccount` object.) - * - */ - public replaceOrCreate(data: any = {}): Observable { - let _method: string = "POST"; - let _url: string = LoopBackConfig.getPath() + "/" + LoopBackConfig.getApiVersion() + - "/room-accounts/replaceOrCreate"; - let _routeParams: any = {}; - let _postBody: any = { - data: data - }; - let _urlParams: any = {}; - let result = this.request(_method, _url, _routeParams, _urlParams, _postBody); - return result; - } - - /** - * Update an existing model instance or insert a new one into the data source based on the where criteria. - * - * @param object where Criteria to match model instances - * - * @param object data Request data. - * - * This method expects a subset of model properties as request parameters. - * - * @returns object An empty reference that will be - * populated with the actual data once the response is returned - * from the server. - * - * - * (The remote method definition does not provide any description. - * This usually means the response is a `RoomAccount` object.) - * - */ - public upsertWithWhere(where: any = {}, data: any = {}): Observable { - let _method: string = "POST"; - let _url: string = LoopBackConfig.getPath() + "/" + LoopBackConfig.getApiVersion() + - "/room-accounts/upsertWithWhere"; - let _routeParams: any = {}; - let _postBody: any = { - data: data - }; - let _urlParams: any = {}; - if (where) _urlParams.where = where; - let result = this.request(_method, _url, _routeParams, _urlParams, _postBody); - return result.map((instance: RoomAccount) => new RoomAccount(instance)); - } - - /** - * Check whether a model instance exists in the data source. - * - * @param any id Model id - * - * @returns object An empty reference that will be - * populated with the actual data once the response is returned - * from the server. - * - * Data properties: - * - * - `exists` – `{boolean}` - - */ - public exists(id: any): Observable { - let _method: string = "GET"; - let _url: string = LoopBackConfig.getPath() + "/" + LoopBackConfig.getApiVersion() + - "/room-accounts/:id/exists"; - let _routeParams: any = { - id: id - }; - let _postBody: any = {}; - let _urlParams: any = {}; - let result = this.request(_method, _url, _routeParams, _urlParams, _postBody); - return result; - } - - /** - * Find a model instance by {{id}} from the data source. - * - * @param any id Model id - * - * @param object filter Filter defining fields and include - * - * @returns object An empty reference that will be - * populated with the actual data once the response is returned - * from the server. - * - * - * (The remote method definition does not provide any description. - * This usually means the response is a `RoomAccount` object.) - * - */ - public findById(id: any, filter: LoopBackFilter = {}): Observable { - let _method: string = "GET"; - let _url: string = LoopBackConfig.getPath() + "/" + LoopBackConfig.getApiVersion() + - "/room-accounts/:id"; - let _routeParams: any = { - id: id - }; - let _postBody: any = {}; - let _urlParams: any = {}; - if (filter) _urlParams.filter = filter; - let result = this.request(_method, _url, _routeParams, _urlParams, _postBody); - return result.map((instance: RoomAccount) => new RoomAccount(instance)); - } - - /** - * Replace attributes for a model instance and persist it into the data source. - * - * @param any id Model id - * - * @param object data Request data. - * - * This method expects a subset of model properties as request parameters. - * - * @returns object An empty reference that will be - * populated with the actual data once the response is returned - * from the server. - * - * - * (The remote method definition does not provide any description. - * This usually means the response is a `RoomAccount` object.) - * - */ - public replaceById(id: any, data: any = {}): Observable { - let _method: string = "POST"; - let _url: string = LoopBackConfig.getPath() + "/" + LoopBackConfig.getApiVersion() + - "/room-accounts/:id/replace"; - let _routeParams: any = { - id: id - }; - let _postBody: any = { - data: data - }; - let _urlParams: any = {}; - let result = this.request(_method, _url, _routeParams, _urlParams, _postBody); - return result; - } - - /** - * Find all instances of the model matched by filter from the data source. - * - * @param object filter Filter defining fields, where, include, order, offset, and limit - * - * @returns object[] An empty reference that will be - * populated with the actual data once the response is returned - * from the server. - * - * - * (The remote method definition does not provide any description. - * This usually means the response is a `RoomAccount` object.) - * - */ - public find(filter: LoopBackFilter = {}): Observable> { - let _method: string = "GET"; - let _url: string = LoopBackConfig.getPath() + "/" + LoopBackConfig.getApiVersion() + - "/room-accounts"; - let _routeParams: any = {}; - let _postBody: any = {}; - let _urlParams: any = {}; - if (filter) _urlParams.filter = filter; - let result = this.request(_method, _url, _routeParams, _urlParams, _postBody); - return result.map((instances: Array) => - instances.map((instance: RoomAccount) => new RoomAccount(instance)) - ); - } - - /** - * Find first instance of the model matched by filter from the data source. - * - * @param object filter Filter defining fields, where, include, order, offset, and limit - * - * @returns object An empty reference that will be - * populated with the actual data once the response is returned - * from the server. - * - * - * (The remote method definition does not provide any description. - * This usually means the response is a `RoomAccount` object.) - * - */ - public findOne(filter: LoopBackFilter = {}): Observable { - let _method: string = "GET"; - let _url: string = LoopBackConfig.getPath() + "/" + LoopBackConfig.getApiVersion() + - "/room-accounts/findOne"; - let _routeParams: any = {}; - let _postBody: any = {}; - let _urlParams: any = {}; - if (filter) _urlParams.filter = filter; - let result = this.request(_method, _url, _routeParams, _urlParams, _postBody); - return result.map((instance: RoomAccount) => new RoomAccount(instance)); - } - - /** - * Update instances of the model matched by {{where}} from the data source. - * - * @param object where Criteria to match model instances - * - * @param object data Request data. - * - * This method expects a subset of model properties as request parameters. - * - * @returns object An empty reference that will be - * populated with the actual data once the response is returned - * from the server. - * - * The number of instances updated - */ - public updateAll(where: any = {}, data: any = {}): Observable { - let _method: string = "POST"; - let _url: string = LoopBackConfig.getPath() + "/" + LoopBackConfig.getApiVersion() + - "/room-accounts/update"; - let _routeParams: any = {}; - let _postBody: any = { - data: data - }; - let _urlParams: any = {}; - if (where) _urlParams.where = where; - let result = this.request(_method, _url, _routeParams, _urlParams, _postBody); - return result; - } - - /** - * Delete a model instance by {{id}} from the data source. - * - * @param any id Model id - * - * @returns object An empty reference that will be - * populated with the actual data once the response is returned - * from the server. - * - * - * (The remote method definition does not provide any description. - * This usually means the response is a `RoomAccount` object.) - * - */ - public deleteById(id: any): Observable { - let _method: string = "DELETE"; - let _url: string = LoopBackConfig.getPath() + "/" + LoopBackConfig.getApiVersion() + - "/room-accounts/:id"; - let _routeParams: any = { - id: id - }; - let _postBody: any = {}; - let _urlParams: any = {}; - let result = this.request(_method, _url, _routeParams, _urlParams, _postBody); - return result; - } - - /** - * Count instances of the model matched by where from the data source. - * - * @param object where Criteria to match model instances - * - * @returns object An empty reference that will be - * populated with the actual data once the response is returned - * from the server. - * - * Data properties: - * - * - `count` – `{number}` - - */ - public count(where: any = {}): Observable { - let _method: string = "GET"; - let _url: string = LoopBackConfig.getPath() + "/" + LoopBackConfig.getApiVersion() + - "/room-accounts/count"; - let _routeParams: any = {}; - let _postBody: any = {}; - let _urlParams: any = {}; - if (where) _urlParams.where = where; - let result = this.request(_method, _url, _routeParams, _urlParams, _postBody); - return result; - } - - /** - * Patch attributes for a model instance and persist it into the data source. - * - * @param any id PersistedModel id - * - * @param object data Request data. - * - * This method expects a subset of model properties as request parameters. - * - * @returns object An empty reference that will be - * populated with the actual data once the response is returned - * from the server. - * - * - * (The remote method definition does not provide any description. - * This usually means the response is a `RoomAccount` object.) - * - */ - public updateAttributes(id: any, data: any = {}): Observable { - let _method: string = "PUT"; - let _url: string = LoopBackConfig.getPath() + "/" + LoopBackConfig.getApiVersion() + - "/room-accounts/:id"; - let _routeParams: any = { - id: id - }; - let _postBody: any = { - data: data - }; - let _urlParams: any = {}; - let result = this.request(_method, _url, _routeParams, _urlParams, _postBody); - return result; - } - - /** - * Create a change stream. - * - * @param object data Request data. - * - * - `options` – `{object}` - - * - * @returns object An empty reference that will be - * populated with the actual data once the response is returned - * from the server. - * - * Data properties: - * - * - `changes` – `{ReadableStream}` - - */ - public createChangeStream(): Observable { - let _url: string = LoopBackConfig.getPath() + "/" + LoopBackConfig.getApiVersion() + - "/room-accounts/change-stream"; - let subject = new Subject(); - if (typeof EventSource !== 'undefined') { - let emit = (msg: any) => subject.next(JSON.parse(msg.data)); - var source = new EventSource(_url); - source.addEventListener('data', emit); - source.onerror = emit; - } else { - console.warn('SDK Builder: EventSource is not supported'); - } - return subject.asObservable(); - } - /** - * Create a new instance of the model and persist it into the data source. - * - * @param object data Request data. - * - * This method expects a subset of model properties as request parameters. - * - * @returns object[] An empty reference that will be - * populated with the actual data once the response is returned - * from the server. - * - * - * (The remote method definition does not provide any description. - * This usually means the response is a `RoomAccount` object.) - * - */ - public createMany(data: Array = []): Observable> { - let _method: string = "POST"; - let _url: string = LoopBackConfig.getPath() + "/" + LoopBackConfig.getApiVersion() + - "/room-accounts"; - let _routeParams: any = {}; - let _postBody: any = { - data: data - }; - let _urlParams: any = {}; - let result = this.request(_method, _url, _routeParams, _urlParams, _postBody); - return result.map((instances: Array) => - instances.map((instance: RoomAccount) => new RoomAccount(instance)) - ); - } - /** * The name of the model represented by this $resource, * i.e. `RoomAccount`. diff --git a/tests/angular2/src/app/shared/sdk/services/custom/SDKModels.ts b/tests/angular2/src/app/shared/sdk/services/custom/SDKModels.ts new file mode 100644 index 00000000..c0fb228b --- /dev/null +++ b/tests/angular2/src/app/shared/sdk/services/custom/SDKModels.ts @@ -0,0 +1,36 @@ +/* tslint:disable */ +import { Injectable } from '@angular/core'; +import { User } from '../../models/User'; +import { Room } from '../../models/Room'; +import { Message } from '../../models/Message'; +import { ApplicationCredential } from '../../models/ApplicationCredential'; +import { UserCredential } from '../../models/UserCredential'; +import { UserIdentity } from '../../models/UserIdentity'; +import { Category } from '../../models/Category'; +import { Account } from '../../models/Account'; +import { RoomAccount } from '../../models/RoomAccount'; +import { Storage } from '../../models/Storage'; +import { Core } from '../../models/Core'; + +@Injectable() +export class SDKModels { + + private models: { [name: string]: any } = { + User: User, + Room: Room, + Message: Message, + ApplicationCredential: ApplicationCredential, + UserCredential: UserCredential, + UserIdentity: UserIdentity, + Category: Category, + Account: Account, + RoomAccount: RoomAccount, + Storage: Storage, + Core: Core, + + }; + + public get(modelName: string): any { + return this.models[modelName]; + } +} diff --git a/tests/angular2/src/app/shared/sdk/services/custom/Storage.ts b/tests/angular2/src/app/shared/sdk/services/custom/Storage.ts index 38a97d57..4b04d307 100644 --- a/tests/angular2/src/app/shared/sdk/services/custom/Storage.ts +++ b/tests/angular2/src/app/shared/sdk/services/custom/Storage.ts @@ -1,9 +1,11 @@ /* tslint:disable */ import { Injectable, Inject, Optional } from '@angular/core'; import { Http, Response } from '@angular/http'; +import { SDKModels } from './SDKModels'; import { BaseLoopBackApi } from '../core/base.service'; import { LoopBackConfig } from '../../lb.config'; import { LoopBackAuth } from '../core/auth.service'; +import { SocketConnections } from '../../sockets/socket.connections'; import { LoopBackFilter, } from '../../models/BaseModels'; import { JSONSearchParams } from '../core/search.params'; import { ErrorHandler } from '../core/error.service'; @@ -12,8 +14,6 @@ import { Observable } from 'rxjs/Observable'; import 'rxjs/add/operator/map'; import { Storage } from '../../models/Storage'; -// Making Sure EventSource Type is available to avoid compilation issues. -declare var EventSource: any; /** * Api services for the `Storage` model. @@ -22,12 +22,14 @@ declare var EventSource: any; export class StorageApi extends BaseLoopBackApi { constructor( - @Inject(Http) http: Http, - @Inject(LoopBackAuth) protected auth: LoopBackAuth, - @Inject(JSONSearchParams) protected searchParams: JSONSearchParams, - @Optional() @Inject(ErrorHandler) errorHandler: ErrorHandler + @Inject(Http) protected http: Http, + @Inject(SocketConnections) protected connections: SocketConnections, + @Inject(SDKModels) protected models: SDKModels, + @Inject(LoopBackAuth) protected auth: LoopBackAuth, + @Inject(JSONSearchParams) protected searchParams: JSONSearchParams, + @Optional() @Inject(ErrorHandler) protected errorHandler: ErrorHandler ) { - super(http, auth, searchParams, errorHandler); + super(http, connections, models, auth, searchParams, errorHandler); } /** diff --git a/tests/angular2/src/app/shared/sdk/services/custom/User.ts b/tests/angular2/src/app/shared/sdk/services/custom/User.ts index dd0de1e5..5ed66eae 100644 --- a/tests/angular2/src/app/shared/sdk/services/custom/User.ts +++ b/tests/angular2/src/app/shared/sdk/services/custom/User.ts @@ -1,9 +1,11 @@ /* tslint:disable */ import { Injectable, Inject, Optional } from '@angular/core'; import { Http, Response } from '@angular/http'; +import { SDKModels } from './SDKModels'; import { BaseLoopBackApi } from '../core/base.service'; import { LoopBackConfig } from '../../lb.config'; import { LoopBackAuth } from '../core/auth.service'; +import { SocketConnections } from '../../sockets/socket.connections'; import { LoopBackFilter, SDKToken, AccessToken } from '../../models/BaseModels'; import { JSONSearchParams } from '../core/search.params'; import { ErrorHandler } from '../core/error.service'; @@ -12,8 +14,6 @@ import { Observable } from 'rxjs/Observable'; import 'rxjs/add/operator/map'; import { User } from '../../models/User'; -// Making Sure EventSource Type is available to avoid compilation issues. -declare var EventSource: any; /** * Api services for the `User` model. @@ -22,12 +22,14 @@ declare var EventSource: any; export class UserApi extends BaseLoopBackApi { constructor( - @Inject(Http) http: Http, - @Inject(LoopBackAuth) protected auth: LoopBackAuth, - @Inject(JSONSearchParams) protected searchParams: JSONSearchParams, - @Optional() @Inject(ErrorHandler) errorHandler: ErrorHandler + @Inject(Http) protected http: Http, + @Inject(SocketConnections) protected connections: SocketConnections, + @Inject(SDKModels) protected models: SDKModels, + @Inject(LoopBackAuth) protected auth: LoopBackAuth, + @Inject(JSONSearchParams) protected searchParams: JSONSearchParams, + @Optional() @Inject(ErrorHandler) protected errorHandler: ErrorHandler ) { - super(http, auth, searchParams, errorHandler); + super(http, connections, models, auth, searchParams, errorHandler); } /** @@ -239,411 +241,6 @@ export class UserApi extends BaseLoopBackApi { return result; } - /** - * Create a new instance of the model and persist it into the data source. - * - * @param object data Request data. - * - * This method expects a subset of model properties as request parameters. - * - * @returns object An empty reference that will be - * populated with the actual data once the response is returned - * from the server. - * - * - * (The remote method definition does not provide any description. - * This usually means the response is a `User` object.) - * - */ - public create(data: any = {}): Observable { - let _method: string = "POST"; - let _url: string = LoopBackConfig.getPath() + "/" + LoopBackConfig.getApiVersion() + - "/Users"; - let _routeParams: any = {}; - let _postBody: any = { - data: data - }; - let _urlParams: any = {}; - let result = this.request(_method, _url, _routeParams, _urlParams, _postBody); - return result.map((instance: User) => new User(instance)); - } - - /** - * Patch an existing model instance or insert a new one into the data source. - * - * @param object data Request data. - * - * This method expects a subset of model properties as request parameters. - * - * @returns object An empty reference that will be - * populated with the actual data once the response is returned - * from the server. - * - * - * (The remote method definition does not provide any description. - * This usually means the response is a `User` object.) - * - */ - public upsert(data: any = {}): Observable { - let _method: string = "PUT"; - let _url: string = LoopBackConfig.getPath() + "/" + LoopBackConfig.getApiVersion() + - "/Users"; - let _routeParams: any = {}; - let _postBody: any = { - data: data - }; - let _urlParams: any = {}; - let result = this.request(_method, _url, _routeParams, _urlParams, _postBody); - return result.map((instance: User) => new User(instance)); - } - - /** - * Replace an existing model instance or insert a new one into the data source. - * - * @param object data Request data. - * - * This method expects a subset of model properties as request parameters. - * - * @returns object An empty reference that will be - * populated with the actual data once the response is returned - * from the server. - * - * - * (The remote method definition does not provide any description. - * This usually means the response is a `User` object.) - * - */ - public replaceOrCreate(data: any = {}): Observable { - let _method: string = "POST"; - let _url: string = LoopBackConfig.getPath() + "/" + LoopBackConfig.getApiVersion() + - "/Users/replaceOrCreate"; - let _routeParams: any = {}; - let _postBody: any = { - data: data - }; - let _urlParams: any = {}; - let result = this.request(_method, _url, _routeParams, _urlParams, _postBody); - return result; - } - - /** - * Update an existing model instance or insert a new one into the data source based on the where criteria. - * - * @param object where Criteria to match model instances - * - * @param object data Request data. - * - * This method expects a subset of model properties as request parameters. - * - * @returns object An empty reference that will be - * populated with the actual data once the response is returned - * from the server. - * - * - * (The remote method definition does not provide any description. - * This usually means the response is a `User` object.) - * - */ - public upsertWithWhere(where: any = {}, data: any = {}): Observable { - let _method: string = "POST"; - let _url: string = LoopBackConfig.getPath() + "/" + LoopBackConfig.getApiVersion() + - "/Users/upsertWithWhere"; - let _routeParams: any = {}; - let _postBody: any = { - data: data - }; - let _urlParams: any = {}; - if (where) _urlParams.where = where; - let result = this.request(_method, _url, _routeParams, _urlParams, _postBody); - return result.map((instance: User) => new User(instance)); - } - - /** - * Check whether a model instance exists in the data source. - * - * @param any id Model id - * - * @returns object An empty reference that will be - * populated with the actual data once the response is returned - * from the server. - * - * Data properties: - * - * - `exists` – `{boolean}` - - */ - public exists(id: any): Observable { - let _method: string = "GET"; - let _url: string = LoopBackConfig.getPath() + "/" + LoopBackConfig.getApiVersion() + - "/Users/:id/exists"; - let _routeParams: any = { - id: id - }; - let _postBody: any = {}; - let _urlParams: any = {}; - let result = this.request(_method, _url, _routeParams, _urlParams, _postBody); - return result; - } - - /** - * Find a model instance by {{id}} from the data source. - * - * @param any id Model id - * - * @param object filter Filter defining fields and include - * - * @returns object An empty reference that will be - * populated with the actual data once the response is returned - * from the server. - * - * - * (The remote method definition does not provide any description. - * This usually means the response is a `User` object.) - * - */ - public findById(id: any, filter: LoopBackFilter = {}): Observable { - let _method: string = "GET"; - let _url: string = LoopBackConfig.getPath() + "/" + LoopBackConfig.getApiVersion() + - "/Users/:id"; - let _routeParams: any = { - id: id - }; - let _postBody: any = {}; - let _urlParams: any = {}; - if (filter) _urlParams.filter = filter; - let result = this.request(_method, _url, _routeParams, _urlParams, _postBody); - return result.map((instance: User) => new User(instance)); - } - - /** - * Replace attributes for a model instance and persist it into the data source. - * - * @param any id Model id - * - * @param object data Request data. - * - * This method expects a subset of model properties as request parameters. - * - * @returns object An empty reference that will be - * populated with the actual data once the response is returned - * from the server. - * - * - * (The remote method definition does not provide any description. - * This usually means the response is a `User` object.) - * - */ - public replaceById(id: any, data: any = {}): Observable { - let _method: string = "POST"; - let _url: string = LoopBackConfig.getPath() + "/" + LoopBackConfig.getApiVersion() + - "/Users/:id/replace"; - let _routeParams: any = { - id: id - }; - let _postBody: any = { - data: data - }; - let _urlParams: any = {}; - let result = this.request(_method, _url, _routeParams, _urlParams, _postBody); - return result; - } - - /** - * Find all instances of the model matched by filter from the data source. - * - * @param object filter Filter defining fields, where, include, order, offset, and limit - * - * @returns object[] An empty reference that will be - * populated with the actual data once the response is returned - * from the server. - * - * - * (The remote method definition does not provide any description. - * This usually means the response is a `User` object.) - * - */ - public find(filter: LoopBackFilter = {}): Observable> { - let _method: string = "GET"; - let _url: string = LoopBackConfig.getPath() + "/" + LoopBackConfig.getApiVersion() + - "/Users"; - let _routeParams: any = {}; - let _postBody: any = {}; - let _urlParams: any = {}; - if (filter) _urlParams.filter = filter; - let result = this.request(_method, _url, _routeParams, _urlParams, _postBody); - return result.map((instances: Array) => - instances.map((instance: User) => new User(instance)) - ); - } - - /** - * Find first instance of the model matched by filter from the data source. - * - * @param object filter Filter defining fields, where, include, order, offset, and limit - * - * @returns object An empty reference that will be - * populated with the actual data once the response is returned - * from the server. - * - * - * (The remote method definition does not provide any description. - * This usually means the response is a `User` object.) - * - */ - public findOne(filter: LoopBackFilter = {}): Observable { - let _method: string = "GET"; - let _url: string = LoopBackConfig.getPath() + "/" + LoopBackConfig.getApiVersion() + - "/Users/findOne"; - let _routeParams: any = {}; - let _postBody: any = {}; - let _urlParams: any = {}; - if (filter) _urlParams.filter = filter; - let result = this.request(_method, _url, _routeParams, _urlParams, _postBody); - return result.map((instance: User) => new User(instance)); - } - - /** - * Update instances of the model matched by {{where}} from the data source. - * - * @param object where Criteria to match model instances - * - * @param object data Request data. - * - * This method expects a subset of model properties as request parameters. - * - * @returns object An empty reference that will be - * populated with the actual data once the response is returned - * from the server. - * - * The number of instances updated - */ - public updateAll(where: any = {}, data: any = {}): Observable { - let _method: string = "POST"; - let _url: string = LoopBackConfig.getPath() + "/" + LoopBackConfig.getApiVersion() + - "/Users/update"; - let _routeParams: any = {}; - let _postBody: any = { - data: data - }; - let _urlParams: any = {}; - if (where) _urlParams.where = where; - let result = this.request(_method, _url, _routeParams, _urlParams, _postBody); - return result; - } - - /** - * Delete a model instance by {{id}} from the data source. - * - * @param any id Model id - * - * @returns object An empty reference that will be - * populated with the actual data once the response is returned - * from the server. - * - * - * (The remote method definition does not provide any description. - * This usually means the response is a `User` object.) - * - */ - public deleteById(id: any): Observable { - let _method: string = "DELETE"; - let _url: string = LoopBackConfig.getPath() + "/" + LoopBackConfig.getApiVersion() + - "/Users/:id"; - let _routeParams: any = { - id: id - }; - let _postBody: any = {}; - let _urlParams: any = {}; - let result = this.request(_method, _url, _routeParams, _urlParams, _postBody); - return result; - } - - /** - * Count instances of the model matched by where from the data source. - * - * @param object where Criteria to match model instances - * - * @returns object An empty reference that will be - * populated with the actual data once the response is returned - * from the server. - * - * Data properties: - * - * - `count` – `{number}` - - */ - public count(where: any = {}): Observable { - let _method: string = "GET"; - let _url: string = LoopBackConfig.getPath() + "/" + LoopBackConfig.getApiVersion() + - "/Users/count"; - let _routeParams: any = {}; - let _postBody: any = {}; - let _urlParams: any = {}; - if (where) _urlParams.where = where; - let result = this.request(_method, _url, _routeParams, _urlParams, _postBody); - return result; - } - - /** - * Patch attributes for a model instance and persist it into the data source. - * - * @param any id User id - * - * @param object data Request data. - * - * This method expects a subset of model properties as request parameters. - * - * @returns object An empty reference that will be - * populated with the actual data once the response is returned - * from the server. - * - * - * (The remote method definition does not provide any description. - * This usually means the response is a `User` object.) - * - */ - public updateAttributes(id: any, data: any = {}): Observable { - let _method: string = "PUT"; - let _url: string = LoopBackConfig.getPath() + "/" + LoopBackConfig.getApiVersion() + - "/Users/:id"; - let _routeParams: any = { - id: id - }; - let _postBody: any = { - data: data - }; - let _urlParams: any = {}; - let result = this.request(_method, _url, _routeParams, _urlParams, _postBody); - return result; - } - - /** - * Create a change stream. - * - * @param object data Request data. - * - * - `options` – `{object}` - - * - * @returns object An empty reference that will be - * populated with the actual data once the response is returned - * from the server. - * - * Data properties: - * - * - `changes` – `{ReadableStream}` - - */ - public createChangeStream(): Observable { - let _url: string = LoopBackConfig.getPath() + "/" + LoopBackConfig.getApiVersion() + - "/Users/change-stream"; - let subject = new Subject(); - if (typeof EventSource !== 'undefined') { - let emit = (msg: any) => subject.next(JSON.parse(msg.data)); - var source = new EventSource(_url); - source.addEventListener('data', emit); - source.onerror = emit; - } else { - console.warn('SDK Builder: EventSource is not supported'); - } - return subject.asObservable(); - } /** * Login a user with username/email and password. * @@ -681,7 +278,8 @@ export class UserApi extends BaseLoopBackApi { if (include) _urlParams.include = include; let result = this.request(_method, _url, _routeParams, _urlParams, _postBody) .map( - (response: SDKToken) => { + (response: any) => { + response.ttl = parseInt(response.ttl); response.rememberMe = rememberMe; this.auth.setUser(response); this.auth.save(); @@ -805,37 +403,6 @@ export class UserApi extends BaseLoopBackApi { let result = this.request(_method, _url, _routeParams, _urlParams, _postBody); return result; } - - /** - * Create a new instance of the model and persist it into the data source. - * - * @param object data Request data. - * - * This method expects a subset of model properties as request parameters. - * - * @returns object[] An empty reference that will be - * populated with the actual data once the response is returned - * from the server. - * - * - * (The remote method definition does not provide any description. - * This usually means the response is a `User` object.) - * - */ - public createMany(data: Array = []): Observable> { - let _method: string = "POST"; - let _url: string = LoopBackConfig.getPath() + "/" + LoopBackConfig.getApiVersion() + - "/Users"; - let _routeParams: any = {}; - let _postBody: any = { - data: data - }; - let _urlParams: any = {}; - let result = this.request(_method, _url, _routeParams, _urlParams, _postBody); - return result.map((instances: Array) => - instances.map((instance: User) => new User(instance)) - ); - } /** * @ngdoc method * @name sdk.User#getCurrent diff --git a/tests/angular2/src/app/shared/sdk/services/custom/UserCredential.ts b/tests/angular2/src/app/shared/sdk/services/custom/UserCredential.ts index f5fd2fbd..2261a290 100644 --- a/tests/angular2/src/app/shared/sdk/services/custom/UserCredential.ts +++ b/tests/angular2/src/app/shared/sdk/services/custom/UserCredential.ts @@ -1,9 +1,11 @@ /* tslint:disable */ import { Injectable, Inject, Optional } from '@angular/core'; import { Http, Response } from '@angular/http'; +import { SDKModels } from './SDKModels'; import { BaseLoopBackApi } from '../core/base.service'; import { LoopBackConfig } from '../../lb.config'; import { LoopBackAuth } from '../core/auth.service'; +import { SocketConnections } from '../../sockets/socket.connections'; import { LoopBackFilter, } from '../../models/BaseModels'; import { JSONSearchParams } from '../core/search.params'; import { ErrorHandler } from '../core/error.service'; @@ -12,8 +14,6 @@ import { Observable } from 'rxjs/Observable'; import 'rxjs/add/operator/map'; import { UserCredential } from '../../models/UserCredential'; -// Making Sure EventSource Type is available to avoid compilation issues. -declare var EventSource: any; /** * Api services for the `UserCredential` model. @@ -22,448 +22,14 @@ declare var EventSource: any; export class UserCredentialApi extends BaseLoopBackApi { constructor( - @Inject(Http) http: Http, - @Inject(LoopBackAuth) protected auth: LoopBackAuth, - @Inject(JSONSearchParams) protected searchParams: JSONSearchParams, - @Optional() @Inject(ErrorHandler) errorHandler: ErrorHandler + @Inject(Http) protected http: Http, + @Inject(SocketConnections) protected connections: SocketConnections, + @Inject(SDKModels) protected models: SDKModels, + @Inject(LoopBackAuth) protected auth: LoopBackAuth, + @Inject(JSONSearchParams) protected searchParams: JSONSearchParams, + @Optional() @Inject(ErrorHandler) protected errorHandler: ErrorHandler ) { - super(http, auth, searchParams, errorHandler); - } - - /** - * Create a new instance of the model and persist it into the data source. - * - * @param object data Request data. - * - * This method expects a subset of model properties as request parameters. - * - * @returns object An empty reference that will be - * populated with the actual data once the response is returned - * from the server. - * - * - * (The remote method definition does not provide any description. - * This usually means the response is a `UserCredential` object.) - * - */ - public create(data: any = {}): Observable { - let _method: string = "POST"; - let _url: string = LoopBackConfig.getPath() + "/" + LoopBackConfig.getApiVersion() + - "/UserCredentials"; - let _routeParams: any = {}; - let _postBody: any = { - data: data - }; - let _urlParams: any = {}; - let result = this.request(_method, _url, _routeParams, _urlParams, _postBody); - return result.map((instance: UserCredential) => new UserCredential(instance)); - } - - /** - * Patch an existing model instance or insert a new one into the data source. - * - * @param object data Request data. - * - * This method expects a subset of model properties as request parameters. - * - * @returns object An empty reference that will be - * populated with the actual data once the response is returned - * from the server. - * - * - * (The remote method definition does not provide any description. - * This usually means the response is a `UserCredential` object.) - * - */ - public upsert(data: any = {}): Observable { - let _method: string = "PUT"; - let _url: string = LoopBackConfig.getPath() + "/" + LoopBackConfig.getApiVersion() + - "/UserCredentials"; - let _routeParams: any = {}; - let _postBody: any = { - data: data - }; - let _urlParams: any = {}; - let result = this.request(_method, _url, _routeParams, _urlParams, _postBody); - return result.map((instance: UserCredential) => new UserCredential(instance)); - } - - /** - * Replace an existing model instance or insert a new one into the data source. - * - * @param object data Request data. - * - * This method expects a subset of model properties as request parameters. - * - * @returns object An empty reference that will be - * populated with the actual data once the response is returned - * from the server. - * - * - * (The remote method definition does not provide any description. - * This usually means the response is a `UserCredential` object.) - * - */ - public replaceOrCreate(data: any = {}): Observable { - let _method: string = "POST"; - let _url: string = LoopBackConfig.getPath() + "/" + LoopBackConfig.getApiVersion() + - "/UserCredentials/replaceOrCreate"; - let _routeParams: any = {}; - let _postBody: any = { - data: data - }; - let _urlParams: any = {}; - let result = this.request(_method, _url, _routeParams, _urlParams, _postBody); - return result; - } - - /** - * Update an existing model instance or insert a new one into the data source based on the where criteria. - * - * @param object where Criteria to match model instances - * - * @param object data Request data. - * - * This method expects a subset of model properties as request parameters. - * - * @returns object An empty reference that will be - * populated with the actual data once the response is returned - * from the server. - * - * - * (The remote method definition does not provide any description. - * This usually means the response is a `UserCredential` object.) - * - */ - public upsertWithWhere(where: any = {}, data: any = {}): Observable { - let _method: string = "POST"; - let _url: string = LoopBackConfig.getPath() + "/" + LoopBackConfig.getApiVersion() + - "/UserCredentials/upsertWithWhere"; - let _routeParams: any = {}; - let _postBody: any = { - data: data - }; - let _urlParams: any = {}; - if (where) _urlParams.where = where; - let result = this.request(_method, _url, _routeParams, _urlParams, _postBody); - return result.map((instance: UserCredential) => new UserCredential(instance)); - } - - /** - * Check whether a model instance exists in the data source. - * - * @param any id Model id - * - * @returns object An empty reference that will be - * populated with the actual data once the response is returned - * from the server. - * - * Data properties: - * - * - `exists` – `{boolean}` - - */ - public exists(id: any): Observable { - let _method: string = "GET"; - let _url: string = LoopBackConfig.getPath() + "/" + LoopBackConfig.getApiVersion() + - "/UserCredentials/:id/exists"; - let _routeParams: any = { - id: id - }; - let _postBody: any = {}; - let _urlParams: any = {}; - let result = this.request(_method, _url, _routeParams, _urlParams, _postBody); - return result; - } - - /** - * Find a model instance by {{id}} from the data source. - * - * @param any id Model id - * - * @param object filter Filter defining fields and include - * - * @returns object An empty reference that will be - * populated with the actual data once the response is returned - * from the server. - * - * - * (The remote method definition does not provide any description. - * This usually means the response is a `UserCredential` object.) - * - */ - public findById(id: any, filter: LoopBackFilter = {}): Observable { - let _method: string = "GET"; - let _url: string = LoopBackConfig.getPath() + "/" + LoopBackConfig.getApiVersion() + - "/UserCredentials/:id"; - let _routeParams: any = { - id: id - }; - let _postBody: any = {}; - let _urlParams: any = {}; - if (filter) _urlParams.filter = filter; - let result = this.request(_method, _url, _routeParams, _urlParams, _postBody); - return result.map((instance: UserCredential) => new UserCredential(instance)); - } - - /** - * Replace attributes for a model instance and persist it into the data source. - * - * @param any id Model id - * - * @param object data Request data. - * - * This method expects a subset of model properties as request parameters. - * - * @returns object An empty reference that will be - * populated with the actual data once the response is returned - * from the server. - * - * - * (The remote method definition does not provide any description. - * This usually means the response is a `UserCredential` object.) - * - */ - public replaceById(id: any, data: any = {}): Observable { - let _method: string = "POST"; - let _url: string = LoopBackConfig.getPath() + "/" + LoopBackConfig.getApiVersion() + - "/UserCredentials/:id/replace"; - let _routeParams: any = { - id: id - }; - let _postBody: any = { - data: data - }; - let _urlParams: any = {}; - let result = this.request(_method, _url, _routeParams, _urlParams, _postBody); - return result; - } - - /** - * Find all instances of the model matched by filter from the data source. - * - * @param object filter Filter defining fields, where, include, order, offset, and limit - * - * @returns object[] An empty reference that will be - * populated with the actual data once the response is returned - * from the server. - * - * - * (The remote method definition does not provide any description. - * This usually means the response is a `UserCredential` object.) - * - */ - public find(filter: LoopBackFilter = {}): Observable> { - let _method: string = "GET"; - let _url: string = LoopBackConfig.getPath() + "/" + LoopBackConfig.getApiVersion() + - "/UserCredentials"; - let _routeParams: any = {}; - let _postBody: any = {}; - let _urlParams: any = {}; - if (filter) _urlParams.filter = filter; - let result = this.request(_method, _url, _routeParams, _urlParams, _postBody); - return result.map((instances: Array) => - instances.map((instance: UserCredential) => new UserCredential(instance)) - ); - } - - /** - * Find first instance of the model matched by filter from the data source. - * - * @param object filter Filter defining fields, where, include, order, offset, and limit - * - * @returns object An empty reference that will be - * populated with the actual data once the response is returned - * from the server. - * - * - * (The remote method definition does not provide any description. - * This usually means the response is a `UserCredential` object.) - * - */ - public findOne(filter: LoopBackFilter = {}): Observable { - let _method: string = "GET"; - let _url: string = LoopBackConfig.getPath() + "/" + LoopBackConfig.getApiVersion() + - "/UserCredentials/findOne"; - let _routeParams: any = {}; - let _postBody: any = {}; - let _urlParams: any = {}; - if (filter) _urlParams.filter = filter; - let result = this.request(_method, _url, _routeParams, _urlParams, _postBody); - return result.map((instance: UserCredential) => new UserCredential(instance)); - } - - /** - * Update instances of the model matched by {{where}} from the data source. - * - * @param object where Criteria to match model instances - * - * @param object data Request data. - * - * This method expects a subset of model properties as request parameters. - * - * @returns object An empty reference that will be - * populated with the actual data once the response is returned - * from the server. - * - * The number of instances updated - */ - public updateAll(where: any = {}, data: any = {}): Observable { - let _method: string = "POST"; - let _url: string = LoopBackConfig.getPath() + "/" + LoopBackConfig.getApiVersion() + - "/UserCredentials/update"; - let _routeParams: any = {}; - let _postBody: any = { - data: data - }; - let _urlParams: any = {}; - if (where) _urlParams.where = where; - let result = this.request(_method, _url, _routeParams, _urlParams, _postBody); - return result; - } - - /** - * Delete a model instance by {{id}} from the data source. - * - * @param any id Model id - * - * @returns object An empty reference that will be - * populated with the actual data once the response is returned - * from the server. - * - * - * (The remote method definition does not provide any description. - * This usually means the response is a `UserCredential` object.) - * - */ - public deleteById(id: any): Observable { - let _method: string = "DELETE"; - let _url: string = LoopBackConfig.getPath() + "/" + LoopBackConfig.getApiVersion() + - "/UserCredentials/:id"; - let _routeParams: any = { - id: id - }; - let _postBody: any = {}; - let _urlParams: any = {}; - let result = this.request(_method, _url, _routeParams, _urlParams, _postBody); - return result; - } - - /** - * Count instances of the model matched by where from the data source. - * - * @param object where Criteria to match model instances - * - * @returns object An empty reference that will be - * populated with the actual data once the response is returned - * from the server. - * - * Data properties: - * - * - `count` – `{number}` - - */ - public count(where: any = {}): Observable { - let _method: string = "GET"; - let _url: string = LoopBackConfig.getPath() + "/" + LoopBackConfig.getApiVersion() + - "/UserCredentials/count"; - let _routeParams: any = {}; - let _postBody: any = {}; - let _urlParams: any = {}; - if (where) _urlParams.where = where; - let result = this.request(_method, _url, _routeParams, _urlParams, _postBody); - return result; - } - - /** - * Patch attributes for a model instance and persist it into the data source. - * - * @param any id PersistedModel id - * - * @param object data Request data. - * - * This method expects a subset of model properties as request parameters. - * - * @returns object An empty reference that will be - * populated with the actual data once the response is returned - * from the server. - * - * - * (The remote method definition does not provide any description. - * This usually means the response is a `UserCredential` object.) - * - */ - public updateAttributes(id: any, data: any = {}): Observable { - let _method: string = "PUT"; - let _url: string = LoopBackConfig.getPath() + "/" + LoopBackConfig.getApiVersion() + - "/UserCredentials/:id"; - let _routeParams: any = { - id: id - }; - let _postBody: any = { - data: data - }; - let _urlParams: any = {}; - let result = this.request(_method, _url, _routeParams, _urlParams, _postBody); - return result; - } - - /** - * Create a change stream. - * - * @param object data Request data. - * - * - `options` – `{object}` - - * - * @returns object An empty reference that will be - * populated with the actual data once the response is returned - * from the server. - * - * Data properties: - * - * - `changes` – `{ReadableStream}` - - */ - public createChangeStream(): Observable { - let _url: string = LoopBackConfig.getPath() + "/" + LoopBackConfig.getApiVersion() + - "/UserCredentials/change-stream"; - let subject = new Subject(); - if (typeof EventSource !== 'undefined') { - let emit = (msg: any) => subject.next(JSON.parse(msg.data)); - var source = new EventSource(_url); - source.addEventListener('data', emit); - source.onerror = emit; - } else { - console.warn('SDK Builder: EventSource is not supported'); - } - return subject.asObservable(); - } - /** - * Create a new instance of the model and persist it into the data source. - * - * @param object data Request data. - * - * This method expects a subset of model properties as request parameters. - * - * @returns object[] An empty reference that will be - * populated with the actual data once the response is returned - * from the server. - * - * - * (The remote method definition does not provide any description. - * This usually means the response is a `UserCredential` object.) - * - */ - public createMany(data: Array = []): Observable> { - let _method: string = "POST"; - let _url: string = LoopBackConfig.getPath() + "/" + LoopBackConfig.getApiVersion() + - "/UserCredentials"; - let _routeParams: any = {}; - let _postBody: any = { - data: data - }; - let _urlParams: any = {}; - let result = this.request(_method, _url, _routeParams, _urlParams, _postBody); - return result.map((instances: Array) => - instances.map((instance: UserCredential) => new UserCredential(instance)) - ); + super(http, connections, models, auth, searchParams, errorHandler); } /** diff --git a/tests/angular2/src/app/shared/sdk/services/custom/UserIdentity.ts b/tests/angular2/src/app/shared/sdk/services/custom/UserIdentity.ts index 9821b4ff..d8840896 100644 --- a/tests/angular2/src/app/shared/sdk/services/custom/UserIdentity.ts +++ b/tests/angular2/src/app/shared/sdk/services/custom/UserIdentity.ts @@ -1,9 +1,11 @@ /* tslint:disable */ import { Injectable, Inject, Optional } from '@angular/core'; import { Http, Response } from '@angular/http'; +import { SDKModels } from './SDKModels'; import { BaseLoopBackApi } from '../core/base.service'; import { LoopBackConfig } from '../../lb.config'; import { LoopBackAuth } from '../core/auth.service'; +import { SocketConnections } from '../../sockets/socket.connections'; import { LoopBackFilter, } from '../../models/BaseModels'; import { JSONSearchParams } from '../core/search.params'; import { ErrorHandler } from '../core/error.service'; @@ -13,8 +15,6 @@ import 'rxjs/add/operator/map'; import { UserIdentity } from '../../models/UserIdentity'; import { User } from '../../models/User'; -// Making Sure EventSource Type is available to avoid compilation issues. -declare var EventSource: any; /** * Api services for the `UserIdentity` model. @@ -23,12 +23,14 @@ declare var EventSource: any; export class UserIdentityApi extends BaseLoopBackApi { constructor( - @Inject(Http) http: Http, - @Inject(LoopBackAuth) protected auth: LoopBackAuth, - @Inject(JSONSearchParams) protected searchParams: JSONSearchParams, - @Optional() @Inject(ErrorHandler) errorHandler: ErrorHandler + @Inject(Http) protected http: Http, + @Inject(SocketConnections) protected connections: SocketConnections, + @Inject(SDKModels) protected models: SDKModels, + @Inject(LoopBackAuth) protected auth: LoopBackAuth, + @Inject(JSONSearchParams) protected searchParams: JSONSearchParams, + @Optional() @Inject(ErrorHandler) protected errorHandler: ErrorHandler ) { - super(http, auth, searchParams, errorHandler); + super(http, connections, models, auth, searchParams, errorHandler); } /** @@ -61,442 +63,6 @@ export class UserIdentityApi extends BaseLoopBackApi { return result; } - /** - * Create a new instance of the model and persist it into the data source. - * - * @param object data Request data. - * - * This method expects a subset of model properties as request parameters. - * - * @returns object An empty reference that will be - * populated with the actual data once the response is returned - * from the server. - * - * - * (The remote method definition does not provide any description. - * This usually means the response is a `UserIdentity` object.) - * - */ - public create(data: any = {}): Observable { - let _method: string = "POST"; - let _url: string = LoopBackConfig.getPath() + "/" + LoopBackConfig.getApiVersion() + - "/UserIdentities"; - let _routeParams: any = {}; - let _postBody: any = { - data: data - }; - let _urlParams: any = {}; - let result = this.request(_method, _url, _routeParams, _urlParams, _postBody); - return result.map((instance: UserIdentity) => new UserIdentity(instance)); - } - - /** - * Patch an existing model instance or insert a new one into the data source. - * - * @param object data Request data. - * - * This method expects a subset of model properties as request parameters. - * - * @returns object An empty reference that will be - * populated with the actual data once the response is returned - * from the server. - * - * - * (The remote method definition does not provide any description. - * This usually means the response is a `UserIdentity` object.) - * - */ - public upsert(data: any = {}): Observable { - let _method: string = "PUT"; - let _url: string = LoopBackConfig.getPath() + "/" + LoopBackConfig.getApiVersion() + - "/UserIdentities"; - let _routeParams: any = {}; - let _postBody: any = { - data: data - }; - let _urlParams: any = {}; - let result = this.request(_method, _url, _routeParams, _urlParams, _postBody); - return result.map((instance: UserIdentity) => new UserIdentity(instance)); - } - - /** - * Replace an existing model instance or insert a new one into the data source. - * - * @param object data Request data. - * - * This method expects a subset of model properties as request parameters. - * - * @returns object An empty reference that will be - * populated with the actual data once the response is returned - * from the server. - * - * - * (The remote method definition does not provide any description. - * This usually means the response is a `UserIdentity` object.) - * - */ - public replaceOrCreate(data: any = {}): Observable { - let _method: string = "POST"; - let _url: string = LoopBackConfig.getPath() + "/" + LoopBackConfig.getApiVersion() + - "/UserIdentities/replaceOrCreate"; - let _routeParams: any = {}; - let _postBody: any = { - data: data - }; - let _urlParams: any = {}; - let result = this.request(_method, _url, _routeParams, _urlParams, _postBody); - return result; - } - - /** - * Update an existing model instance or insert a new one into the data source based on the where criteria. - * - * @param object where Criteria to match model instances - * - * @param object data Request data. - * - * This method expects a subset of model properties as request parameters. - * - * @returns object An empty reference that will be - * populated with the actual data once the response is returned - * from the server. - * - * - * (The remote method definition does not provide any description. - * This usually means the response is a `UserIdentity` object.) - * - */ - public upsertWithWhere(where: any = {}, data: any = {}): Observable { - let _method: string = "POST"; - let _url: string = LoopBackConfig.getPath() + "/" + LoopBackConfig.getApiVersion() + - "/UserIdentities/upsertWithWhere"; - let _routeParams: any = {}; - let _postBody: any = { - data: data - }; - let _urlParams: any = {}; - if (where) _urlParams.where = where; - let result = this.request(_method, _url, _routeParams, _urlParams, _postBody); - return result.map((instance: UserIdentity) => new UserIdentity(instance)); - } - - /** - * Check whether a model instance exists in the data source. - * - * @param any id Model id - * - * @returns object An empty reference that will be - * populated with the actual data once the response is returned - * from the server. - * - * Data properties: - * - * - `exists` – `{boolean}` - - */ - public exists(id: any): Observable { - let _method: string = "GET"; - let _url: string = LoopBackConfig.getPath() + "/" + LoopBackConfig.getApiVersion() + - "/UserIdentities/:id/exists"; - let _routeParams: any = { - id: id - }; - let _postBody: any = {}; - let _urlParams: any = {}; - let result = this.request(_method, _url, _routeParams, _urlParams, _postBody); - return result; - } - - /** - * Find a model instance by {{id}} from the data source. - * - * @param any id Model id - * - * @param object filter Filter defining fields and include - * - * @returns object An empty reference that will be - * populated with the actual data once the response is returned - * from the server. - * - * - * (The remote method definition does not provide any description. - * This usually means the response is a `UserIdentity` object.) - * - */ - public findById(id: any, filter: LoopBackFilter = {}): Observable { - let _method: string = "GET"; - let _url: string = LoopBackConfig.getPath() + "/" + LoopBackConfig.getApiVersion() + - "/UserIdentities/:id"; - let _routeParams: any = { - id: id - }; - let _postBody: any = {}; - let _urlParams: any = {}; - if (filter) _urlParams.filter = filter; - let result = this.request(_method, _url, _routeParams, _urlParams, _postBody); - return result.map((instance: UserIdentity) => new UserIdentity(instance)); - } - - /** - * Replace attributes for a model instance and persist it into the data source. - * - * @param any id Model id - * - * @param object data Request data. - * - * This method expects a subset of model properties as request parameters. - * - * @returns object An empty reference that will be - * populated with the actual data once the response is returned - * from the server. - * - * - * (The remote method definition does not provide any description. - * This usually means the response is a `UserIdentity` object.) - * - */ - public replaceById(id: any, data: any = {}): Observable { - let _method: string = "POST"; - let _url: string = LoopBackConfig.getPath() + "/" + LoopBackConfig.getApiVersion() + - "/UserIdentities/:id/replace"; - let _routeParams: any = { - id: id - }; - let _postBody: any = { - data: data - }; - let _urlParams: any = {}; - let result = this.request(_method, _url, _routeParams, _urlParams, _postBody); - return result; - } - - /** - * Find all instances of the model matched by filter from the data source. - * - * @param object filter Filter defining fields, where, include, order, offset, and limit - * - * @returns object[] An empty reference that will be - * populated with the actual data once the response is returned - * from the server. - * - * - * (The remote method definition does not provide any description. - * This usually means the response is a `UserIdentity` object.) - * - */ - public find(filter: LoopBackFilter = {}): Observable> { - let _method: string = "GET"; - let _url: string = LoopBackConfig.getPath() + "/" + LoopBackConfig.getApiVersion() + - "/UserIdentities"; - let _routeParams: any = {}; - let _postBody: any = {}; - let _urlParams: any = {}; - if (filter) _urlParams.filter = filter; - let result = this.request(_method, _url, _routeParams, _urlParams, _postBody); - return result.map((instances: Array) => - instances.map((instance: UserIdentity) => new UserIdentity(instance)) - ); - } - - /** - * Find first instance of the model matched by filter from the data source. - * - * @param object filter Filter defining fields, where, include, order, offset, and limit - * - * @returns object An empty reference that will be - * populated with the actual data once the response is returned - * from the server. - * - * - * (The remote method definition does not provide any description. - * This usually means the response is a `UserIdentity` object.) - * - */ - public findOne(filter: LoopBackFilter = {}): Observable { - let _method: string = "GET"; - let _url: string = LoopBackConfig.getPath() + "/" + LoopBackConfig.getApiVersion() + - "/UserIdentities/findOne"; - let _routeParams: any = {}; - let _postBody: any = {}; - let _urlParams: any = {}; - if (filter) _urlParams.filter = filter; - let result = this.request(_method, _url, _routeParams, _urlParams, _postBody); - return result.map((instance: UserIdentity) => new UserIdentity(instance)); - } - - /** - * Update instances of the model matched by {{where}} from the data source. - * - * @param object where Criteria to match model instances - * - * @param object data Request data. - * - * This method expects a subset of model properties as request parameters. - * - * @returns object An empty reference that will be - * populated with the actual data once the response is returned - * from the server. - * - * The number of instances updated - */ - public updateAll(where: any = {}, data: any = {}): Observable { - let _method: string = "POST"; - let _url: string = LoopBackConfig.getPath() + "/" + LoopBackConfig.getApiVersion() + - "/UserIdentities/update"; - let _routeParams: any = {}; - let _postBody: any = { - data: data - }; - let _urlParams: any = {}; - if (where) _urlParams.where = where; - let result = this.request(_method, _url, _routeParams, _urlParams, _postBody); - return result; - } - - /** - * Delete a model instance by {{id}} from the data source. - * - * @param any id Model id - * - * @returns object An empty reference that will be - * populated with the actual data once the response is returned - * from the server. - * - * - * (The remote method definition does not provide any description. - * This usually means the response is a `UserIdentity` object.) - * - */ - public deleteById(id: any): Observable { - let _method: string = "DELETE"; - let _url: string = LoopBackConfig.getPath() + "/" + LoopBackConfig.getApiVersion() + - "/UserIdentities/:id"; - let _routeParams: any = { - id: id - }; - let _postBody: any = {}; - let _urlParams: any = {}; - let result = this.request(_method, _url, _routeParams, _urlParams, _postBody); - return result; - } - - /** - * Count instances of the model matched by where from the data source. - * - * @param object where Criteria to match model instances - * - * @returns object An empty reference that will be - * populated with the actual data once the response is returned - * from the server. - * - * Data properties: - * - * - `count` – `{number}` - - */ - public count(where: any = {}): Observable { - let _method: string = "GET"; - let _url: string = LoopBackConfig.getPath() + "/" + LoopBackConfig.getApiVersion() + - "/UserIdentities/count"; - let _routeParams: any = {}; - let _postBody: any = {}; - let _urlParams: any = {}; - if (where) _urlParams.where = where; - let result = this.request(_method, _url, _routeParams, _urlParams, _postBody); - return result; - } - - /** - * Patch attributes for a model instance and persist it into the data source. - * - * @param any id PersistedModel id - * - * @param object data Request data. - * - * This method expects a subset of model properties as request parameters. - * - * @returns object An empty reference that will be - * populated with the actual data once the response is returned - * from the server. - * - * - * (The remote method definition does not provide any description. - * This usually means the response is a `UserIdentity` object.) - * - */ - public updateAttributes(id: any, data: any = {}): Observable { - let _method: string = "PUT"; - let _url: string = LoopBackConfig.getPath() + "/" + LoopBackConfig.getApiVersion() + - "/UserIdentities/:id"; - let _routeParams: any = { - id: id - }; - let _postBody: any = { - data: data - }; - let _urlParams: any = {}; - let result = this.request(_method, _url, _routeParams, _urlParams, _postBody); - return result; - } - - /** - * Create a change stream. - * - * @param object data Request data. - * - * - `options` – `{object}` - - * - * @returns object An empty reference that will be - * populated with the actual data once the response is returned - * from the server. - * - * Data properties: - * - * - `changes` – `{ReadableStream}` - - */ - public createChangeStream(): Observable { - let _url: string = LoopBackConfig.getPath() + "/" + LoopBackConfig.getApiVersion() + - "/UserIdentities/change-stream"; - let subject = new Subject(); - if (typeof EventSource !== 'undefined') { - let emit = (msg: any) => subject.next(JSON.parse(msg.data)); - var source = new EventSource(_url); - source.addEventListener('data', emit); - source.onerror = emit; - } else { - console.warn('SDK Builder: EventSource is not supported'); - } - return subject.asObservable(); - } - /** - * Create a new instance of the model and persist it into the data source. - * - * @param object data Request data. - * - * This method expects a subset of model properties as request parameters. - * - * @returns object[] An empty reference that will be - * populated with the actual data once the response is returned - * from the server. - * - * - * (The remote method definition does not provide any description. - * This usually means the response is a `UserIdentity` object.) - * - */ - public createMany(data: Array = []): Observable> { - let _method: string = "POST"; - let _url: string = LoopBackConfig.getPath() + "/" + LoopBackConfig.getApiVersion() + - "/UserIdentities"; - let _routeParams: any = {}; - let _postBody: any = { - data: data - }; - let _urlParams: any = {}; - let result = this.request(_method, _url, _routeParams, _urlParams, _postBody); - return result.map((instances: Array) => - instances.map((instance: UserIdentity) => new UserIdentity(instance)) - ); - } - /** * The name of the model represented by this $resource, * i.e. `UserIdentity`. diff --git a/tests/angular2/src/app/shared/sdk/services/custom/index.ts b/tests/angular2/src/app/shared/sdk/services/custom/index.ts index d6894cd2..b79d7cac 100644 --- a/tests/angular2/src/app/shared/sdk/services/custom/index.ts +++ b/tests/angular2/src/app/shared/sdk/services/custom/index.ts @@ -10,4 +10,5 @@ export * from './Account'; export * from './RoomAccount'; export * from './Storage'; export * from './Core'; +export * from './SDKModels'; export * from './logger.service'; diff --git a/tests/angular2/src/app/shared/sdk/sockets/index.ts b/tests/angular2/src/app/shared/sdk/sockets/index.ts deleted file mode 100644 index a45e85f9..00000000 --- a/tests/angular2/src/app/shared/sdk/sockets/index.ts +++ /dev/null @@ -1,2 +0,0 @@ -export * from './socket.driver'; -export * from './socket.connections'; diff --git a/tests/angular2/src/app/shared/sdk/sockets/socket.browser.ts b/tests/angular2/src/app/shared/sdk/sockets/socket.browser.ts new file mode 100644 index 00000000..3cf06e96 --- /dev/null +++ b/tests/angular2/src/app/shared/sdk/sockets/socket.browser.ts @@ -0,0 +1,7 @@ +/* tslint:disable */ +import * as io from 'socket.io-client'; +export class SocketBrowser { + connect(url: any, options: any) { + return io(url, options); + } +} diff --git a/tests/angular2/src/app/shared/sdk/sockets/socket.connections.ts b/tests/angular2/src/app/shared/sdk/sockets/socket.connections.ts index 42e9f1fe..85a9361e 100644 --- a/tests/angular2/src/app/shared/sdk/sockets/socket.connections.ts +++ b/tests/angular2/src/app/shared/sdk/sockets/socket.connections.ts @@ -1,4 +1,7 @@ /* tslint:disable */ +import { Injectable, Inject } from '@angular/core'; +import { SocketDriver } from './socket.driver'; +import { AccessToken } from '../models'; /** * @author Jonathan Casarrubias * @module SocketConnections @@ -8,45 +11,45 @@ * connection, it will use the SDK Socket Driver Available currently supporting * Angular 2 for web and NativeScript 2. **/ -import { SocketDriver } from './socket.driver'; -import { AccessToken } from '../models'; +@Injectable() export class SocketConnections { - private static connections: any = {}; - private static configured: boolean = false; - static getHandler(url: string, token: AccessToken) { - if (!SocketConnections.connections[url]) { + private connections: any = {}; + private configured: boolean = false; + constructor(@Inject(SocketDriver) private driver: SocketDriver) {} + getHandler(url: string, token: AccessToken) { + if (!this.connections[url]) { console.log('Creating a new connection with: ', url); let config: any = { log: false, secure: false, forceWebsockets: true }; - SocketConnections.connections[url] = SocketDriver.connect(url, config); - SocketConnections.connections[url].on('connect', () => { - if (!SocketConnections.configured) - SocketConnections.setupConnection(url, token, config); + this.connections[url] = this.driver.connect(url, config); + this.connections[url].on('connect', () => { + if (!this.configured) + this.setupConnection(url, token, config); }); let forceConfig: any = setInterval(() => { - if (!SocketConnections.configured && SocketConnections.connections[url].connected) { + if (!this.configured && this.connections[url].connected) { console.info('Forcing IO Configuration'); - SocketConnections.setupConnection(url, token, config); + this.setupConnection(url, token, config); clearInterval(forceConfig); - } else if (SocketConnections.configured) { + } else if (this.configured) { clearInterval(forceConfig); } }, 1000) } else { console.log('Reusing existing connection: ', url); } - return SocketConnections.connections[url]; + return this.connections[url]; } - private static setupConnection(url: string, token: AccessToken, config: any): void { - SocketConnections.configured = true; + private setupConnection(url: string, token: AccessToken, config: any): void { + this.configured = true; console.log('Connected to %s', url); if(token.id) { - SocketConnections.connections[url].emit('authentication', token); + this.connections[url].emit('authentication', token); } - SocketConnections.connections[url].on('unauthorized', (res: any) => console.error('Unauthenticated', res)); - setInterval(() => SocketConnections.connections[url].emit('lb-ping'), 15000); - SocketConnections.connections[url].on('lb-pong', (data: any) => console.info('Heartbeat: ', data)); - SocketConnections.connections[url].on('disconnect', (data: any) => { + this.connections[url].on('unauthorized', (res: any) => console.error('Unauthenticated', res)); + setInterval(() => this.connections[url].emit('lb-ping'), 15000); + this.connections[url].on('lb-pong', (data: any) => console.info('Heartbeat: ', data)); + this.connections[url].on('disconnect', (data: any) => { console.info('Unexpected disconnection from IO - Socket IO will try to reconnect'); }); } diff --git a/tests/angular2/src/app/shared/sdk/sockets/socket.driver.ts b/tests/angular2/src/app/shared/sdk/sockets/socket.driver.ts index 19d007e3..69b5c7bc 100644 --- a/tests/angular2/src/app/shared/sdk/sockets/socket.driver.ts +++ b/tests/angular2/src/app/shared/sdk/sockets/socket.driver.ts @@ -1,7 +1,11 @@ -/* tslint:disable */ -import * as io from 'socket.io-client'; +/** + * @module SocketDriver + * @author Jonathan Casarrubias + * @license MIT + * @description + * The SocketDriver class is used for dependency injection swapping. + * It will be provided using factory method from different sources. + **/ export class SocketDriver { - static connect(url: any, options: any) { - return io(url, options); - } + connect(url: any, options: any) {} } diff --git a/tests/angular2/src/app/shared/sdk/sockets/socket.native.ts b/tests/angular2/src/app/shared/sdk/sockets/socket.native.ts new file mode 100644 index 00000000..1f0232bd --- /dev/null +++ b/tests/angular2/src/app/shared/sdk/sockets/socket.native.ts @@ -0,0 +1,7 @@ +/* tslint:disable */ +var SocketIO = require('nativescript-socket.io'); +export class SocketNative { + connect(url: any, options: any) { + return SocketIO.connect(url, options); + } +} diff --git a/tests/angular2/src/app/shared/sdk/sockets/socket.node.ts b/tests/angular2/src/app/shared/sdk/sockets/socket.node.ts new file mode 100644 index 00000000..16abf4d4 --- /dev/null +++ b/tests/angular2/src/app/shared/sdk/sockets/socket.node.ts @@ -0,0 +1,7 @@ +/* tslint:disable */ +import * as io from 'socket.io-client'; +export class SocketNode { + connect(url: any, options: any) { + return io(url, options); + } +} diff --git a/tests/angular2/src/app/shared/sdk/storage/cookie.browser.ts b/tests/angular2/src/app/shared/sdk/storage/cookie.browser.ts new file mode 100644 index 00000000..baf0ad04 --- /dev/null +++ b/tests/angular2/src/app/shared/sdk/storage/cookie.browser.ts @@ -0,0 +1,44 @@ +import { Injectable } from '@angular/core'; +/** +* @module CookieBrowser +* @author Jonathan Casarrubias +* @license MIT +* @description +* Stand-alone cookie service for browsers +**/ +@Injectable() +export class CookieBrowser { + private cookies: { [key: string]: any } = {}; + get(key: string): any { + if (!this.cookies[key]) { + let cookie = window.document + .cookie.split('; ') + .filter((item: any) => item.split('=')[0] === key).pop(); + if (!cookie) { + return null; + } + + this.cookies[key] = this.parse(cookie.split('=').pop()); + } + + return this.cookies[key]; + } + + set(key: string, value: any, expires?: Date) { + this.cookies[key] = value; + let cookie = `${key}=${value}${expires ? `; expires=${ expires.toUTCString() }` : ''}`; + window.document.cookie = cookie; + } + + remove(key: string) { + document.cookie = key + '=; expires=Thu, 01 Jan 1970 00:00:01 GMT;'; + } + + private parse(value: any) { + try { + return JSON.parse(value); + } catch (e) { + return value; + } + } +} diff --git a/tests/angular2/src/app/shared/sdk/storage/cookie.node.ts b/tests/angular2/src/app/shared/sdk/storage/cookie.node.ts new file mode 100644 index 00000000..58b4bb91 --- /dev/null +++ b/tests/angular2/src/app/shared/sdk/storage/cookie.node.ts @@ -0,0 +1,19 @@ +declare var Zone: any; +import { Injectable } from '@angular/core'; + +@Injectable() +export class CookieNode { + + get(key: string) { + let cookies: { [key: string]: number } = Zone.current.get('req').cookies; + return cookies[key]; + } + + set(key: string, value: any): any { + Zone.current.get('res').cookies(key, value).send('Cookie is set'); + } + // Will this be really needed? + remove(key: string, value: any): any { + Zone.current.get('res').cookies(key, '; expires=Thu, 01 Jan 1970 00:00:01 GMT;').send('Cookie is removed'); + } +} diff --git a/tests/angular2/src/app/shared/sdk/storage/internal.storage.ts b/tests/angular2/src/app/shared/sdk/storage/internal.storage.ts new file mode 100644 index 00000000..ea25828c --- /dev/null +++ b/tests/angular2/src/app/shared/sdk/storage/internal.storage.ts @@ -0,0 +1,13 @@ +/** + * @module InternalStorage + * @author Jonathan Casarrubias + * @license MIT + * @description + * The InternalStorage class is used for dependency injection swapping. + * It will be provided using factory method from different sources. + **/ +export class InternalStorage { + get(key: string): any {} + set(key: string, value: any): any {} + remove(key: string): any {} +} diff --git a/tests/angular2/src/app/shared/sdk/storage/storage.driver.ts b/tests/angular2/src/app/shared/sdk/storage/storage.driver.ts deleted file mode 100644 index a26dcbc6..00000000 --- a/tests/angular2/src/app/shared/sdk/storage/storage.driver.ts +++ /dev/null @@ -1,12 +0,0 @@ -/* tslint:disable */ -export class StorageDriver { - static set(key: string, value: string) { - localStorage.setItem(key, value); - } - static get(key: string): string { - return localStorage.getItem(key); - } - static remove(key: string): any { - localStorage.removeItem(key); - } -} diff --git a/tests/angular2/src/app/shared/sdk/storage/storage.native.ts b/tests/angular2/src/app/shared/sdk/storage/storage.native.ts new file mode 100644 index 00000000..3368a31d --- /dev/null +++ b/tests/angular2/src/app/shared/sdk/storage/storage.native.ts @@ -0,0 +1,20 @@ +/* tslint:disable */ +import * as AppSettings from 'application-settings'; +import { Injectable } from '@angular/core'; + +@Injectable() +export class StorageNative { + set(key: string, value: any) { + AppSettings.setString(key, String(value)); + } + get(key: string): any { + return AppSettings.getString(key); + } + remove(key: string): any { + if (AppSettings.hasKey(key)) { + AppSettings.remove(key); + } else { + console.log('Trying to remove unexisting key: ', key); + } + } +} diff --git a/tests/angular2/src/app/user-service.service.spec.ts b/tests/angular2/src/app/user-service.service.spec.ts index 29ae4732..0d1e0605 100644 --- a/tests/angular2/src/app/user-service.service.spec.ts +++ b/tests/angular2/src/app/user-service.service.spec.ts @@ -1,7 +1,7 @@ /* tslint:disable:no-unused-variable */ import { TestBed, async, inject } from '@angular/core/testing'; -import { SDKModule } from './shared/sdk'; +import { SDKBrowserModule } from './shared/sdk'; import { User, AccessToken } from './shared/sdk/models'; import { UserApi } from './shared/sdk/services'; @@ -9,7 +9,7 @@ describe('Service: User Service', () => { beforeEach(() => { TestBed.configureTestingModule({ imports: [ - SDKModule.forRoot() + SDKBrowserModule.forRoot() ] }); });