├── .gitattributes ├── .gitignore ├── .npmignore ├── .travis.yml ├── Installation.md ├── README.md ├── Release_Information.xlsx ├── _config.yml ├── config.ts ├── core ├── api │ └── metadataController.ts ├── config.ts ├── constants │ ├── constantKeys.ts │ ├── decorators.ts │ ├── index.ts │ ├── metadata.ts │ └── reflect.ts ├── decorators │ ├── allowanonymous.ts │ ├── association.ts │ ├── authorize.ts │ ├── entityAction.ts │ ├── index.ts │ ├── interfaces │ │ ├── IProcessControlParams.ts │ │ ├── IProcessControlService.ts │ │ ├── association-params.ts │ │ ├── decorator-metadata.ts │ │ ├── decorator-params.ts │ │ ├── index.ts │ │ ├── postfilter-params.ts │ │ ├── preauthorize-params.ts │ │ ├── repository-params.ts │ │ ├── response.ts │ │ ├── worker-params.ts │ │ ├── workerParamsDto.ts │ │ └── workerassociation-params.ts │ ├── jsonignore.ts │ ├── optimisticlocking.ts │ ├── postfilter.ts │ ├── preauthorize.ts │ ├── processControl.ts │ ├── promisable.ts │ ├── repository.ts │ ├── required.ts │ ├── transaction.ts │ ├── transient.ts │ ├── upload.ts │ ├── worker.spec.ts │ └── workerAssociation.ts ├── dynamic │ ├── crud.entity.ts │ ├── dynamic-controller.ts │ ├── dynamic-repository.ts │ ├── model-entity.ts │ └── security-impl.ts ├── enums │ ├── decorator-type.ts │ ├── entity-change.ts │ ├── index.ts │ ├── jsonignore-enum.ts │ ├── optimisticlock-type.ts │ ├── repo-actions-enum.ts │ └── storage-type-enum.ts ├── exports │ ├── index.ts │ ├── repositories.ts │ ├── router.ts │ └── schemas.ts ├── index.ts ├── initialize │ ├── initialize-controllers.ts │ ├── initialize-messengers.ts │ ├── initialize-repositories.ts │ ├── initialize-sockets.ts │ └── initialize.ts ├── interfaces │ ├── entity-service.ts │ ├── queryOptions.ts │ ├── schema-generator.ts │ └── shard-Info.ts ├── metadata │ ├── actionUtils.ts │ ├── interfaces │ │ ├── decorator-metadata.ts │ │ ├── field-metadata.ts │ │ └── metaroot.ts │ ├── metadata.ts │ ├── param-type-custom.ts │ ├── searchUtils.ts │ ├── utils-mock.ts │ ├── utils.spec.ts │ └── utils.ts ├── reflect │ └── reflect-utils.ts ├── services │ ├── instance-service.ts │ ├── post-filter-service.ts │ ├── pre-auth-service.ts │ └── workerProcessService.ts └── utils │ ├── classtype.ts │ ├── index.ts │ ├── nodemodule-type.ts │ ├── serial.ts │ └── types.ts ├── current-user-detail-service.ts ├── custom.d.ts ├── decorators ├── interfaces │ └── authorization-params.ts └── metadata │ └── searchUtils.spec.ts ├── di ├── decorators │ ├── index.ts │ ├── inject.ts │ ├── interfaces │ │ └── inject-params.ts │ └── service.ts ├── di.spec.ts ├── di.ts ├── index.ts └── tests │ ├── cyclic-a.ts │ ├── cyclic-b.ts │ ├── service-a.ts │ ├── service-b.ts │ ├── service-c.ts │ ├── service-d.ts │ └── service-e.ts ├── filePath ├── gulpfile.js ├── images ├── atlassian.png ├── browserstack-logo-600x315.png ├── compare_frameworkes2.png ├── node-data-multiple-db-code.png ├── node-data-multiple-db.png ├── realsociable.png ├── talentica.png └── talentica_old.png ├── index.d.ts ├── jsdocconf.json ├── license ├── logging ├── index.ts └── winstonLog.ts ├── login.html ├── models ├── IWorkerProcess.ts ├── baseModel.ts ├── baseSequelizeModel.ts ├── blogPostSqlModel.ts ├── blogSqlModel.ts ├── sequelizeSchool.ts ├── sequelizeStudent.ts ├── sequelizeTeacher.ts ├── session.ts └── storyModel.ts ├── mongoose ├── constants │ ├── decorators.ts │ └── index.ts ├── datatype.ts ├── db.ts ├── decorators │ ├── document.ts │ ├── entity.ts │ ├── field.ts │ ├── index.ts │ └── interfaces │ │ ├── document-params.ts │ │ ├── field-params.ts │ │ └── index.ts ├── dynamic-schema.ts ├── enums │ ├── document-strict.ts │ └── index.ts ├── index.ts ├── mongoose-model-helper.ts ├── mongoose-model.spec.ts ├── mongoose-model.ts ├── mongoose-service.ts ├── mongooseSchemaGenerator.ts ├── pubsub │ ├── messenger.ts │ └── model.ts ├── schema.ts └── utils │ └── index.ts ├── node-data.njsproj ├── node-data.png ├── node-data.sln ├── node-data1.png ├── package-lock.json ├── package.json ├── postman_scripts ├── Embedded_child.postman_collection.json └── WorkerAndProcessControlTest.json ├── publish.bat ├── readme-code-uniformity.md ├── repositories ├── AuthorizationRepository.ts ├── blogPostsqlrepository.ts ├── blogsqlrepository.ts ├── schoolRepository.ts ├── storyrepository.ts ├── studentRepository.ts └── teacherRepository.ts ├── scripts └── ci-version-devbuild.js ├── search └── elasticSearchUtils.ts ├── security-config.d.ts ├── security-config.ts ├── security └── auth │ ├── auth-service.spec.ts │ ├── auth-service.ts │ ├── authcontroller.spec.ts │ ├── authcontroller.ts │ ├── autherizationParam.ts │ ├── domain.ts │ ├── principalContext.ts │ ├── security-utils.spec.ts │ ├── security-utils.ts │ ├── user-detail-service.ts │ ├── user-details.ts │ └── user.ts ├── sequelizeimp ├── constants │ ├── decorators.ts │ └── index.ts ├── datatype.ts ├── decorators │ ├── column.ts │ ├── entity.ts │ ├── index.ts │ ├── interfaces │ │ ├── column-params.ts │ │ ├── entity-params.ts │ │ └── index.ts │ └── transient.ts ├── dynamic-schema.ts ├── enums │ ├── entity-strict.ts │ └── index.ts ├── index.ts ├── schema.ts ├── sequelizeService.ts └── utils │ └── index.ts ├── server.ts ├── spec └── support │ └── jasmine.json ├── tests ├── models │ ├── baseModel.ts │ ├── city.ts │ ├── company.ts │ ├── employee.ts │ ├── planet.ts │ ├── processControlModel.ts │ ├── role.ts │ ├── rolemodel.ts │ ├── school.ts │ ├── subject.ts │ ├── teacher.ts │ ├── topic.ts │ ├── user.ts │ └── usermodel.ts ├── preauth-service.ts ├── repositories │ ├── cityRepository.ts │ ├── companyRepository.ts │ ├── employeeRepository.ts │ ├── planetRepository.ts │ ├── processControlRepository.ts │ ├── promisableTestRepository.ts │ ├── role.repository.ts │ ├── schoolRepository.ts │ ├── subjectRepository.ts │ ├── teacherRepository.ts │ ├── topicRepository.ts │ └── userRepository.ts └── services │ ├── authorizationService.ts │ ├── processControlService.ts │ └── teacherService.ts ├── tsconfig.json ├── tsd.json ├── tslint.json ├── typings.json ├── unit-test ├── InitializeModels.ts ├── MockDataForRelation.ts ├── OutputFiles │ ├── file.txt │ └── file1.txt ├── Sample │ ├── GlobalObject.ts │ ├── MockService.ts │ ├── SampleClassA.ts │ ├── SampleClassB.ts │ └── format.spec.ts ├── controllers │ ├── format.ts │ └── usercontroller.spec.ts ├── dto │ ├── blogDto.ts │ └── format.ts ├── models │ ├── blog.ts │ ├── course.ts │ ├── format.ts │ ├── student.ts │ └── testModels.ts ├── repository │ ├── blogRepository.ts │ └── user-repository-mock.ts ├── sample-tests │ ├── GlobalObject.ts │ ├── MockService.ts │ ├── SampleClassA.ts │ ├── SampleClassB.ts │ └── format.spec.ts └── services │ ├── MockAuthService.ts │ ├── MockService.ts │ ├── blogServiceImpl.ts │ └── interface │ └── blogService.ts ├── views ├── authlogin.ejs ├── home.ejs └── login.ejs └── worker.ts /.gitattributes: -------------------------------------------------------------------------------- 1 | * text=auto 2 | 3 | *.js eol=lf 4 | *.ts eol=lf -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | node_modules/** 2 | .*/** 3 | **/*.js.map 4 | **/*.js 5 | bin/** 6 | typings/**/*.* 7 | obj/**/*.* 8 | *.suo 9 | *.htm 10 | **/*.orig 11 | out/** 12 | coverage/** 13 | npm-debug.log 14 | nodedataLog.log -------------------------------------------------------------------------------- /.npmignore: -------------------------------------------------------------------------------- 1 | node_modules/** 2 | bin/** 3 | typings/** 4 | obj/**/*.* 5 | *.suo 6 | *.htm 7 | **/*.orig 8 | out/** 9 | *.njsproj 10 | *.sln 11 | server.js 12 | **/server.* 13 | *.spec.* -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: node_js 2 | node_js: 3 | - '5.6' 4 | sudo: required 5 | deploy: 6 | provider: npm 7 | email: vakilpratik@gmail.com 8 | api_key: 9 | secure: HvGIOtJDSNunlyMFTclm6caDv+q6HGRlPIFFtm58OlERG/UQ2U2JDGdEICsrmBSGNuLdGzJZ1Ua1iyJhEdccKHxO3tIILQb0/El0yhL6LzFFSby17wbAgDbdhYaHjPOlU1/HbAqTLu5UDSsZpAeETp97HAI7csWJWYmstc3GoQ2/ugZJYky3XQlRLuGtNa9LsT6fZQw7esOuqwM0v8I9veVafVRjxDDXICnws0+66n2vfrmeSnU4P6eblReats5WyKNWAeDHOjAEvvSg1ReJY3/1IoOCgFlpVLXr0VpiMVAKbMtHrV1ZBpUVQ+o9HHQS4RMOPGydK9CvWT7EnT3fDEa4oZhPN+assmPNzAtMh9A58X/28WzjoYOx9YmseTmulLSycTbw6KlZkM25BECA8IMzoif5DrCYw045s0Vh5KXc2+CQmOyXo2Zsm6HWF31ltRFj3wuMm7XDess9zoNOJV7EcpblV0+xllN/2s4AN/mc4848zo7aSYKDevY65bhDpOiTngVhD0SvoDlHdHMcRs16USwYS2fxzCwiXpEvs7SUrWQGnL7PFGOxWwX9z0/s7sqtIRDVKXiN4cQIjPZvIdhpfkaaL/6Y9UNHS/a+AoR7EV7zqxqw7zYok5tFGPQKlGtvZGjCRkm3kC3PfJ3qI8OASgSaB71JgTLvrqzlmv8= 10 | -------------------------------------------------------------------------------- /Installation.md: -------------------------------------------------------------------------------- 1 |  2 | 3 | Setup 4 | 1) Install Nodejs - https://nodejs.org/en/download/current/ (5.7.0) 5 | 2) Install MongoDb - https://www.mongodb.org/downloads#production (3.2) 6 | 3) Run mongodb 7 | > Create 'c:\data' Folder 8 | > Goto 'C:\Program Files\MongoDB\Server\3.2\bin' and start 'mongod.exe' 9 | 4) Install RoboMongo - https://robomongo.org/download (0.9.0 RC7) 10 | 5) Start RoboMongo and connect to 'localhost:27017' 11 | 6) Install postman - http://www.getpostman.com/ 12 | 7) open command prompt at root directory 13 | > run 'npm install' 14 | > run 'tsd install' 15 | 16 | Compile 17 | 1) using gulp 18 | > open command prompt at root directory 19 | > run 'gulp compile-ts' 20 | 2) using visual studio 21 | > Configure visual studio as explained below*** 22 | > Compile the project 23 | 24 | Run 25 | 1) using gulp 26 | > open command prompt at root directory 27 | > run 'gulp compile-ts' 28 | 2) using visual studio 29 | > Configure visual studio as explained below 30 | > Run the project 31 | 32 | 33 | ***Steps for Configuring visual studio 34 | 1) Install Visual Studio 2015 Community - https://www.visualstudio.com/en-us/downloads/download-visual-studio-vs.aspx 35 | 2) Install Nodejs for Visual Studio 2015 - https://www.visualstudio.com/en-us/features/node-js-vs.aspx 36 | 3) Install Typescript for Visual Studio 2015 - https://visualstudiogallery.msdn.microsoft.com/418d1f01-e58c-453a-a7d0-8381b562d499 37 | 4) Open Tools->Options 38 | - Disable intellisence of Nodejs 39 | > Select TextEditor->Nodejs->Intellisense 40 | > Select 'No Intellisense' 41 | - Enable auto compiling of Typescript 42 | > Select TextEditor->Typescript->Project 43 | > Select 'Auto Compile Typescript' and 'Use AMD' 44 | Apply the changes 45 | 5) Restart visual studio 46 | 47 | Troubleshoot (if compiling the visual studio project fails) 48 | Replace npm to %appdata% 49 | - goto 'C:\Program Files\nodejs' 50 | - copy 'npm' and 'npm.cmd' and replace at '%appdata%/npm' 51 | - goto 'C:\Program Files\nodejs\node_modules' 52 | - copy 'npm' folder and replace at '%appdata%/npm/node_modules' 53 | - restart visual studio -------------------------------------------------------------------------------- /Release_Information.xlsx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ratneshsinghparihar/Node-Data/0f4beb2384678e1b973d55c01d7dbce68ec96602/Release_Information.xlsx -------------------------------------------------------------------------------- /_config.yml: -------------------------------------------------------------------------------- 1 | theme: jekyll-theme-cayman -------------------------------------------------------------------------------- /config.ts: -------------------------------------------------------------------------------- 1 | 2 | let DbConnectionOptions = { server: { poolSize: 20, domainsEnabled: true, socketOptions: { keepAlive: 1 } } }; 3 | 4 | export class Config { 5 | public static DbConnection: string = "mongodb://localhost:27017/test_nodedata"; 6 | public static DbConnectionOptions = DbConnectionOptions; 7 | public static basePath: string = "data"; 8 | public static apiversion: string = "v1"; 9 | 10 | public static ElasticSearchConnection : string = "http://localhost:9200"; 11 | public static ApplyElasticSearch : boolean = false; 12 | public static ignorePaths = ['server.js']; 13 | public static internalIgnorePaths = ['gulpfile.js']; 14 | public static isMultiThreaded = true; // This param is for configuring multi process using worker/ process control attribute.. 15 | public static worker = 'worker.js'; 16 | public static process = 1; 17 | public static isCacheEnabled: boolean = false; // by default caching is false, make it true to enable cahing in your application 18 | } 19 | 20 | export class SqlConfig { 21 | 22 | public static isSqlEnabled: boolean = false; 23 | public static database: string = "test"; 24 | public static username: string = "sa"; 25 | public static password: string = "Apr@2016"; 26 | 27 | public static sequlizeSetting: any = { 28 | host: '172.19.101.120', 29 | dialect: 'mssql', 30 | 31 | pool: { 32 | max: 5, 33 | min: 0, 34 | idle: 10000 35 | } 36 | 37 | // SQLite only 38 | //storage: 'path/to/database.sqlite' 39 | }; 40 | 41 | } 42 | 43 | export class Security { 44 | public static isAutheticationEnabled = "disabled";//allowed values: "disabled","enabledWithoutAuthorization","enabledWithAuthorization" 45 | public static authenticationType = "TokenBased";//allowed values: "passwordBased","TokenBased" 46 | public static useFaceBookAuth = false; 47 | } 48 | 49 | export class facebookAuth { 50 | public static clientID = '11';// your App ID 51 | public static clientSecret = 'aa';// your App Secret 52 | public static callbackURL = 'http://localhost:23548/auth/facebook/callback'; 53 | } 54 | 55 | -------------------------------------------------------------------------------- /core/api/metadataController.ts: -------------------------------------------------------------------------------- 1 | /// 2 | import {router} from '../exports'; 3 | import {MetaUtils} from "../metadata/utils"; 4 | import {DecoratorType} from '../enums'; 5 | import * as Utils from "../utils"; 6 | import {GetRepositoryForName} from '../dynamic/dynamic-repository'; 7 | import {MetaData} from '../metadata/metadata'; 8 | import {IAssociationParams} from '../decorators/interfaces'; 9 | import * as Enumerable from 'linq'; 10 | import * as securityUtils from '../../security/auth/security-utils'; 11 | 12 | export interface metaDataObject { 13 | id?: string; 14 | type?: string; 15 | properties?: Array 16 | } 17 | 18 | export interface metaDataInnerObject { 19 | name?: string; 20 | type?: string; //"string","number","date","Object","Array" 21 | subtype?: string; 22 | metadata?: metaDataObject 23 | pathFromRoot?: Array 24 | } 25 | 26 | 27 | export interface metaDataMapping { 28 | from: metaDataObject; 29 | to: metaDataObject; 30 | type?: string; // "data" default , "name" 31 | innerMapping?: Array 32 | } 33 | 34 | export class MetadataController { 35 | private path: string; 36 | private metaData: { [key: string]: any } = {}; 37 | constructor() { 38 | this.path = "/Metadata"; 39 | this.AddRoutes(); 40 | } 41 | 42 | private AddRoutes() { 43 | router.get(this.path, securityUtils.ensureLoggedIn(), (req, res) => { 44 | this.metaData['All'] = this.metaData['All'] ? this.metaData['All'] : this.getAllMetadata(req); 45 | this.sendresult(req, res, this.metaData['All']); 46 | }); 47 | 48 | router.get(this.path + '/:type', securityUtils.ensureLoggedIn(), (req, res) => { 49 | this.sendresult(req, res, this.getMetadata(req, req.params.type)); 50 | }); 51 | } 52 | 53 | private sendresult(req, res, result) { 54 | res.set("Content-Type", "application/json"); 55 | 56 | res.send(JSON.stringify(result, null, 4)); 57 | } 58 | 59 | private getAllMetadata(req): any { 60 | var metaData = {}; 61 | metaData['_links'] = []; 62 | 63 | var names = Utils.getAllResourceNames(); 64 | Enumerable.from(names).forEach(x=> { 65 | var object = {}; 66 | object['name'] = x; 67 | object['metadata'] = this.getProtocol(req) + '://' + req.get('host') + this.path + '/' + x; 68 | metaData['_links'].push(object); 69 | }); 70 | 71 | return metaData; 72 | } 73 | 74 | public getMetadata(req, type): any { 75 | 76 | if (this.metaData[type]) 77 | return this.metaData[type]; 78 | var baseRelMeta = this.getProtocol(req) + '://' + req.get('host') + this.path + '/' 79 | var metadata:any = MetaUtils.getDescriptiveMetadata(type, baseRelMeta); 80 | this.metaData[type] = metadata; 81 | return metadata; 82 | } 83 | 84 | private getProtocol(req) : string{ 85 | if(req.headers && req.headers["x-arr-ssl"]){ 86 | return "https"; 87 | } 88 | else{ 89 | return req.protocol; 90 | } 91 | } 92 | 93 | } 94 | 95 | export default MetadataController; 96 | -------------------------------------------------------------------------------- /core/config.ts: -------------------------------------------------------------------------------- 1 | export class Config { 2 | public static DbConnection: string = "mongodb://localhost:27017/userDatabase"; 3 | public static basePath: string = "data"; 4 | public static apiversion: string = "v1"; 5 | 6 | public static ElasticSearchConnection : string = "http://localhost:9200"; 7 | public static ApplyElasticSearch : boolean = false; 8 | } 9 | 10 | export class Security { 11 | public static isAutheticationEnabled = "enabledWithoutAuthorization";//allowed values: "disabled","enabledWithoutAuthorization","enabledWithAuthorization" 12 | public static authenticationType = "passwordBased";//allowed values: "passwordBased","TokenBased" 13 | } 14 | 15 | export class facebookAuth { 16 | public static clientID = '11';// your App ID 17 | public static clientSecret = 'aa';// your App Secret 18 | public static callbackURL = 'http://localhost:23548/auth/facebook/callback'; 19 | } 20 | -------------------------------------------------------------------------------- /core/constants/constantKeys.ts: -------------------------------------------------------------------------------- 1 | export class ConstantKeys { 2 | public static FullyLoaded = '__FullyLoaded'; 3 | public static TempId = '__TempId'; 4 | public static collectionName = 'collectionName'; 5 | public static property = 'property'; 6 | public static parentId = 'parentId'; 7 | public static parent = 'parent'; 8 | public static transaction = 'TRANSACTION'; 9 | } -------------------------------------------------------------------------------- /core/constants/decorators.ts: -------------------------------------------------------------------------------- 1 |  2 | export class Decorators { 3 | public static DOCUMENT = 'document'; 4 | public static ENTITY = 'entity'; 5 | public static FIELD = 'field'; 6 | public static COLUMN = 'column'; 7 | public static INJECT = 'inject'; 8 | public static INJECTBYNAME = 'injectbyname'; 9 | public static MANYTOMANY = 'manytomany'; 10 | public static MANYTOONE = 'manytoone'; 11 | public static ONETOMANY = 'onetomany'; 12 | public static ONETOONE = 'onetoone'; 13 | public static REPOSITORY = 'repository'; 14 | public static SERVICE = 'service'; 15 | public static AUTHORIZE = 'authorize'; 16 | public static PREAUTHORIZE = 'preauthorize'; 17 | public static POSTFILTER = 'postfilter'; 18 | public static UPLOAD = 'upload'; 19 | public static JSONIGNORE = 'jsonignore'; 20 | public static REQUIRED = 'required'; 21 | public static TRANSIENT = 'transient'; 22 | public static ALLOWANONYMOUS = 'allowanonymous'; 23 | public static WORKER = 'worker'; 24 | public static OPTIMISTICLOCK = 'OptimisticLocking'; 25 | public static PROMISABLE = 'Promisable'; 26 | public static PROCESS_START = 'processStart'; 27 | public static PROCESS_END = 'processEnd'; 28 | public static PROCESS_START_AND_END = 'processStartEnd'; 29 | public static TRANSACTION = 'transaction'; 30 | } 31 | 32 | export enum ExportTypes { 33 | 34 | NONE = 0, 35 | REST = 1, 36 | WS = 2, 37 | WS_BROAD_CAST = 4, 38 | PUB_SUB = 8, 39 | WS_WS_BROAD_CAST_PUB_SUB=14, 40 | ALL = 15, 41 | 42 | 43 | } 44 | 45 | export var RelationDecorators: Array = [Decorators.ONETOONE, Decorators.ONETOMANY, Decorators.MANYTOONE, Decorators.MANYTOMANY]; -------------------------------------------------------------------------------- /core/constants/index.ts: -------------------------------------------------------------------------------- 1 | export {Decorators, RelationDecorators,ExportTypes} from './decorators'; 2 | export {ReflectConstants} from './reflect'; 3 | export {MetadataConstants} from './metadata'; 4 | export {ConstantKeys} from './constantKeys'; -------------------------------------------------------------------------------- /core/constants/metadata.ts: -------------------------------------------------------------------------------- 1 | export class MetadataConstants { 2 | public static CLASSDECORATOR_PROPKEY = '__'; 3 | public static PROPKEY_PARAMINDEX_JOIN = '_'; 4 | } -------------------------------------------------------------------------------- /core/constants/reflect.ts: -------------------------------------------------------------------------------- 1 | export class ReflectConstants { 2 | public static DESIGNTYPE = 'design:type'; 3 | public static DESIGNPARAMTYPES = 'design:paramtypes'; 4 | public static DESIGNRETURNTYPE = 'design:returntype'; 5 | } -------------------------------------------------------------------------------- /core/decorators/allowanonymous.ts: -------------------------------------------------------------------------------- 1 | import {MetaUtils} from "../metadata/utils"; 2 | import {Decorators} from '../constants/decorators'; 3 | import {DecoratorType} from '../enums/decorator-type'; 4 | import {JsonIgnore} from '../enums/jsonignore-enum'; 5 | 6 | export function allowanonymous(params?: JsonIgnore): any { 7 | params = params || {}; 8 | return function (target: Object, propertyKey: string) { 9 | MetaUtils.addMetaData(target, 10 | { 11 | decorator: Decorators.ALLOWANONYMOUS, 12 | decoratorType: DecoratorType.PROPERTY, 13 | params: params, 14 | propertyKey: propertyKey 15 | }); 16 | }; 17 | } 18 | -------------------------------------------------------------------------------- /core/decorators/association.ts: -------------------------------------------------------------------------------- 1 | import {Decorators} from '../constants'; 2 | import {DecoratorType} from '../enums'; 3 | import {ParamTypeCustom} from '../metadata/param-type-custom'; 4 | 5 | import {MetaUtils} from "../metadata/utils"; 6 | import {IAssociationParams} from './interfaces/association-params'; 7 | import * as ReflectUtils from '../reflect/reflect-utils'; 8 | 9 | export function onetomany(params: IAssociationParams) { 10 | return (target: Object, propertyKey: string) => addMetadata(target, propertyKey, Decorators.ONETOMANY, params); 11 | } 12 | 13 | export function manytoone(params: IAssociationParams) { 14 | return (target: Object, propertyKey: string) => addMetadata(target, propertyKey, Decorators.MANYTOONE, params); 15 | } 16 | 17 | export function manytomany(params: IAssociationParams) { 18 | return (target: Object, propertyKey: string) => addMetadata(target, propertyKey, Decorators.MANYTOMANY, params); 19 | } 20 | 21 | export function onetoone(params: IAssociationParams) { 22 | return (target: Object, propertyKey: string) => addMetadata(target, propertyKey, Decorators.ONETOONE, params); 23 | } 24 | 25 | function addMetadata(target: Object, propertyKey: string, decorator: string, params: IAssociationParams) { 26 | params = params || {}; 27 | 28 | var name = target.constructor.name; 29 | console.log(decorator, ' - propertyKey: ', propertyKey, ', target:', target.constructor && target.constructor.name); 30 | 31 | let itemType = ReflectUtils.getDesignType(target, propertyKey); 32 | let type = (params && params.itemType) 33 | ? new ParamTypeCustom(params.itemType, itemType === Array) 34 | : new ParamTypeCustom(itemType, false); 35 | MetaUtils.addMetaData( 36 | target, 37 | { 38 | decorator: decorator, 39 | decoratorType: DecoratorType.PROPERTY, 40 | params: params, 41 | propertyKey: propertyKey, 42 | type: type 43 | }); 44 | } -------------------------------------------------------------------------------- /core/decorators/authorize.ts: -------------------------------------------------------------------------------- 1 |  2 | import {MetaUtils} from "../metadata/utils"; 3 | import {Decorators} from '../constants/decorators'; 4 | import {DecoratorType} from '../enums/decorator-type'; 5 | 6 | export function authorize(params: { roles: Array }): any { 7 | params = params || {}; 8 | 9 | return function (target: Function, propertyKey: string) { 10 | MetaUtils.addMetaData(target, 11 | { 12 | decorator: Decorators.AUTHORIZE, 13 | decoratorType: DecoratorType.METHOD, 14 | params: params, 15 | propertyKey: propertyKey 16 | }); 17 | }; 18 | } 19 | -------------------------------------------------------------------------------- /core/decorators/index.ts: -------------------------------------------------------------------------------- 1 | export {onetomany, manytoone, manytomany, onetoone} from './association'; 2 | export {jsonignore} from './jsonignore'; 3 | export {repository} from './repository'; 4 | export {required} from './required'; 5 | export {allowanonymous} from './allowanonymous'; 6 | export {transient} from './transient'; 7 | export {Worker} from './workerAssociation'; 8 | export {promisable, IPromisableFetchParam, IPromisableParam} from './promisable'; 9 | export {processStart, processEnd, processStartEnd} from './processControl'; 10 | export {OptimisticLocking} from './optimisticlocking'; 11 | 12 | -------------------------------------------------------------------------------- /core/decorators/interfaces/IProcessControlParams.ts: -------------------------------------------------------------------------------- 1 | export interface IProcessControlParams { 2 | indexofArgumentForTargetObjectId?: number, 3 | type: string, 4 | action: string, 5 | indexofArgumentForTargetObject?: number, 6 | executeInWorker?: boolean, 7 | executeInDistributedWorker?: boolean, 8 | notify?: boolean 9 | } -------------------------------------------------------------------------------- /core/decorators/interfaces/IProcessControlService.ts: -------------------------------------------------------------------------------- 1 | import {workerParamsDto} from './workerParamsDto'; 2 | import {ProcessControlModel} from '../../../tests/models/processControlModel'; 3 | import { IProcessControlParams } from './IProcessControlParams'; 4 | 5 | export interface IProcessControlService { 6 | initialize(serviceName: string, methodName: string, targetObjectId: any, processControlParams: IProcessControlParams, taskInfo?: workerParamsDto): Q.Promise; 7 | startProcess(): Q.Promise; 8 | completeProcess(responseData: any): Q.Promise; 9 | errorOutProcess(errorMessage: string): Q.Promise; 10 | sendResponse(processModel: any, workerDetails?: workerParamsDto): Q.IPromise; 11 | } 12 | 13 | export const processControlServiceName = 'ProcessControlService'; 14 | 15 | /** 16 | * get or set processControlContext through PrincipalContext 17 | * Use to store processControlModel in PrincipalContext to access in main application as well as in worker process 18 | */ 19 | export const processControlContext = "processControlContext"; 20 | -------------------------------------------------------------------------------- /core/decorators/interfaces/association-params.ts: -------------------------------------------------------------------------------- 1 | export interface IAssociationParams { 2 | rel: string, 3 | itemType: Object, 4 | embedded?: boolean, 5 | eagerLoading: boolean, 6 | deleteCascade?: boolean, 7 | properties?: Array, 8 | persist?: boolean, 9 | storageType?:string, 10 | propertyKey?:string, 11 | foreignKey?:string 12 | } -------------------------------------------------------------------------------- /core/decorators/interfaces/decorator-metadata.ts: -------------------------------------------------------------------------------- 1 | import {MetaData} from '../../metadata/metadata'; 2 | 3 | /** {decorator: { 4 | "field": { 5 | "_id": { 6 | 7 | }, 8 | "name":{ 9 | 10 | } 11 | }, 12 | "onetomany": {} 13 | } 14 | }**/ 15 | export type DecoratorMetaData = { [key: string]: { [key: string]: MetaData } }; -------------------------------------------------------------------------------- /core/decorators/interfaces/decorator-params.ts: -------------------------------------------------------------------------------- 1 | export interface IDecoratorParams { 2 | name: string 3 | } -------------------------------------------------------------------------------- /core/decorators/interfaces/index.ts: -------------------------------------------------------------------------------- 1 | export {IAssociationParams} from './association-params'; 2 | export {IRepositoryParams} from './repository-params'; 3 | export {IPreauthorizeParams} from './preauthorize-params'; 4 | export {IPostfilterParams} from './postfilter-params'; 5 | -------------------------------------------------------------------------------- /core/decorators/interfaces/postfilter-params.ts: -------------------------------------------------------------------------------- 1 | export interface IPostfilterParams { 2 | serviceName: string, 3 | methodName: string 4 | } -------------------------------------------------------------------------------- /core/decorators/interfaces/preauthorize-params.ts: -------------------------------------------------------------------------------- 1 | export interface IPreauthorizeParams { 2 | serviceName: string, 3 | methodName: string 4 | //params: { 5 | // id: string, 6 | // entity: string, 7 | // other?: Array 8 | //}; 9 | } -------------------------------------------------------------------------------- /core/decorators/interfaces/repository-params.ts: -------------------------------------------------------------------------------- 1 | 2 | export interface IRepositoryParams { 3 | path: string, 4 | model: any; 5 | } -------------------------------------------------------------------------------- /core/decorators/interfaces/response.ts: -------------------------------------------------------------------------------- 1 | export class responseDetails{ 2 | message: any; 3 | status: any; 4 | error: any; 5 | } -------------------------------------------------------------------------------- /core/decorators/interfaces/worker-params.ts: -------------------------------------------------------------------------------- 1 | export interface WorkerParams { 2 | serviceName?: string, 3 | servicemethodName?: string, 4 | arguments?: [any], 5 | principalContext?: any 6 | } -------------------------------------------------------------------------------- /core/decorators/interfaces/workerParamsDto.ts: -------------------------------------------------------------------------------- 1 | export class workerParamsDto { 2 | id: any; 3 | serviceName: string; 4 | servicemethodName: string; 5 | arguments: [any]; 6 | principalContext: any; 7 | processId: number; 8 | initialize: boolean; 9 | status: string; 10 | message: string; 11 | result: any; 12 | } -------------------------------------------------------------------------------- /core/decorators/interfaces/workerassociation-params.ts: -------------------------------------------------------------------------------- 1 | import {WorkerParams} from './worker-params'; 2 | 3 | export interface WorkerAssociation { 4 | name?: string, 5 | workerParams?: WorkerParams 6 | } -------------------------------------------------------------------------------- /core/decorators/jsonignore.ts: -------------------------------------------------------------------------------- 1 | import {MetaUtils} from "../metadata/utils"; 2 | import {Decorators} from '../constants/decorators'; 3 | import {DecoratorType} from '../enums/decorator-type'; 4 | import {JsonIgnore} from '../enums/jsonignore-enum'; 5 | 6 | 7 | /** 8 | * Ignores the property for an update in db from frontend or any external api source. 9 | * Params: An optional parameter, if no parameter supplied means the property will not be available in frontend at all. 10 | * if parameter Jsonignore.READ means the property will be available to frontend side but readonly mode. (can't altered by any external api in db) 11 | * @param params 12 | */ 13 | export function jsonignore(params?: JsonIgnore): any { 14 | params = params || {}; 15 | return function (target: Object, propertyKey: string) { 16 | MetaUtils.addMetaData(target, 17 | { 18 | decorator: Decorators.JSONIGNORE, 19 | decoratorType: DecoratorType.PROPERTY, 20 | params: params, 21 | propertyKey: propertyKey 22 | }); 23 | }; 24 | } 25 | -------------------------------------------------------------------------------- /core/decorators/optimisticlocking.ts: -------------------------------------------------------------------------------- 1 | import {MetaUtils} from "../metadata/utils"; 2 | import {Decorators} from '../constants/decorators'; 3 | import {DecoratorType} from '../enums/decorator-type'; 4 | import {JsonIgnore} from '../enums/jsonignore-enum'; 5 | import { OptimisticLockType } from "../enums/optimisticlock-type"; 6 | 7 | export function OptimisticLocking(params?: JsonIgnore): any { 8 | params = params || {}; 9 | return function (target: Object, propertyKey: string) { 10 | let type = params && params["type"]; 11 | switch(type){ 12 | case OptimisticLockType.VERSION: 13 | MetaUtils.addMetaData(target, 14 | { 15 | decorator: Decorators.OPTIMISTICLOCK, 16 | decoratorType: DecoratorType.PROPERTY, 17 | params: params, 18 | propertyKey: propertyKey 19 | }); 20 | break; 21 | } 22 | }; 23 | } 24 | -------------------------------------------------------------------------------- /core/decorators/postfilter.ts: -------------------------------------------------------------------------------- 1 | import {MetaUtils} from "../metadata/utils"; 2 | import * as Utils from "../utils"; 3 | import {Decorators} from '../constants/decorators'; 4 | import {DecoratorType} from '../enums/decorator-type'; 5 | import {IPostfilterParams} from './interfaces/postfilter-params'; 6 | //var domain = require('../../security/auth/domain'); 7 | import {PostFilterService} from '../services/post-filter-service'; 8 | 9 | export function postfilter(params: IPostfilterParams): any { 10 | params = params || {}; 11 | 12 | return function (target: Function, propertyKey: string, descriptor: any) { 13 | MetaUtils.addMetaData(target, 14 | { 15 | decorator: Decorators.POSTFILTER, 16 | decoratorType: DecoratorType.METHOD, 17 | params: params, 18 | propertyKey: propertyKey 19 | }); 20 | 21 | var originalMethod = descriptor.value; 22 | 23 | descriptor.value = function () { 24 | var result = originalMethod.apply(this, arguments); 25 | if (Utils.isPromise(result)){ 26 | return result.then(ret => { 27 | return PostFilterService.postFilter(ret, params); 28 | }); 29 | } 30 | else { 31 | return PostFilterService.postFilter(result, params); 32 | } 33 | } 34 | return descriptor; 35 | }; 36 | } 37 | -------------------------------------------------------------------------------- /core/decorators/repository.ts: -------------------------------------------------------------------------------- 1 | import {MetaUtils} from "../metadata/utils"; 2 | import {Decorators} from '../constants/decorators'; 3 | import {ExportTypes} from '../constants/decorators'; 4 | import {DecoratorType} from '../enums/decorator-type'; 5 | 6 | //export function repository(path: string, model: Function) { 7 | export function repository(params: { path: string, model: any, exportType?: ExportTypes, broadCastType?: ExportTypes, sharded?: boolean, dedicatedMessenger?: boolean,bufferBatchSize?:number }) { 8 | //params = params || {}; 9 | 10 | return function (target: Function) { 11 | console.log('Repository - Path : ', params.path); 12 | target.prototype.path = params.path; 13 | target.prototype.model = params.model; 14 | if (params.exportType==undefined) { 15 | params.exportType = ExportTypes.REST; 16 | } 17 | MetaUtils.addMetaData(((target).prototype || target), 18 | { 19 | decorator: Decorators.REPOSITORY, 20 | decoratorType: DecoratorType.CLASS, 21 | 22 | params: params 23 | }); 24 | }; 25 | } 26 | -------------------------------------------------------------------------------- /core/decorators/required.ts: -------------------------------------------------------------------------------- 1 | import {MetaUtils} from "../metadata/utils"; 2 | import {Decorators} from '../constants/decorators'; 3 | import {DecoratorType} from '../enums/decorator-type'; 4 | 5 | export function required(): any { 6 | return function (target: Object, propertyKey: string) { 7 | MetaUtils.addMetaData(target, 8 | { 9 | decorator: Decorators.REQUIRED, 10 | decoratorType: DecoratorType.PROPERTY, 11 | params: {}, 12 | propertyKey: propertyKey 13 | }); 14 | }; 15 | } 16 | -------------------------------------------------------------------------------- /core/decorators/transaction.ts: -------------------------------------------------------------------------------- 1 | import {MetaUtils } from "../metadata/utils"; 2 | import {Decorators} from '../constants/decorators'; 3 | import {DecoratorType} from '../enums/decorator-type'; 4 | import {PrincipalContext} from '../../security/auth/principalContext'; 5 | import * as Utils from "../utils"; 6 | import { MetaData } from "../metadata/metadata"; 7 | import {pathRepoMap} from '../dynamic/model-entity'; 8 | import {ConstantKeys} from '../constants/constantKeys'; 9 | var Q = require('q'); 10 | 11 | export function transaction(params?: any): any { 12 | params = params || {}; 13 | 14 | return function (target: Function, propertyKey: string, descriptor: any) { 15 | MetaUtils.addMetaData(target, 16 | { 17 | decorator: Decorators.TRANSACTION, 18 | decoratorType: DecoratorType.METHOD, 19 | params: params, 20 | propertyKey: propertyKey 21 | }); 22 | 23 | var originalMethod = descriptor.value; 24 | descriptor.value = function () { 25 | let transaction = PrincipalContext.get(ConstantKeys.transaction); 26 | let args = []; 27 | args = Array.apply(null, arguments); 28 | if(!transaction && this.path){ 29 | let entityService = Utils.entityService(pathRepoMap[this.path].modelType) 30 | return entityService.startTransaction().then(transaction=>{ 31 | PrincipalContext.save(ConstantKeys.transaction,transaction); 32 | return executeOriginalMethod.apply(this, [originalMethod, args]).then(result=>{ 33 | return entityService.commitTransaction(PrincipalContext.get(ConstantKeys.transaction)).then(commit=>{ 34 | return result; 35 | }); 36 | }); 37 | }).catch(exc=>{ 38 | return entityService.rollbackTransaction(PrincipalContext.get(ConstantKeys.transaction)).then(result=>{ 39 | PrincipalContext.save(ConstantKeys.transaction, null); 40 | throw exc; 41 | }) 42 | }); 43 | } 44 | else{ 45 | return executeOriginalMethod.apply(this, [originalMethod, args]); 46 | } 47 | } 48 | return descriptor; 49 | } 50 | } 51 | 52 | function executeOriginalMethod(originalMethod, args){ 53 | let ret = originalMethod.apply(this, args); 54 | if (Utils.isPromise(ret)) { 55 | return ret; 56 | } 57 | else{ 58 | return Q.when(ret); 59 | } 60 | } -------------------------------------------------------------------------------- /core/decorators/transient.ts: -------------------------------------------------------------------------------- 1 | import {MetaUtils} from "../metadata/utils"; 2 | import {Decorators} from '../constants/decorators'; 3 | import {DecoratorType} from '../enums/decorator-type'; 4 | 5 | export function transient(): any { 6 | return function (target: Object, propertyKey: string) { 7 | MetaUtils.addMetaData(target, 8 | { 9 | decorator: Decorators.TRANSIENT, 10 | decoratorType: DecoratorType.PROPERTY, 11 | params: {}, 12 | propertyKey: propertyKey 13 | }); 14 | }; 15 | } 16 | -------------------------------------------------------------------------------- /core/decorators/upload.ts: -------------------------------------------------------------------------------- 1 | import {MetaUtils} from "../metadata/utils"; 2 | import {Decorators} from '../constants/decorators'; 3 | import {DecoratorType} from '../enums/decorator-type'; 4 | 5 | export function upload(params: { destination: string }): any { 6 | return function (target: Function, propertyKey: string) { 7 | MetaUtils.addMetaData(target, 8 | { 9 | decorator: Decorators.UPLOAD, 10 | decoratorType: DecoratorType.METHOD, 11 | params: params, 12 | propertyKey: propertyKey 13 | }); 14 | }; 15 | } 16 | -------------------------------------------------------------------------------- /core/dynamic/crud.entity.ts: -------------------------------------------------------------------------------- 1 | 2 | import {field, document} from '../../mongoose/decorators'; 3 | import { jsonignore } from '../decorators'; 4 | import {DynamicRepository} from './dynamic-repository'; 5 | import {Types} from 'mongoose'; 6 | import * as Enumerable from 'linq'; 7 | import {repoFromModel} from "./model-entity"; 8 | import {MetaUtils} from "../metadata/utils"; 9 | import { Decorators} from '../constants/decorators'; 10 | import {transient} from "../decorators/transient"; 11 | 12 | export class CrudEntity { 13 | @field({ primary: true, autogenerated: true }) 14 | _id: Types.ObjectId | string | number | Date; 15 | 16 | 17 | @field() 18 | @transient() 19 | __dbEntity: any; 20 | 21 | constructor() { 22 | ["put", "post", "delete", "patch"].forEach((prop) => { 23 | Object.defineProperty((this).__proto__, prop, { 24 | writable: false, 25 | value: CrudEntity.prototype[prop] 26 | }); 27 | }); 28 | } 29 | 30 | private getCaller(trace: any):string { 31 | for (let i = 2; i < trace.length; i++) { 32 | if (trace[i].getTypeName() 33 | && trace[i].getTypeName() != null 34 | && trace[i].getTypeName() != "wrappedPromise") { 35 | return trace[i].getTypeName(); 36 | } 37 | } 38 | return undefined; 39 | } 40 | 41 | getRepo(): DynamicRepository { 42 | return this.getRepository(); 43 | } 44 | 45 | private getRepository(): DynamicRepository { 46 | 47 | let stack = require('stack-trace'); 48 | let trace = stack.get(); 49 | let caller = this.getCaller(trace); 50 | if (!caller) 51 | return undefined; 52 | 53 | 54 | // target.constructor.name 55 | 56 | let cachedModels = MetaUtils.getMetaDataFromName(caller); 57 | MetaUtils.getMetaDataFromName(caller); 58 | if (cachedModels && cachedModels.length) { 59 | return undefined; 60 | } 61 | 62 | if (this.constructor && this.constructor.name) { 63 | let c = repoFromModel; 64 | var meta = MetaUtils.getMetaData(this.constructor, Decorators.DOCUMENT); 65 | if (meta && meta[0]) { 66 | return repoFromModel[meta[0].params.name]; 67 | } 68 | 69 | } 70 | return undefined; 71 | } 72 | put(): Q.Promise { 73 | 74 | 75 | if (!this.getRepository()) { 76 | return Q.reject("repository not found") 77 | } 78 | return this.getRepository().put(this._id, this); 79 | } 80 | post(): Q.Promise{ 81 | if (!this.getRepository()) { 82 | return Q.reject("repository not found") 83 | } 84 | return this.getRepository().post(this); 85 | } 86 | delete() { 87 | if (!this.getRepository()) { 88 | return Q.reject("repository not found") 89 | } 90 | return this.getRepository().delete(this._id); 91 | } 92 | patch() { 93 | if (!this.getRepository()) { 94 | return Q.reject("repository not found") 95 | } 96 | return this.getRepository().patch(this._id, this); 97 | } 98 | } 99 | 100 | export const put: () => Q.Promise < any > = () => { 101 | if (!this.getRepository()) { 102 | return Q.reject("repository not found") 103 | } 104 | return this.getRepository().put(this._id, this); 105 | }; 106 | 107 | export default CrudEntity; 108 | -------------------------------------------------------------------------------- /core/dynamic/model-entity.ts: -------------------------------------------------------------------------------- 1 | import {PrincipalContext} from '../../security/auth/principalContext'; 2 | import {User} from '../../security/auth/user'; 3 | var schemaNameModel: { [key: string]: any } = {}; 4 | export var pathRepoMap: { [key: string]: { schemaName: string, modelType: string } } = {}; 5 | export var repoFromModel: { [key: string]: any } = {}; 6 | 7 | export function updateModelEntity(schemaName: string, entity: any, model: any, schema: any) { 8 | if (!schemaNameModel[schemaName]) { 9 | schemaNameModel[schemaName] = { entity: entity, model: model ,schema: schema }; 10 | } 11 | } 12 | 13 | export function getEntity(schemaName: string): any { 14 | if (!schemaNameModel[schemaName]) 15 | return null; 16 | 17 | return schemaNameModel[schemaName]['entity']; 18 | } 19 | 20 | export function getModel(schemaName: string): any { 21 | if (!schemaNameModel[schemaName]) 22 | return null; 23 | 24 | //let currentUser: User = PrincipalContext.User; 25 | //if (currentUser && currentUser.getDbName()) { 26 | // return getDbSpecifcModel(schemaName, schemaNameModel[schemaName]['schema'], currentUser.getDbName()); 27 | //} 28 | return schemaNameModel[schemaName]['model']; 29 | } 30 | 31 | export function getSchema(schemaName: string) { 32 | if (!schemaNameModel[schemaName]) 33 | return null; 34 | return schemaNameModel[schemaName]['schema']; 35 | } -------------------------------------------------------------------------------- /core/dynamic/security-impl.ts: -------------------------------------------------------------------------------- 1 | //This is default behaviour of the methods.It will be overridden at run time. 2 | export function ensureLoggedIn() { 3 | return function (req, res, next) { 4 | next(); 5 | } 6 | } 7 | 8 | export function isAuthorize(req: any, repository: any, invokedFunction?: string): boolean { 9 | return true; 10 | } 11 | 12 | 13 | export function getContextObjectFromSession(sessionObj: any) { 14 | return {}; 15 | } 16 | 17 | export function updateSession(inObj: any, curSession: any) { 18 | return new Promise((resolve, reject) => { 19 | resolve(true); 20 | }) 21 | } 22 | 23 | export function getSession(query: any) { 24 | return new Promise((resolve, reject) => { 25 | resolve({}); 26 | }) 27 | } 28 | 29 | export function getSessionLastTimeStampForChannel(query: any, channel: string, curSession?: any) { 30 | return new Promise((resolve, reject) => { 31 | resolve(new Date()); 32 | }) 33 | } 34 | 35 | export function getSessionLastAckForChannel(query: any, channel: string, curSession?: any) { 36 | return new Promise((resolve, reject) => { 37 | resolve(new Date()); 38 | }) 39 | } -------------------------------------------------------------------------------- /core/enums/decorator-type.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * Enum of DecoratorType, i.e. where decorator is defined. 3 | * @enum 4 | */ 5 | export enum DecoratorType { 6 | CLASS, 7 | METHOD, 8 | PROPERTY, 9 | PARAM, 10 | MODEL 11 | } -------------------------------------------------------------------------------- /core/enums/entity-change.ts: -------------------------------------------------------------------------------- 1 | export enum EntityChange { 2 | put, 3 | post, 4 | patch, 5 | delete 6 | } -------------------------------------------------------------------------------- /core/enums/index.ts: -------------------------------------------------------------------------------- 1 | export {DecoratorType} from './decorator-type'; 2 | export {EntityChange} from './entity-change'; 3 | export {StorageType} from './storage-type-enum'; 4 | -------------------------------------------------------------------------------- /core/enums/jsonignore-enum.ts: -------------------------------------------------------------------------------- 1 | export class JsonIgnore { 2 | /** 3 | * property will available to frontend side in readonly mode. (can't altered by any external api in db) 4 | */ 5 | public static READ = "READ"; 6 | } -------------------------------------------------------------------------------- /core/enums/optimisticlock-type.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * Enum of DecoratorType, i.e. where decorator is defined. 3 | * @enum 4 | */ 5 | export class OptimisticLockType { 6 | public static VERSION = "VERSION" 7 | } -------------------------------------------------------------------------------- /core/enums/repo-actions-enum.ts: -------------------------------------------------------------------------------- 1 | export class RepoActions { 2 | public static bulkPost = 'bulkPost'; 3 | public static bulkPut = 'bulkPut'; 4 | public static bulkDel = 'bulkDel'; 5 | 6 | public static findOne = 'findOne'; 7 | public static findMany = 'findMany'; 8 | public static findAll = 'findAll'; 9 | public static findWhere = 'findWhere'; 10 | public static findByField = 'findByField'; 11 | public static findChild = 'findChild'; 12 | 13 | public static put = 'put'; 14 | public static post = 'post'; 15 | public static delete = 'delete'; 16 | public static patch = 'patch'; 17 | } 18 | -------------------------------------------------------------------------------- /core/enums/storage-type-enum.ts: -------------------------------------------------------------------------------- 1 | export class StorageType{ 2 | public static JSONMAP = "jsonmap"; 3 | } -------------------------------------------------------------------------------- /core/exports/index.ts: -------------------------------------------------------------------------------- 1 | export {repositoryMap} from './repositories'; 2 | export {router} from './router'; 3 | -------------------------------------------------------------------------------- /core/exports/repositories.ts: -------------------------------------------------------------------------------- 1 | import {IDynamicRepository, DynamicRepository} from '../dynamic/dynamic-repository'; 2 | 3 | var _repositoryMap: { [key: string]: { fn: Object, repo: IDynamicRepository } } = {}; 4 | 5 | export function repositoryMap(repositoryMap?: any): { [key: string]: { fn: Object, repo: IDynamicRepository } } { 6 | if (repositoryMap !== undefined) { 7 | _repositoryMap = repositoryMap; 8 | } 9 | return _repositoryMap; 10 | } -------------------------------------------------------------------------------- /core/exports/router.ts: -------------------------------------------------------------------------------- 1 | var express = require('express'); 2 | export var router = express.Router(); -------------------------------------------------------------------------------- /core/exports/schemas.ts: -------------------------------------------------------------------------------- 1 |  2 | export var mongooseSchemaMap: { [key: string]: { schema: any, name: string, fn: any } } = {}; -------------------------------------------------------------------------------- /core/initialize/initialize-controllers.ts: -------------------------------------------------------------------------------- 1 | import {DynamicController} from '../dynamic/dynamic-controller'; 2 | import {AuthController} from '../../security/auth/authcontroller'; 3 | import {MetadataController} from '../api/metadataController'; 4 | import {repositoryMap} from "../exports/repositories"; 5 | import {MetaData} from '../metadata/metadata'; 6 | import {ExportTypes} from '../constants/decorators'; 7 | 8 | export class InitializeControllers { 9 | constructor() { 10 | this.initializeController(); 11 | } 12 | 13 | private initializeController() { 14 | 15 | for (var path in repositoryMap()) { 16 | let repo = repositoryMap()[path].repo; 17 | let meta: MetaData = repo.getMetaData(); 18 | if (meta && ((meta.params.exportType & ExportTypes.REST) == ExportTypes.REST)) { 19 | var controller = new DynamicController(repositoryMap()[path].fn, repo); 20 | } 21 | } 22 | var authController = new AuthController("/"); 23 | var metadataController = new MetadataController(); 24 | } 25 | } -------------------------------------------------------------------------------- /core/initialize/initialize.ts: -------------------------------------------------------------------------------- 1 |  2 | import {InitializeRepositories} from "./initialize-repositories"; 3 | import {InitializeScokets} from "./initialize-sockets"; 4 | import {InitializeMessengers} from "./initialize-messengers"; 5 | import {InitializeControllers} from "./initialize-controllers"; 6 | import {ParamTypeCustom} from '../metadata/param-type-custom'; 7 | import {router} from '../exports'; 8 | import path = require('path'); 9 | import * as Enumerable from 'linq'; 10 | import Q = require('q'); 11 | import {MetaUtils} from "../metadata/utils"; 12 | import * as Utils from "../utils"; 13 | import {CrudEntity} from "../dynamic/crud.entity"; 14 | 15 | export class Initalize { 16 | constructor(files: Array, server?: any) { 17 | new InitializeRepositories(); 18 | if (server) { 19 | new InitializeMessengers(); 20 | new InitializeScokets(server); 21 | } 22 | new InitializeControllers(); 23 | 24 | this.configureBase(); 25 | ['bulkPost', 'bulkPut', 'bulkPatch', 'bulkDel'].forEach(x => { 26 | Object.defineProperty(Array.prototype, x, { 27 | enumerable: false, 28 | writable: false, 29 | value: this.getExtendedArrayMethod(x) 30 | }); 31 | }); 32 | } 33 | 34 | getExtendedArrayMethod(action: string): () => Q.Promise { 35 | return (function () { 36 | let curArr = this; 37 | if (!curArr[0]) { 38 | return Q.when([]); 39 | } 40 | let repo = ((curArr[0])).getRepo(); 41 | if (!repo) { 42 | return Q.reject("repository not found"); 43 | } 44 | return repo[action]([].concat(curArr)); 45 | }); 46 | } 47 | 48 | configureBase() { 49 | var path = Utils.config().Config.basePath.indexOf('/') === 0 ? Utils.config().Config.basePath : '/' + Utils.config().Config.basePath; 50 | router.get(path, 51 | (req, res) => { 52 | //fetch all resources name (not the model name) in an array 53 | var allresourcesNames: Array = Utils.getAllResourceNames(); 54 | var allresourceJson = []; 55 | var fullbaseUrl: string = ""; 56 | fullbaseUrl = this.getProtocol(req) + '://' + req.get('host') + req.originalUrl; 57 | allresourcesNames.forEach(resource => { 58 | var resoucejson = {}; 59 | resoucejson[resource] = fullbaseUrl + (resource[0] === '/' ? resource : '/' + resource);//+ tokenUrl; 60 | allresourceJson.push(resoucejson); 61 | }); 62 | //loop through rsources and push in json array with name as key and url as value 63 | res.set("Content-Type", "application/json"); 64 | 65 | res.send(JSON.stringify(allresourceJson, null, 4)); 66 | } 67 | ) 68 | } 69 | 70 | 71 | 72 | private getProtocol(req) : string{ 73 | if(req.headers && req.headers["x-arr-ssl"]){ 74 | return "https"; 75 | } 76 | else{ 77 | return req.protocol; 78 | } 79 | } 80 | 81 | } -------------------------------------------------------------------------------- /core/interfaces/entity-service.ts: -------------------------------------------------------------------------------- 1 | import Q = require('q'); 2 | import {QueryOptions} from '../interfaces/queryOptions'; 3 | 4 | export interface IEntityService { 5 | startTransaction(param?:any):Q.Promise; 6 | commitTransaction(param?:any):Q.Promise; 7 | rollbackTransaction(param?:any):Q.Promise; 8 | findAll(model: any): Q.Promise; 9 | findWhere(model: any, query, selectedFields?: Array, queryOptions?: QueryOptions, toLoadChilds?: boolean): Q.Promise; 10 | countWhere(model: any, query): Q.Promise; 11 | distinctWhere(model: any, query): Q.Promise; 12 | findOne(model: any, id, donotLoadChilds?: boolean); 13 | findByField(model: any, fieldName, value): Q.Promise; 14 | findMany(model: any, ids: Array,toLoadEmbeddedChilds?:boolean); 15 | findChild(model: any, id, prop); 16 | bulkPost(model: any, objArr: Array, batchSize?: number): Q.Promise; 17 | bulkPut(model: any, objArr: Array, batchSize?: number, donotLoadChilds?: boolean): Q.Promise; 18 | bulkPatch(model: any, objArr: Array): Q.Promise; 19 | bulkPutMany(model: any, objIds: Array, obj: any): Q.Promise; 20 | bulkDel(model: any, objArr: Array): Q.Promise; 21 | post(model: any, obj: any): Q.Promise; 22 | put(model: any, id: any, obj: any): Q.Promise; 23 | del(model: any, id: any): Q.Promise; 24 | patch(model: any, id: any, obj): Q.Promise; 25 | getModel(repoPath: string, dynamicName?: string); 26 | } -------------------------------------------------------------------------------- /core/interfaces/queryOptions.ts: -------------------------------------------------------------------------------- 1 | import * as Enumerable from 'linq'; 2 | import { MetaUtils } from "../../core/metadata/utils"; 3 | import { MetaData } from '../../core/metadata/metadata'; 4 | import { Decorators } from '../../core/constants/decorators'; 5 | export interface QueryOptions { 6 | rows?: number; 7 | start?: number; 8 | from?: Date; 9 | until?: Date; 10 | order?: "asc" | "desc"; 11 | fields?: any; 12 | skip?: number; 13 | limit?: number; 14 | sort?: any; 15 | lt?: any; 16 | gt?: any; 17 | lt_value?: any; 18 | gt_value?: any; 19 | lte?: any; 20 | gte?: any; 21 | lte_value?: any; 22 | gte_value?: any; 23 | } 24 | 25 | export var getQueryOptionsFromQuery = (repository: any, query: { queryObj: any, options: any }) => { 26 | let primaryKey; 27 | var metaDataMap = MetaUtils.getMetaData(repository.entity.model, Decorators.COLUMN); 28 | for (var field in metaDataMap) { 29 | var fieldMetadata: MetaData = metaDataMap[field]; 30 | if (fieldMetadata.params.primaryKey) { 31 | primaryKey = fieldMetadata.params.name; 32 | } 33 | } 34 | 35 | var queryObj = query; 36 | var options = {}; 37 | Enumerable.from(queryObj).forEach((x: any) => { 38 | if (filterProps.indexOf(x.key) >= 0) { 39 | options[x.key] = x.value; 40 | delete queryObj[x.key]; 41 | } 42 | else 43 | if (primaryKey && x.key == primaryKey && x.key) { 44 | let valStr = queryObj[x.key]; //Incoming Comma Separated String Values 45 | let valArray; 46 | if (valStr == "" || valStr == null || valStr == "null" || valStr == '""' || valStr == "''" || valStr == undefined || valStr == "undefined") { 47 | valArray = []; 48 | } 49 | else { 50 | valArray = valStr.split(","); //Convert Comma Separated Values to Array 51 | } 52 | queryObj[x.key] = { $in: valArray }; 53 | } 54 | else { 55 | var val = queryObj[x.key]; 56 | var i = val.indexOf('%LIKE%'); 57 | if (i == 0) { 58 | // contains 59 | val = val.replace('%LIKE%', ''); 60 | queryObj[x.key] = { 61 | $regex: '.*' + val + '.*' 62 | } 63 | } 64 | else { 65 | i = val.indexOf('%START%'); 66 | if (i == 0) { 67 | // starts with 68 | val = val.replace('%START%', ''); 69 | queryObj[x.key] = { 70 | $regex: '^' + val + '.*' 71 | } 72 | } 73 | } 74 | } 75 | }); 76 | return { queryObj: queryObj, options: options } 77 | } 78 | 79 | export var filterProps: Array = ['rows', 'start', 'from', 'until', 'order', 'fields', 'skip', 'limit', 'sort', 'lt', 'gt', 'lte', 'gte', 'lt_value', 'gt_value', 'lte_value', 'gte_value']; 80 | -------------------------------------------------------------------------------- /core/interfaces/schema-generator.ts: -------------------------------------------------------------------------------- 1 | export interface ISchemaGenerator { 2 | getSchema(); 3 | } -------------------------------------------------------------------------------- /core/interfaces/shard-Info.ts: -------------------------------------------------------------------------------- 1 | export interface ShardInfo { 2 | getShardKey(); 3 | getUniqueId(); 4 | getCollectionNameFromSelf(); 5 | getCollectionNameFromShardKey(id: string); 6 | getAllShardCollectionNames(): Array; // This will be used for broadcasting queries in all the shards 7 | } -------------------------------------------------------------------------------- /core/metadata/actionUtils.ts: -------------------------------------------------------------------------------- 1 | import * as Enumerable from 'linq'; 2 | 3 | export interface IActionPropertyMap { 4 | key: string; 5 | args: Array 6 | } 7 | 8 | export function GetAllActionFromPrototype(targetProtoType: any): Array { 9 | var properties: string[] = Object.getOwnPropertyNames(targetProtoType); 10 | var action = "do"; 11 | var queryRegEx = new RegExp("^" + action, "i"); 12 | 13 | var searchProperties: Array = Enumerable.from(properties).where(p => { 14 | return queryRegEx.test(p); 15 | }).toArray(); 16 | 17 | var namePropMap: Array = []; 18 | var descs = []; 19 | Enumerable.from(searchProperties).forEach(x => { 20 | var desc = Object.getOwnPropertyDescriptor(targetProtoType, x); 21 | var arg = argumentNames(desc.value); 22 | namePropMap.push({ key: x, args: arg }); 23 | }); 24 | return namePropMap; 25 | } 26 | 27 | function argumentNames(fun) { 28 | var names = fun.toString().match(/^[\s\(]*[^(]*\(([^)]*)\)/)[1] 29 | .replace(/\/\/.*?[\r\n]|\/\*(?:.|[\r\n])*?\*\//g, '') 30 | .replace(/\s+/g, '').split(','); 31 | return names.length == 1 && !names[0] ? [] : names; 32 | } 33 | -------------------------------------------------------------------------------- /core/metadata/interfaces/decorator-metadata.ts: -------------------------------------------------------------------------------- 1 | import {MetaData} from '../metadata'; 2 | 3 | /** {decorator: { 4 | "field": { 5 | "_id": { 6 | 7 | }, 8 | "name":{ 9 | 10 | } 11 | }, 12 | "onetomany": {} 13 | } 14 | }**/ 15 | export type DecoratorMetaData = { [key: string]: { [key: string]: MetaData } }; -------------------------------------------------------------------------------- /core/metadata/interfaces/field-metadata.ts: -------------------------------------------------------------------------------- 1 | import {MetaData} from '../metadata'; 2 | 3 | export interface FieldMetaData { 4 | fields: { [key: string]: MetaData }; 5 | } -------------------------------------------------------------------------------- /core/metadata/interfaces/metaroot.ts: -------------------------------------------------------------------------------- 1 | import {DecoratorMetaData} from './decorator-metadata'; 2 | 3 | 4 | // {"models": { 5 | // "UserModel": {}, 6 | // "TeacherModel": {} 7 | // } 8 | export type MetaRoot = Map; 9 | -------------------------------------------------------------------------------- /core/metadata/metadata.ts: -------------------------------------------------------------------------------- 1 | import {DecoratorType} from '../enums/decorator-type'; 2 | import {ParamTypeCustom} from './param-type-custom'; 3 | import {ReflectConstants} from '../constants'; 4 | import * as ReflectUtils from '../reflect/reflect-utils'; 5 | 6 | export interface IMetaOptions { 7 | decorator: string; 8 | decoratorType: DecoratorType; 9 | modelType?: DecoratorType; 10 | params?: any; 11 | propertyKey?: string; 12 | paramIndex?: number; 13 | paramTypes?: Array; 14 | type?: ParamTypeCustom; 15 | returnType?: ParamTypeCustom; 16 | } 17 | 18 | /** 19 | * Creates new metadata object. 20 | * @class 21 | */ 22 | export class MetaData { 23 | /** Function prototype where decorator is declared. 24 | * @member {Object} 25 | */ 26 | target: Object = null; 27 | /** 28 | * The decorator is declared on static method/property. 29 | * @member {Boolean} 30 | */ 31 | isStatic: boolean; 32 | /** 33 | * The name of the method/property/paramter. 34 | * @member {string} 35 | */ 36 | propertyKey: string; 37 | decorator: string; 38 | propertyType: ParamTypeCustom; 39 | returnType: ParamTypeCustom; 40 | paramTypes: Array 41 | params: any; 42 | decoratorType: DecoratorType; 43 | modelType: DecoratorType; 44 | paramIndex: number; 45 | 46 | constructor(target: Object, isStatic: boolean, metaOptions: IMetaOptions) { 47 | this.target = target; 48 | this.isStatic = isStatic; 49 | this.propertyKey = metaOptions.propertyKey; 50 | this.paramIndex = metaOptions.paramIndex; 51 | this.decorator = metaOptions.decorator; 52 | this.decoratorType = metaOptions.decoratorType; 53 | this.modelType = metaOptions.modelType; 54 | this.params = metaOptions.params; 55 | this.propertyType = metaOptions.type || ReflectUtils.getDesignType(target, metaOptions.propertyKey); 56 | this.returnType = metaOptions.returnType || ReflectUtils.getReturnType(target, metaOptions.propertyKey); 57 | this.paramTypes = metaOptions.paramTypes || ReflectUtils.getParamTypes(target, metaOptions.propertyKey); 58 | } 59 | 60 | getType(): any { 61 | if (this.params && this.params.itemType) { 62 | return this.params.itemType; 63 | } 64 | else { 65 | return this.propertyType; 66 | } 67 | } 68 | } 69 | -------------------------------------------------------------------------------- /core/metadata/param-type-custom.ts: -------------------------------------------------------------------------------- 1 |  2 | export class ParamTypeCustom { 3 | itemType: any; 4 | isArray: boolean; 5 | constructor(itemType: any, isArray: boolean) { 6 | this.itemType = itemType; 7 | this.isArray = isArray; 8 | } 9 | } -------------------------------------------------------------------------------- /core/metadata/searchUtils.ts: -------------------------------------------------------------------------------- 1 | import * as Enumerable from 'linq'; 2 | 3 | export interface ISearchPropertyMap { 4 | key: string; 5 | args: Array 6 | } 7 | 8 | export function GetAllFindBySearchFromPrototype(targetProtoType: any): Array { 9 | // Check if the model has any fields 10 | // if( 11 | // targetProtoType.model 12 | // && targetProtoType.model.prototype 13 | // && targetProtoType.model.prototype.decorators 14 | // && targetProtoType.model.prototype.decorators.field ){ 15 | // console.log("There are fields"); 16 | // } 17 | // else{ 18 | // return; 19 | // } 20 | // get all model fields 21 | var properties: string[] = Object.getOwnPropertyNames(targetProtoType); 22 | // Get all the properties starting with findBy 23 | var findBy = "findBy"; 24 | var queryRegEx = new RegExp("^" + findBy, "i"); 25 | var searchProperties: Array = Enumerable.from(properties).where(p=> { 26 | return queryRegEx.test(p); 27 | }).toArray(); 28 | 29 | // Do all this exercise only if there is anything to search over. 30 | // if(searchProperties.length === 0 ){ 31 | // return; 32 | // } 33 | 34 | // var fieldProperties = Object.getOwnPropertyNames(targetProtoType.model.prototype.decorators.field); 35 | // var fieldPropIter = Enumerable.from(fieldProperties); 36 | // searchProperties.every(p=>{ 37 | // return fieldPropIter.contains(p); 38 | // }); 39 | 40 | var namePropMap: Array = []; 41 | 42 | Enumerable.from(searchProperties).forEach(p=> { 43 | var trimmed: string = p.substr(findBy.length, p.length); 44 | var splits = Enumerable.from(trimmed.split("And")).select(s => { 45 | return s.toLowerCase(); 46 | }).toArray(); 47 | namePropMap.push({ key: p, args: splits }); 48 | }); 49 | return namePropMap; 50 | } 51 | -------------------------------------------------------------------------------- /core/reflect/reflect-utils.ts: -------------------------------------------------------------------------------- 1 | import {ReflectConstants} from '../constants'; 2 | 3 | declare namespace Reflect { 4 | function getMetadata(metadataKey: any, target: Object, targetKey: string | symbol): any; 5 | } 6 | 7 | export function getDesignType (target, targetKey) { 8 | return getReflectMetadata(ReflectConstants.DESIGNTYPE, target, targetKey); 9 | } 10 | 11 | export function getParamTypes(target, targetKey) { 12 | return getReflectMetadata(ReflectConstants.DESIGNPARAMTYPES, target, targetKey); 13 | } 14 | 15 | export function getReturnType(target, targetKey) { 16 | return getReflectMetadata(ReflectConstants.DESIGNRETURNTYPE, target, targetKey); 17 | } 18 | 19 | function getReflectMetadata(reflectType: string, target: Object | Function, targetKey) { 20 | return Reflect.getMetadata(reflectType, target, targetKey); 21 | } -------------------------------------------------------------------------------- /core/services/instance-service.ts: -------------------------------------------------------------------------------- 1 | import {getEntity} from '../dynamic/model-entity'; 2 | import * as utils from "../utils"; 3 | import {MetaData} from '../metadata/metadata'; 4 | import {IAssociationParams} from '../decorators/interfaces'; 5 | import * as Enumerable from 'linq'; 6 | 7 | export class InstanceService { 8 | 9 | static getInstance(entity: any, id: any, param: any) { 10 | if (id) { 11 | var meta = utils.getPrimaryKeyMetadata(entity); 12 | if (meta) { 13 | param[meta.propertyKey] = id; 14 | } 15 | } 16 | //InstanceService.initProperties(entity, true, param); 17 | return InstanceService.getInstanceFromType(entity, true, param); 18 | } 19 | 20 | static getObjectFromJson(entity: any, param?: any) { 21 | //InstanceService.initProperties(entity, true, param); 22 | return InstanceService.getInstanceFromType(entity, true, param); 23 | } 24 | 25 | public static getInstanceFromType(type: any, isNew: boolean, param?: any) { 26 | var t: (param) => void = type.constructor; 27 | return InstanceService.createObjectInstance(t, isNew, param); 28 | } 29 | 30 | private static createObjectInstance(t: any, isNew: boolean, param?: any) { 31 | if (isNew) { 32 | return InstanceService.getNewInstance(t, param); 33 | } 34 | else { 35 | return InstanceService.getExistingInstance(t, param); 36 | } 37 | } 38 | 39 | private static getNewInstance(t: any, param?: any) { 40 | // This invokes constructor of the object 41 | var newInstance = new t(param); 42 | if (param) { 43 | for (var prop in param) { 44 | newInstance[prop] = param[prop]; 45 | } 46 | } 47 | return newInstance; 48 | } 49 | 50 | private static getExistingInstance(t: any, param?: any) { 51 | // No constructir is invoked 52 | var existingInstance = Object.create(t.prototype); 53 | if (param) { 54 | for (var prop in param) { 55 | existingInstance[prop] = param[prop]; 56 | } 57 | } 58 | return existingInstance; 59 | } 60 | 61 | private static initProperties(type: any, isNew: boolean, param: any) { 62 | var metas = utils.getAllRelationsForTargetInternal(type); 63 | if (metas) { 64 | metas.forEach(x => { 65 | let meta = x; 66 | let p = meta.params; 67 | if (param[meta.propertyKey]) { 68 | var value = param[meta.propertyKey]; 69 | if (value) { 70 | if (meta.propertyType.isArray) { 71 | if (value.length > 0 && utils.isJSON(value[0])) { 72 | var res = []; 73 | Enumerable.from(value).forEach(x => { 74 | InstanceService.initProperties(p.itemType, isNew, x); 75 | res.push(InstanceService.createObjectInstance(p.itemType, isNew, x)); 76 | }); 77 | param[meta.propertyKey] = res; 78 | } 79 | } 80 | else { 81 | if (utils.isJSON(value)) { 82 | InstanceService.initProperties(p.itemType, isNew, value); 83 | param[meta.propertyKey] = InstanceService.createObjectInstance(p.itemType, isNew, value); 84 | } 85 | } 86 | } 87 | } 88 | }); 89 | } 90 | } 91 | } 92 | -------------------------------------------------------------------------------- /core/services/post-filter-service.ts: -------------------------------------------------------------------------------- 1 | import {MetaUtils} from "../metadata/utils"; 2 | import * as Utils from "../utils"; 3 | import {IPostfilterParams} from '../decorators/interfaces'; 4 | import {Decorators} from '../constants/decorators'; 5 | import {winstonLog} from '../../logging/winstonLog'; 6 | import * as Enumerable from 'linq'; 7 | var Q = require('q'); 8 | var serviceCollection = {}; 9 | 10 | export class PostFilterService { 11 | 12 | 13 | 14 | static postFilter(result, preAuthParam: IPostfilterParams): Q.Promise { 15 | var service; 16 | if (serviceCollection[preAuthParam.serviceName]) { 17 | service = serviceCollection[preAuthParam.serviceName]; 18 | } 19 | else { 20 | var services = MetaUtils.getMetaDataForDecorators([Decorators.SERVICE]); 21 | service = Enumerable.from(services).where(x => x.metadata[0].params.serviceName == preAuthParam.serviceName).select(x => x.metadata[0]).firstOrDefault(); 22 | 23 | } 24 | if(service) { 25 | serviceCollection[preAuthParam.serviceName] = service; 26 | var param = []; 27 | param.push(result); 28 | let ret = service.target[preAuthParam.methodName].call(service.target, ...param); 29 | if (Utils.isPromise(ret)) { 30 | //console.timeEnd("postFilter_" + preAuthParam.serviceName); 31 | return ret.then(result => { 32 | return result; 33 | }).catch((err) => { 34 | winstonLog.logError('[PostFilterService: postFilter]: error ' + err); 35 | throw err; 36 | }); 37 | } 38 | else { 39 | //console.timeEnd("postFilter_" + preAuthParam.serviceName); 40 | return Q.when(ret); 41 | } 42 | } 43 | return Q.when(true); 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /core/services/pre-auth-service.ts: -------------------------------------------------------------------------------- 1 | import {MetaUtils} from "../metadata/utils"; 2 | import * as Utils from "../utils"; 3 | import {IPreauthorizeParams} from '../decorators/interfaces'; 4 | import {Decorators} from '../constants/decorators'; 5 | import {winstonLog} from '../../logging/winstonLog'; 6 | import * as Enumerable from 'linq'; 7 | var Q = require('q'); 8 | 9 | export class PreAuthService { 10 | 11 | static isPreAuthenticated(params, preAuthParam: IPreauthorizeParams, key): Q.Promise { 12 | var services = MetaUtils.getMetaDataForDecorators([Decorators.SERVICE]); 13 | var service = Enumerable.from(services).where(x => x.metadata[0].params.serviceName == preAuthParam.serviceName).select(x => x.metadata[0]).firstOrDefault(); 14 | if (service) { 15 | //var param = []; 16 | //param.push(content); 17 | //if (preAuthParam.params.entity == '#entity') { 18 | // param.push(content); 19 | //} 20 | //if (preAuthParam.params.other) { 21 | // for (var i in preAuthParam.params.other) { 22 | // param.push(preAuthParam.params.other[i]); 23 | // } 24 | //} 25 | var ret = service.target[preAuthParam.methodName].apply(service.target, params); 26 | if (Utils.isPromise(ret)) { 27 | return ret.then(isAllowed => { 28 | return isAllowed; 29 | }).catch((err) => { 30 | winstonLog.logError('[PreAuthService: isPreAuthenticated]: error ' + err); 31 | throw err; 32 | }); 33 | } 34 | else { 35 | return Q.when(ret); 36 | } 37 | } 38 | return Q.when(true); 39 | } 40 | } -------------------------------------------------------------------------------- /core/services/workerProcessService.ts: -------------------------------------------------------------------------------- 1 |  2 | export interface IWorkerProcessService { 3 | addWorker(worker: any); 4 | 5 | createWorker(worker: any); 6 | 7 | updateWorker(worker: any); 8 | 9 | deleteWorker(worker: any); 10 | 11 | getSingleRandomWoker(sessionId: any, role: any): any; 12 | 13 | getActiveWorkerCountForSessionAndRole(sessionId: any, role: any): number; 14 | } -------------------------------------------------------------------------------- /core/utils/classtype.ts: -------------------------------------------------------------------------------- 1 | export interface ClassType { 2 | new (...args: Array): T; 3 | } 4 | -------------------------------------------------------------------------------- /core/utils/nodemodule-type.ts: -------------------------------------------------------------------------------- 1 | export interface NodeModuleType { 2 | __esModule: boolean; 3 | default?: T 4 | } 5 | -------------------------------------------------------------------------------- /core/utils/serial.ts: -------------------------------------------------------------------------------- 1 | import * as Enumerable from 'linq'; 2 | import Q = require('q'); 3 | export class SerialTask { 4 | public static serial(tasks: Array, dataSheets?: Array) { 5 | var results = []; 6 | var chain = Q.when(); 7 | tasks.forEach(function (task, key) { 8 | 9 | //var successTask = task.success || task; 10 | //var failTask = task.fail; 11 | //var notifyTask = task.notify; 12 | 13 | chain = chain.then(/*success*/ 14 | function () { 15 | //results.push(data); 16 | //if (data && dataSheets) { 17 | // dataSheets.push(data); 18 | //} 19 | //if (!successTask) { 20 | // return data; 21 | //} 22 | var ret = task([]); 23 | if (ret['then']) { 24 | ret.then(res => { 25 | results[key] = res; 26 | }); 27 | } 28 | else { 29 | results[key] = ret; 30 | } 31 | return ret; 32 | },/*failure*/ 33 | function (reason) { 34 | results[key] = reason; 35 | return reason; 36 | //if (!failTask) { return Q.reject(reason); } 37 | //// User defined fail callback 38 | //var ret = failTask([reason]); 39 | //results[key] = ret; 40 | //return ret; 41 | }); 42 | }); 43 | return chain.then(r => { 44 | return results; 45 | }); 46 | } 47 | 48 | public static getTask(scope: any, fn: any, args?: Array) { 49 | var func = function (closureFnArgs: Array) { 50 | return fn.apply(scope, args); 51 | } 52 | return func; 53 | } 54 | } -------------------------------------------------------------------------------- /core/utils/types.ts: -------------------------------------------------------------------------------- 1 | export {NodeModuleType} from './nodemodule-type'; 2 | export {ClassType} from './classtype'; -------------------------------------------------------------------------------- /custom.d.ts: -------------------------------------------------------------------------------- 1 | interface Array { 2 | bulkPost(): Q.Promise; 3 | bulkPut(): Q.Promise; 4 | bulkPatch():Q.Promise; 5 | bulkDel(): Q.Promise; 6 | } -------------------------------------------------------------------------------- /decorators/interfaces/authorization-params.ts: -------------------------------------------------------------------------------- 1 | export interface IAuthorizeParams { 2 | roles: Array 3 | } -------------------------------------------------------------------------------- /decorators/metadata/searchUtils.spec.ts: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ratneshsinghparihar/Node-Data/0f4beb2384678e1b973d55c01d7dbce68ec96602/decorators/metadata/searchUtils.spec.ts -------------------------------------------------------------------------------- /di/decorators/index.ts: -------------------------------------------------------------------------------- 1 | export {service} from './service'; 2 | export {inject} from './inject'; 3 | -------------------------------------------------------------------------------- /di/decorators/interfaces/inject-params.ts: -------------------------------------------------------------------------------- 1 | import {ClassType} from '../../../core/utils/classtype'; 2 | 3 | export interface IInjectParams { 4 | type: ClassType, 5 | } -------------------------------------------------------------------------------- /di/decorators/service.ts: -------------------------------------------------------------------------------- 1 | import {Container} from '../di'; 2 | import {MetaUtils} from '../../core/metadata/utils'; 3 | import {Decorators} from '../../core/constants'; 4 | import {DecoratorType} from '../../core/enums'; 5 | import {ClassType} from '../../core/utils/classtype'; 6 | 7 | export function service(params?: { singleton?: boolean, serviceName?: string }) { 8 | params = params || {}; 9 | params.singleton = true; 10 | 11 | return function (target: ClassType) { 12 | Container.addService(target, params); 13 | params['target'] = target; 14 | MetaUtils.addMetaData(target, { 15 | decorator: Decorators.SERVICE, 16 | decoratorType: DecoratorType.CLASS, 17 | params: params 18 | }); 19 | }; 20 | } 21 | -------------------------------------------------------------------------------- /di/index.ts: -------------------------------------------------------------------------------- 1 | import * as DI from './di' 2 | import {repositoryMap} from '../core/exports' 3 | import {ClassType} from '../core/utils/classtype'; 4 | 5 | let repoSource = function (target: ClassType) { 6 | let repo; 7 | if (!target) { 8 | return null; 9 | } 10 | Object.keys(repositoryMap()) 11 | .forEach(x => { 12 | //// TODO: Decide repository map will hold the prototype or the function 13 | var path; 14 | if (target.prototype) { 15 | path = target.prototype.path; 16 | } 17 | else if (target['default']) { 18 | path = target['default'].prototype.path; 19 | } 20 | if (path === x) { 21 | repo = repositoryMap()[x].repo; 22 | } 23 | //if (repositoryMap()[x].fn === target || repositoryMap()[x].fn === target.prototype|| (target.prototype && x === target.prototype.path)) { 24 | // repo = repositoryMap()[x].repo; 25 | //} 26 | }); 27 | return repo; 28 | } 29 | 30 | DI.Container.addSource(repoSource); 31 | 32 | export let Container: DI.IContainer = DI.Container; 33 | -------------------------------------------------------------------------------- /di/tests/cyclic-a.ts: -------------------------------------------------------------------------------- 1 | import {inject, service} from '../../di/decorators'; 2 | import {CyclicB} from './cyclic-b'; 3 | 4 | export class CyclicA { 5 | constructor(a: CyclicA) { 6 | } 7 | } -------------------------------------------------------------------------------- /di/tests/cyclic-b.ts: -------------------------------------------------------------------------------- 1 | import {inject, service} from '../../di/decorators'; 2 | import {CyclicA} from './cyclic-a'; 3 | 4 | export class CyclicB { 5 | constructor(a: CyclicA) { 6 | } 7 | } -------------------------------------------------------------------------------- /di/tests/service-a.ts: -------------------------------------------------------------------------------- 1 | import {inject, service} from '../../di/decorators'; 2 | 3 | export class ServiceA { 4 | 5 | } -------------------------------------------------------------------------------- /di/tests/service-b.ts: -------------------------------------------------------------------------------- 1 | import {inject, service} from '../../di/decorators'; 2 | import {ServiceA} from './service-a'; 3 | 4 | export class ServiceB { 5 | 6 | public serviceA: ServiceA; 7 | 8 | constructor(serviceA: ServiceA) { 9 | this.serviceA = serviceA; 10 | } 11 | } -------------------------------------------------------------------------------- /di/tests/service-c.ts: -------------------------------------------------------------------------------- 1 | import {inject, service} from '../../di/decorators'; 2 | import {ServiceA} from './service-a'; 3 | import {ServiceB} from './service-b'; 4 | 5 | export class ServiceC { 6 | 7 | public serviceA: ServiceA; 8 | public serviceB: ServiceB; 9 | 10 | constructor(serviceA: ServiceA, serviceB: ServiceB) { 11 | this.serviceA = serviceA; 12 | this.serviceB = serviceB; 13 | } 14 | } -------------------------------------------------------------------------------- /di/tests/service-d.ts: -------------------------------------------------------------------------------- 1 |  2 | import {inject, service} from '../../di/decorators'; 3 | import {ServiceA} from './service-a'; 4 | import {ServiceB} from './service-b'; 5 | import {ServiceC} from './service-c'; 6 | 7 | export class ServiceD { 8 | 9 | public serviceA: ServiceA; 10 | public serviceB: ServiceB; 11 | public serviceC: ServiceC; 12 | 13 | constructor(serviceA: ServiceA, serviceB: ServiceB, serviceC: ServiceC) { 14 | this.serviceA = serviceA; 15 | this.serviceB = serviceB; 16 | this.serviceC = serviceC; 17 | } 18 | } -------------------------------------------------------------------------------- /di/tests/service-e.ts: -------------------------------------------------------------------------------- 1 |  2 | import {inject, service} from '../../di/decorators'; 3 | import {ServiceA} from './service-a'; 4 | import {ServiceB} from './service-b'; 5 | 6 | export class ServiceE { 7 | 8 | public serviceA: ServiceA; 9 | public serviceB: ServiceB; 10 | 11 | constructor(serviceA: ServiceA, serviceB: ServiceB) { 12 | this.serviceA = serviceA; 13 | this.serviceB = serviceB; 14 | } 15 | } 16 | 17 | export default ServiceE; -------------------------------------------------------------------------------- /filePath: -------------------------------------------------------------------------------- 1 | Hello -------------------------------------------------------------------------------- /gulpfile.js: -------------------------------------------------------------------------------- 1 | var gulp = require("gulp"); 2 | var tsc = require("gulp-typescript"); 3 | var sourcemaps = require("gulp-sourcemaps"); 4 | var nodemon = require('gulp-nodemon'); 5 | var livereload = require('gulp-livereload'); 6 | var tslint = require('gulp-tslint'); 7 | var ignore = require('gulp-ignore'); 8 | var ciDevVersion = require('./scripts/ci-version-devbuild'); 9 | //var nodeDebug = require("gulp-node-debug"); 10 | 11 | var tsProject = tsc.createProject('tsconfig.json', { sortOutput: true }); 12 | 13 | gulp.task('compile-ts', function () { 14 | var errors = 0; 15 | var tsResult = tsProject.src()//gulp.src() 16 | .pipe(sourcemaps.init()) 17 | .pipe(tsc(tsProject)) 18 | .on("error", function() { 19 | errors++; 20 | }) 21 | .on("finish", function() { 22 | if (errors !== 0) { 23 | console.error("Typescript error(s) found. Build Failed"); 24 | process.exit(1); 25 | } 26 | }); 27 | 28 | tsResult.dts.pipe(gulp.dest("./")); 29 | return tsResult.js 30 | .pipe(sourcemaps.write('.')) 31 | .pipe(gulp.dest("./")); 32 | }); 33 | 34 | gulp.task('live-reload', function () { 35 | gulp.src(["**/*.js", "!node_modules/**/*.*"]) 36 | .pipe(livereload()); 37 | }); 38 | 39 | gulp.task("tslint", function () { 40 | return tsProject.src() 41 | .pipe(ignore.exclude('*.d.ts')) 42 | .pipe(tslint({ 43 | rulesDirectory: ['node_modules/tslint-microsoft-contrib'] 44 | })) 45 | .pipe(tslint.report("verbose")) 46 | }); 47 | 48 | gulp.task("nodemon", ["compile-ts"], function () { 49 | // listen for changes 50 | livereload.listen(); 51 | // configure nodemon 52 | nodemon({ 53 | // the script to run the app 54 | script: "server.js", 55 | ext: 'js' 56 | }).on('start', function () { 57 | // when the app has restarted, run livereload. 58 | gulp.src("server.js") 59 | .pipe(livereload()); 60 | }) 61 | }); 62 | 63 | gulp.task("watch", function () { 64 | gulp.watch("./**/*.ts", ["compile-ts", "live-reload"]); 65 | }) 66 | 67 | gulp.task("ci-dev", function () { 68 | ciDevVersion.setNewDevBuildVersion('package.json'); 69 | }); 70 | 71 | // Task 72 | gulp.task('default', ["nodemon", "watch"]); 73 | 74 | gulp.task('ts', ["compile-ts"]); 75 | -------------------------------------------------------------------------------- /images/atlassian.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ratneshsinghparihar/Node-Data/0f4beb2384678e1b973d55c01d7dbce68ec96602/images/atlassian.png -------------------------------------------------------------------------------- /images/browserstack-logo-600x315.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ratneshsinghparihar/Node-Data/0f4beb2384678e1b973d55c01d7dbce68ec96602/images/browserstack-logo-600x315.png -------------------------------------------------------------------------------- /images/compare_frameworkes2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ratneshsinghparihar/Node-Data/0f4beb2384678e1b973d55c01d7dbce68ec96602/images/compare_frameworkes2.png -------------------------------------------------------------------------------- /images/node-data-multiple-db-code.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ratneshsinghparihar/Node-Data/0f4beb2384678e1b973d55c01d7dbce68ec96602/images/node-data-multiple-db-code.png -------------------------------------------------------------------------------- /images/node-data-multiple-db.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ratneshsinghparihar/Node-Data/0f4beb2384678e1b973d55c01d7dbce68ec96602/images/node-data-multiple-db.png -------------------------------------------------------------------------------- /images/realsociable.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ratneshsinghparihar/Node-Data/0f4beb2384678e1b973d55c01d7dbce68ec96602/images/realsociable.png -------------------------------------------------------------------------------- /images/talentica.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ratneshsinghparihar/Node-Data/0f4beb2384678e1b973d55c01d7dbce68ec96602/images/talentica.png -------------------------------------------------------------------------------- /images/talentica_old.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ratneshsinghparihar/Node-Data/0f4beb2384678e1b973d55c01d7dbce68ec96602/images/talentica_old.png -------------------------------------------------------------------------------- /index.d.ts: -------------------------------------------------------------------------------- 1 | declare module nodedata { 2 | export interface Array { 3 | bulkPost(): Q.Promise; 4 | bulkPut(): Q.Promise; 5 | bulkPatch():Q.Promise; 6 | bulkDel(): Q.Promise; 7 | } 8 | } 9 | 10 | -------------------------------------------------------------------------------- /jsdocconf.json: -------------------------------------------------------------------------------- 1 | { 2 | "tags": { 3 | "allowUnknownTags": true, 4 | "dictionaries": [ "jsdoc", "closure" ] 5 | }, 6 | "source": { 7 | "include": ["decorators"], 8 | "exclude": [ "node_modules" ], 9 | "includePattern": ".+\\.js(doc)?$", 10 | "excludePattern": "(^|\\/|\\\\)_" 11 | }, 12 | "plugins": [ ], 13 | "templates": { 14 | "cleverLinks": false, 15 | "monospaceLinks": false 16 | }, 17 | "opts": { 18 | "encoding": "utf8", // same as -e utf8 19 | "destination": "./out/", // same as -d ./out/ 20 | "recurse": true // same as -r 21 | } 22 | } -------------------------------------------------------------------------------- /license: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) 2016 ratnesh 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | 23 | -------------------------------------------------------------------------------- /logging/index.ts: -------------------------------------------------------------------------------- 1 | import {winstonLog} from "./winstonLog"; 2 | 3 | export {winstonLog}; -------------------------------------------------------------------------------- /logging/winstonLog.ts: -------------------------------------------------------------------------------- 1 | import winston = require('winston'); 2 | 3 | function getLogger(): winston.LoggerInstance { 4 | return new (winston.Logger)({ 5 | transports: [ 6 | new (winston.transports.Console)() 7 | //,new (winston.transports.File)({ filename: 'nodedataLog.log', json: true}) 8 | ] 9 | }); 10 | } 11 | 12 | /** 13 | * A wrapper around the winston logging framework. 14 | */ 15 | class WinstonLog { 16 | winstonLogger = null; 17 | logStream = null; 18 | constructor() { 19 | this.winstonLogger = getLogger(); 20 | var _logger = this.winstonLogger; 21 | this.logStream = { 22 | write : function(message, encoding){ 23 | _logger.debug(message); 24 | } 25 | } 26 | } 27 | 28 | /** 29 | * Logs the message as info. 30 | * @param message The message to be logged. 31 | * @param meta Any additional metadata. 32 | */ 33 | logInfo(message: any, meta? : any) { 34 | this.winstonLogger.log('info', message, meta); 35 | } 36 | 37 | /** 38 | * Logs the message as Debug 39 | * @param message The message to be logged 40 | * @param meta Any additional metadata 41 | */ 42 | logDebug(message: any, meta? : any) { 43 | this.winstonLogger.log('debug', message, meta); 44 | } 45 | 46 | /** 47 | * Logs the message as Erro 48 | * @param message The message to be logged 49 | * @param meta Any additional metadata 50 | */ 51 | logError(message: any, meta? : any) { 52 | this.winstonLogger.log('error', message, meta); 53 | } 54 | 55 | configure(options:any){ 56 | this.winstonLogger.configure(options); 57 | } 58 | 59 | getStream(){ 60 | return this.logStream; 61 | } 62 | } 63 | 64 | var winstonLog = new WinstonLog(); 65 | export {winstonLog}; -------------------------------------------------------------------------------- /login.html: -------------------------------------------------------------------------------- 1 |
2 |
3 | 4 | 5 |
6 |
7 | 8 | 9 |
10 |
11 | 12 |
13 |
-------------------------------------------------------------------------------- /models/IWorkerProcess.ts: -------------------------------------------------------------------------------- 1 |  2 | import {field, document} from '../mongoose/decorators'; 3 | import {Strict} from '../mongoose/enums/'; 4 | import {onetomany, manytoone, manytomany, onetoone} from '../core/decorators'; 5 | 6 | 7 | export interface IWorkerProcess { 8 | 9 | 10 | machineID?: string; 11 | 12 | 13 | processId?: string; 14 | 15 | 16 | serverId?: string; 17 | 18 | 19 | workerId?: number; //possible VLAUES from 1 to N 20 | 21 | 22 | 23 | sessionId?: string; //possible VLAUES from 1 to N 24 | 25 | 26 | role?: string; //possible VLAUES from 1 to N 27 | 28 | status?: string; //active , idle , killed 29 | 30 | 31 | statistics?: { noOfTransactioSoFar: number, activeSince: Date, velocity: number } 32 | channels?: string[]; 33 | 34 | } 35 | 36 | 37 | 38 | -------------------------------------------------------------------------------- /models/baseModel.ts: -------------------------------------------------------------------------------- 1 | import {onetomany, manytoone, manytomany, transient} from '../core/decorators'; 2 | import {field, document} from '../mongoose/decorators'; 3 | import {Strict} from '../mongoose/enums'; 4 | 5 | export class BaseModel { 6 | @field({ primary: true, autogenerated: true }) 7 | _id: any; 8 | 9 | @field() 10 | name: any; 11 | 12 | /* 13 | nodedata internal use for caching, use for findWhere case 14 | */ 15 | @transient() 16 | __selectedFindWhere: boolean; 17 | 18 | /* 19 | nodedata internal use for caching, to marked as partial load for findMany (egar load case not load) 20 | */ 21 | @transient() 22 | __partialLoaded: boolean; 23 | 24 | /* 25 | nodedata internal use for caching, to marked as fully load 26 | */ 27 | @transient() 28 | __FullyLoaded: boolean; 29 | } 30 | 31 | export default BaseModel; -------------------------------------------------------------------------------- /models/baseSequelizeModel.ts: -------------------------------------------------------------------------------- 1 | import { column, entity } from '../sequelizeimp/decorators'; 2 | import * as Sequelize from "sequelize"; 3 | 4 | export class BaseSequelize { 5 | 6 | constructor(params?:any){ 7 | this.CreateDate = new Date(); 8 | } 9 | 10 | @column({name: "name", type:Sequelize.STRING, allowNull:true}) 11 | name: string; 12 | 13 | @column({ name: "CreateDate", type: Sequelize.DATE, allowNull: true }) 14 | CreateDate: Date; 15 | 16 | @column({ name: "CreatedBy", type: Sequelize.INTEGER, allowNull: true }) 17 | CreatedBy: number; 18 | 19 | @column({ name: "ModifyDate", type: Sequelize.DATE, allowNull: true }) 20 | ModifyDate: Date; 21 | 22 | @column({ name: "ModifiedBy", type: Sequelize.INTEGER, allowNull: true }) 23 | ModifiedBy: number; 24 | } 25 | 26 | export default BaseSequelize; -------------------------------------------------------------------------------- /models/blogPostSqlModel.ts: -------------------------------------------------------------------------------- 1 | import {onetomany, manytoone, manytomany} from '../core/decorators'; 2 | import {column, entity} from '../sequelizeimp/decorators'; 3 | import {Strict} from '../sequelizeimp/enums'; 4 | import * as Sequelize from "sequelize"; 5 | import {BlogSqlModel} from "./blogSqlModel" 6 | 7 | @entity({ name:'tbl_blog_post2', tableName: 'tbl_blog_post2',timestamps:false }) 8 | export class BlogPostSqlModel { 9 | @column({name:"id", type: Sequelize.INTEGER, autoIncrement:true, allowNull:false, primaryKey: true }) 10 | _id: number; 11 | 12 | @column({ name: "name", type: Sequelize.STRING(128), defaultValue:"defaultBlog" }) 13 | name: string; 14 | 15 | @manytoone({ rel: 'tbl_blog2', itemType: BlogSqlModel, embedded: false, persist: true, eagerLoading: true }) 16 | blog: BlogSqlModel; 17 | } 18 | 19 | export default BlogPostSqlModel; -------------------------------------------------------------------------------- /models/blogSqlModel.ts: -------------------------------------------------------------------------------- 1 | import {onetomany, manytoone, manytomany} from '../core/decorators'; 2 | import {column, entity} from '../sequelizeimp/decorators'; 3 | import {Strict} from '../sequelizeimp/enums'; 4 | import * as Sequelize from "sequelize"; 5 | import {BlogPostSqlModel} from "./blogPostSqlModel"; 6 | 7 | @entity({ name:'tbl_blog2', tableName: 'tbl_blog2', timestamps: false, freezeTableName: true }) 8 | export class BlogSqlModel { 9 | @column({ name:"id", type: Sequelize.INTEGER, allowNull:false, primaryKey: true }) 10 | _id: number; 11 | 12 | @column({ name: "name", type: Sequelize.STRING(128), allowNull: false }) 13 | name: string; 14 | 15 | @onetomany({ rel: 'tbl_blog_post2', itemType: BlogPostSqlModel, embedded: false, persist: true, eagerLoading: false }) 16 | blogPosts: Array; 17 | } 18 | 19 | export default BlogSqlModel; -------------------------------------------------------------------------------- /models/sequelizeSchool.ts: -------------------------------------------------------------------------------- 1 | import { column, entity } from '../sequelizeimp/decorators'; 2 | import * as Sequelize from "sequelize"; 3 | import {BaseSequelize} from './baseSequelizeModel'; 4 | import {SequelizeTeacher} from './sequelizeTeacher'; 5 | import {manytoone} from '../core/decorators'; 6 | 7 | @entity({ name: 'school', tableName: 'sequelize_school', timestamps: false, freezeTableName: true }) 8 | export class SequelizeSchool extends BaseSequelize { 9 | 10 | @column({ name: "Id", type: Sequelize.INTEGER, allowNull: false, primaryKey: true, autoIncrement: true }) 11 | Id: number; 12 | 13 | @column({ name: "name", type: Sequelize.STRING, allowNull: false }) 14 | name: string; 15 | 16 | // by default it will choose primary key of the table 17 | @manytoone({ rel: 'sequelize_teacher', itemType: SequelizeTeacher, eagerLoading: true, properties:['name'], foreignKey:'TeacherID'}) 18 | Teacher: SequelizeTeacher; 19 | 20 | // foreign key should not be assigned as a column 21 | @column({name: "TeacherID", type:Sequelize.INTEGER, allowNull:true}) 22 | TeacherID:number; 23 | } 24 | 25 | export default SequelizeTeacher; -------------------------------------------------------------------------------- /models/sequelizeStudent.ts: -------------------------------------------------------------------------------- 1 | import { column, entity } from '../sequelizeimp/decorators'; 2 | import * as Sequelize from "sequelize"; 3 | import {BaseSequelize} from './baseSequelizeModel'; 4 | 5 | @entity({ name: 'student', tableName: 'sequelize_student', timestamps: false, freezeTableName: true }) 6 | export class SequelizeStudent extends BaseSequelize { 7 | 8 | @column({ name: "Id", type: Sequelize.INTEGER, allowNull: false, primaryKey: true, autoIncrement: true }) 9 | Id: number; 10 | 11 | @column({ name: "name", type: Sequelize.STRING, allowNull: false }) 12 | name: string; 13 | } 14 | 15 | export default SequelizeStudent; -------------------------------------------------------------------------------- /models/sequelizeTeacher.ts: -------------------------------------------------------------------------------- 1 | import { column, entity } from '../sequelizeimp/decorators'; 2 | import * as Sequelize from "sequelize"; 3 | import {BaseSequelize} from './baseSequelizeModel'; 4 | import {SequelizeStudent} from './sequelizeStudent'; 5 | import {manytoone} from '../core/decorators'; 6 | 7 | @entity({ name: 'teacher', tableName: 'sequelize_teacher', timestamps: false, freezeTableName: true }) 8 | export class SequelizeTeacher extends BaseSequelize { 9 | 10 | @column({ name: "Id", type: Sequelize.INTEGER, allowNull: false, primaryKey: true, autoIncrement: true }) 11 | Id: number; 12 | 13 | @column({ name: "name", type: Sequelize.STRING, allowNull: false }) 14 | name: string; 15 | 16 | // by default it will choose primary key of the table 17 | @manytoone({ rel: 'sequelize_student', itemType: SequelizeStudent, eagerLoading: true,foreignKey:'StudentID' }) 18 | Student: SequelizeStudent; 19 | 20 | @column({name: "StudentID", type:Sequelize.INTEGER, allowNull:true}) 21 | StudentID:number; 22 | } 23 | 24 | export default SequelizeTeacher; -------------------------------------------------------------------------------- /models/session.ts: -------------------------------------------------------------------------------- 1 |  2 | import {field, document} from '../mongoose/decorators'; 3 | import {Strict} from '../mongoose/enums/'; 4 | import {onetomany, manytoone, manytomany, onetoone} from '../core/decorators'; 5 | 6 | //@document({ name: "session", strict: Strict.false }) 7 | export class Session { 8 | 9 | @field() 10 | sessionId: string; 11 | 12 | @field() 13 | userName: string; 14 | 15 | @field() 16 | role: string; 17 | 18 | @field() 19 | userId: number; 20 | 21 | 22 | reliableChannles: any;//format { "order": { "status":true,lastemit:date} } 23 | 24 | 25 | } 26 | 27 | export default Session; 28 | /* 29 | db.sessions.insert([{ 30 | "sessionId":"first1", 31 | "role":"ROLE_USER", 32 | "userName":"Ratnesh" 33 | }, 34 | { 35 | "sessionId":"session_for_ordermatcher", 36 | "role":"ROLE_ADMIN", 37 | "userName":"OrderMatcher" 38 | }, 39 | { 40 | "sessionId":"session_admin", 41 | "role":"ROLE_ADMIN", 42 | "userName":"session_admin" 43 | } 44 | ] 45 | ) 46 | 47 | */ -------------------------------------------------------------------------------- /models/storyModel.ts: -------------------------------------------------------------------------------- 1 | import {onetomany, manytoone, manytomany} from '../core/decorators'; 2 | import {field, document} from '../mongoose/decorators'; 3 | import {Strict} from '../mongoose/enums'; 4 | import {BaseModel} from './baseModel'; 5 | import {Types} from 'mongoose'; 6 | import {BlogSqlModel} from "./blogSqlModel" 7 | 8 | @document({ name: 'stories', strict: Strict.true }) 9 | export class StoryModel extends BaseModel { 10 | 11 | @field({ primary: true, autogenerated: true }) 12 | _id: Types.ObjectId; 13 | 14 | @field() 15 | name: String; 16 | 17 | @onetomany({ rel: 'tbl_blog2', itemType: BlogSqlModel, embedded: false, persist: true, eagerLoading: false }) 18 | blogs: Array; 19 | } 20 | 21 | export default StoryModel; -------------------------------------------------------------------------------- /mongoose/constants/decorators.ts: -------------------------------------------------------------------------------- 1 |  2 | export class Decorators { 3 | public static DOCUMENT = 'document'; 4 | public static FIELD = 'field'; 5 | public static TRANSIENT = 'transient'; 6 | } -------------------------------------------------------------------------------- /mongoose/constants/index.ts: -------------------------------------------------------------------------------- 1 | export {Decorators} from './decorators'; -------------------------------------------------------------------------------- /mongoose/datatype.ts: -------------------------------------------------------------------------------- 1 | import Mongoose = require('mongoose'); 2 | 3 | export import ObjectId = Mongoose.Types.ObjectId; 4 | export import Mixed = Mongoose.SchemaType; 5 | 6 | export var Types = { 7 | ObjectId: ObjectId, 8 | Mixed: Mixed 9 | } -------------------------------------------------------------------------------- /mongoose/db.ts: -------------------------------------------------------------------------------- 1 | import Mongoose = require("mongoose"); 2 | import * as CoreUtils from '../core/utils'; 3 | import {winstonLog} from '../logging/winstonLog'; 4 | import {PrincipalContext} from '../security/auth/principalContext'; 5 | import Q = require('q'); 6 | // use main connection for pooling source 7 | export var mainConnection: any = {}; 8 | var allConnections: any = {}; 9 | var connectionOptions; 10 | import EventEmitter = require('events'); 11 | var emitters: Array = new Array() 12 | 13 | export function connect() { 14 | let dbLoc = CoreUtils.config().Config.DbConnection; 15 | connectionOptions = CoreUtils.config().Config.DbConnectionOptions || {}; 16 | getConnection(dbLoc, connectionOptions); 17 | mainConnection = allConnections[dbLoc]; 18 | } 19 | 20 | export function getDbSpecifcModel(schemaName: any, schema: any): any { 21 | var database = PrincipalContext.get(CoreUtils.resources.userDatabase); 22 | if (database && allConnections[database]) { 23 | return allConnections[database].model(schemaName, schema); 24 | } 25 | else { 26 | return mainConnection.model(schemaName, schema); 27 | } 28 | } 29 | 30 | export function addEmitter(msg: EventEmitter.EventEmitter) { 31 | emitters.push(msg); 32 | } 33 | export function removeEmitter(msg: EventEmitter.EventEmitter) { 34 | emitters = emitters.filter((mem) => { return mem != msg }); 35 | } 36 | 37 | export function updateConnection(connectionString, connectionOption): Q.IPromise { 38 | PrincipalContext.save(CoreUtils.resources.userDatabase, connectionString); 39 | return getConnection(connectionString, connectionOption); 40 | } 41 | 42 | function getConnection(connectionString, connectionOption): Q.IPromise { 43 | if (!connectionString) 44 | return Q.when(false); 45 | 46 | if (!allConnections[connectionString]) { 47 | var conn = Mongoose.createConnection(connectionString, defaultDomainOptions(connectionOption)); 48 | allConnections[connectionString] = conn; 49 | return connectDataBase(conn, connectionString); 50 | } 51 | else { 52 | return Q.when(true); 53 | } 54 | } 55 | 56 | const emitMesseageToALL = (event, message) => { 57 | try { 58 | if (emitters && emitters.length) { 59 | emitters.forEach((emitter) => { 60 | emitter.emit(event, message); 61 | }) 62 | } 63 | } 64 | catch (ex) { } 65 | }; 66 | 67 | function connectDataBase(conn, connectionString): Q.IPromise { 68 | let defer = Q.defer(); 69 | conn.on('connecting', () => { 70 | winstonLog.logInfo(`trying to establish connection for ${connectionString}`); 71 | }); 72 | 73 | conn.on('connected', () => { 74 | winstonLog.logInfo(`connection established successfully ${connectionString}`); 75 | defer.resolve(true); 76 | emitMesseageToALL('databaseconnected', conn); 77 | }); 78 | 79 | conn.on('error', (err) => { 80 | winstonLog.logInfo(`connection to mongo failed for ${connectionString} with error ${err}`); 81 | defer.resolve(false); 82 | emitMesseageToALL('error', conn); 83 | }); 84 | 85 | conn.on('disconnected', () => { 86 | winstonLog.logInfo(`connection closed successfully ${connectionString}`); 87 | defer.resolve(false); 88 | emitMesseageToALL('disconnected', conn); 89 | }); 90 | return defer.promise; 91 | } 92 | 93 | function defaultDomainOptions(connectionOption: any) { 94 | 95 | 96 | if (!connectionOption) { 97 | connectionOption = {}; 98 | } 99 | if (!connectionOption['server']) { 100 | connectionOption['server'] = {}; 101 | } 102 | if (!connectionOption['replset']) { 103 | connectionOption['replset'] = {}; 104 | } 105 | connectionOption['server']['domainsEnabled'] = true; 106 | connectionOption['replset']['domainsEnabled'] = true; 107 | return connectionOption; 108 | } -------------------------------------------------------------------------------- /mongoose/decorators/document.ts: -------------------------------------------------------------------------------- 1 | import {MetaUtils} from "../../core/metadata/utils"; 2 | import {Decorators} from '../../core/constants'; 3 | import {DecoratorType} from '../../core/enums/decorator-type'; 4 | import {Strict} from '../enums/document-strict'; 5 | 6 | var _dcoumentDecoratorCache={}; 7 | export function document(params: { name: string, strict?: Strict, dynamicName?: boolean, pluralization?: boolean }) { 8 | 9 | params = params || {}; 10 | return function(target: Object){ 11 | 12 | console.log("Document: " + params.name); 13 | if(_dcoumentDecoratorCache[params.name]){return;} 14 | _dcoumentDecoratorCache[params.name]=params; 15 | 16 | // add metadata to prototype 17 | MetaUtils.addMetaData(((target).prototype || target), 18 | { 19 | decorator: Decorators.DOCUMENT, 20 | decoratorType: DecoratorType.CLASS, 21 | modelType: DecoratorType.MODEL, 22 | params: params 23 | }); 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /mongoose/decorators/entity.ts: -------------------------------------------------------------------------------- 1 | import {MetaUtils} from "../../core/metadata/utils"; 2 | import {Decorators} from '../../core/constants'; 3 | import {DecoratorType} from '../../core/enums/decorator-type'; 4 | import {Strict} from '../enums/document-strict'; 5 | 6 | export function entity(params: { name: string, strict?: Strict }) { 7 | params = params || {}; 8 | return function(target: Object){ 9 | // add metadata to prototype 10 | MetaUtils.addMetaData(((target).prototype || target), 11 | { 12 | decorator: Decorators.ENTITY, 13 | decoratorType: DecoratorType.CLASS, 14 | modelType: DecoratorType.MODEL, 15 | params: params 16 | }); 17 | } 18 | } -------------------------------------------------------------------------------- /mongoose/decorators/field.ts: -------------------------------------------------------------------------------- 1 | import {MetaUtils} from "../../core/metadata/utils"; 2 | import {DecoratorType} from '../../core/enums/decorator-type'; 3 | import {Decorators} from '../constants'; 4 | 5 | export function field(params?: {itemType?: any, primary?: boolean, autogenerated?: boolean, searchIndex?:boolean}) { 6 | return function (target: Object, propertyKey: string) { 7 | console.log('field - propertyKey: ', propertyKey, ', target:', target); 8 | MetaUtils.addMetaData(target, 9 | { 10 | decorator: Decorators.FIELD, 11 | decoratorType: DecoratorType.PROPERTY, 12 | params: params, 13 | propertyKey: propertyKey 14 | }); 15 | } 16 | } -------------------------------------------------------------------------------- /mongoose/decorators/index.ts: -------------------------------------------------------------------------------- 1 | export {field} from './field'; 2 | export {document} from './document'; 3 | export {transient} from '../../core/decorators/transient'; -------------------------------------------------------------------------------- /mongoose/decorators/interfaces/document-params.ts: -------------------------------------------------------------------------------- 1 | import {Strict} from '../../enums/document-strict'; 2 | import {IDecoratorParams} from '../../../core/decorators/interfaces/decorator-params'; 3 | 4 | export interface IDocumentParams extends IDecoratorParams { 5 | strict: Strict; 6 | /** 7 | * Set false if you want to use same name as the collection name 8 | * (means letter case conversion and pluralization 9 | * ) 10 | */ 11 | pluralization: boolean; 12 | } -------------------------------------------------------------------------------- /mongoose/decorators/interfaces/field-params.ts: -------------------------------------------------------------------------------- 1 | export interface IFieldParams { 2 | itemType?: any, 3 | primary?: boolean, 4 | autogenerated?: boolean, 5 | searchIndex? : boolean 6 | } -------------------------------------------------------------------------------- /mongoose/decorators/interfaces/index.ts: -------------------------------------------------------------------------------- 1 | export {IFieldParams} from './field-params'; 2 | export {IDocumentParams} from './document-params'; -------------------------------------------------------------------------------- /mongoose/enums/document-strict.ts: -------------------------------------------------------------------------------- 1 | export enum Strict { 2 | false, 3 | true, 4 | throw 5 | } -------------------------------------------------------------------------------- /mongoose/enums/index.ts: -------------------------------------------------------------------------------- 1 |  2 | export {Strict} from './document-strict'; -------------------------------------------------------------------------------- /mongoose/index.ts: -------------------------------------------------------------------------------- 1 |  2 | import {MongooseService} from './mongoose-service'; 3 | 4 | export var entityServiceInst = new MongooseService(); 5 | export {generateSchema} from './schema'; 6 | export {connect} from './db'; 7 | -------------------------------------------------------------------------------- /mongoose/mongooseSchemaGenerator.ts: -------------------------------------------------------------------------------- 1 | import Mongoose = require('mongoose'); 2 | import * as Utils from "../core/metadata/utils"; 3 | import {searchUtils} from "../search/elasticSearchUtils"; 4 | var MongooseSchema = Mongoose.Schema; 5 | 6 | 7 | export interface IMongooseSchemaOptions { 8 | options: Object, 9 | searchIndex: boolean; 10 | } 11 | 12 | class MongooseSchemaGenrator { 13 | createSchema(parsedSchema: any, mongooseOptions: IMongooseSchemaOptions): Object { 14 | var mongooseSchemaObj = new MongooseSchema(parsedSchema, mongooseOptions.options); 15 | if (mongooseOptions.searchIndex) { 16 | searchUtils.insertMongoosasticToSchema(mongooseSchemaObj); 17 | } 18 | return mongooseSchemaObj; 19 | } 20 | } 21 | 22 | export var schemaGenerator = new MongooseSchemaGenrator(); -------------------------------------------------------------------------------- /mongoose/pubsub/model.ts: -------------------------------------------------------------------------------- 1 | 2 | import * as CoreUtils from '../../core/utils'; 3 | var Mongoose:any = require('mongoose'); 4 | var db = require("../db"); 5 | 6 | var defaultMessengerSize = 1024 * 1024 * 100; 7 | var mainMessagerName = 'Message1'; 8 | var mainMessengerSize = 1024 * 1024 * 100; 9 | 10 | if (CoreUtils.config().mainMessagerName) { 11 | mainMessagerName = CoreUtils.config().mainMessagerName; 12 | } 13 | 14 | if (CoreUtils.config().mainMessengerSize) { 15 | mainMessengerSize = CoreUtils.config().mainMessengerSize; 16 | } 17 | 18 | if (CoreUtils.config().defaultMessengerSize) { 19 | defaultMessengerSize = CoreUtils.config().defaultMessengerSize; 20 | } 21 | 22 | var MessageFordefaultMessengerSize = new Mongoose.Schema({ 23 | channel: String, 24 | timestamp: { type: Date, default: Date.now }, 25 | message: {} 26 | }, { 27 | capped: { 28 | size: defaultMessengerSize, // in bytes 29 | autoIndexId: true 30 | 31 | }, 32 | validateBeforeSave: false 33 | }); 34 | 35 | var MessageForMainMessengerSize = new Mongoose.Schema({ 36 | channel: String, 37 | timestamp: { type: Date, default: Date.now }, 38 | message: {} 39 | }, { 40 | capped: { 41 | size: mainMessengerSize, // in bytes 42 | autoIndexId: true 43 | 44 | }, 45 | validateBeforeSave: false 46 | }); 47 | 48 | var getMessengerOfSize = (size) => new Mongoose.Schema({ 49 | channel: String, 50 | timestamp: { type: Date, default: Date.now }, 51 | message: {} 52 | }, { 53 | capped: { 54 | size: size, // in bytes 55 | autoIndexId: true 56 | 57 | }, 58 | validateBeforeSave: false 59 | }); 60 | 61 | 62 | export function getMessage(collectionName?: string, size?: number):any{ 63 | 64 | if (CoreUtils.config().mainMessagerName) { 65 | mainMessagerName = CoreUtils.config().mainMessagerName; 66 | } 67 | 68 | if (CoreUtils.config().mainMessengerSize) { 69 | mainMessengerSize = CoreUtils.config().mainMessengerSize; 70 | } 71 | 72 | if (CoreUtils.config().defaultMessengerSize) { 73 | defaultMessengerSize = CoreUtils.config().defaultMessengerSize; 74 | } 75 | 76 | let schemaName = mainMessagerName; 77 | let schema = MessageForMainMessengerSize; 78 | if (collectionName) { 79 | schemaName = collectionName; 80 | schema = MessageFordefaultMessengerSize; 81 | } 82 | if (size) { 83 | schema = getMessengerOfSize(size); 84 | } 85 | 86 | return db.getDbSpecifcModel(schemaName, schema); 87 | } 88 | 89 | module.exports = getMessage 90 | -------------------------------------------------------------------------------- /mongoose/schema.ts: -------------------------------------------------------------------------------- 1 | import {DynamicSchema} from './dynamic-schema'; 2 | import {repositoryMap} from '../core/exports'; 3 | import {MetaUtils} from '../core/metadata/utils'; 4 | import {Decorators as CoreDecorators} from '../core/constants'; 5 | import {Decorators} from './constants'; 6 | import {MongooseService} from './mongoose-service'; 7 | import * as Utils from '../core/utils'; 8 | import {IDocumentParams} from './decorators/interfaces/document-params'; 9 | import {IRepositoryParams} from '../core/decorators/interfaces/repository-params'; 10 | import {updateModelEntity, pathRepoMap, getModel, repoFromModel} from '../core/dynamic/model-entity'; 11 | import Mongoose = require('mongoose'); 12 | 13 | export function generateSchema() { 14 | 15 | // register mongoose service 16 | Utils.entityService(Decorators.DOCUMENT, new MongooseService()); 17 | 18 | var documents = MetaUtils.getMetaDataForDecorators([CoreDecorators.DOCUMENT]); 19 | documents.forEach(x => { 20 | let documentMeta = x.metadata[0]; 21 | let schemaName = (documentMeta.params).name; 22 | let schema = new DynamicSchema(documentMeta.target, schemaName); 23 | let mongooseSchema = schema.getSchema(); 24 | let model = Mongoose.model(schemaName, mongooseSchema); 25 | updateModelEntity(schemaName, documentMeta.target, model, schema); 26 | }); 27 | 28 | var repositoryMetadata = MetaUtils.getMetaDataForDecorators([CoreDecorators.REPOSITORY]); 29 | repositoryMetadata.forEach(x => { 30 | if (!x.metadata || !x.metadata.length) { 31 | return; 32 | } 33 | let repositoryParams = x.metadata[0].params; 34 | let entity = (x.metadata[0].params).model; 35 | let meta = MetaUtils.getMetaData(entity, Decorators.DOCUMENT); 36 | if (meta && meta.length > 0) { 37 | let documentMeta = meta[0]; 38 | if (documentMeta) { 39 | let schemaName = (documentMeta.params).name; 40 | pathRepoMap[repositoryParams.path] = { schemaName: schemaName, modelType: Decorators.DOCUMENT}; 41 | 42 | //repoFromModel[documentMeta.params.name] = repositoryMap[repositoryParams.path]; 43 | } 44 | } 45 | }); 46 | } 47 | 48 | // need to pass this via reference 49 | // var visitedNodes = new Map(); 50 | 51 | // export function validateModels() { 52 | // var modelsMeta = metaUtils.getMetaDataForDecoratorInAllTargets(Decorators.DOCUMENT); 53 | // Enumerable.from(modelsMeta).forEach(x => { 54 | // var m: MetaData = x; 55 | // var res = this.hasLoop(m.target, new Array()); 56 | // if (res) { 57 | // throw 'Cannot start server. Please correct the model ' + m.target.constructor.name; 58 | // } 59 | // }); 60 | //} 61 | 62 | // private function hasLoop(target: Object, vis: Array): boolean { 63 | // var rel = metaUtils.getAllRelationsForTargetInternal(target); 64 | // Enumerable.from(rel).forEach(y => { 65 | // var r: MetaData = y; 66 | // var param: IAssociationParams = r.params; 67 | // if (param.embedded || param.eagerLoading) { 68 | // var res = false; 69 | // if (this.visitedNodes.has(r)) { 70 | // // no need to go ahead, path from this node is already checked 71 | // res = false; 72 | // } 73 | // else if (vis.indexOf(r) > -1) { 74 | // // loop found 75 | // res = true; 76 | // } 77 | // else { 78 | // vis.push(r); 79 | // this.visitedNodes.set(r, true); 80 | // res = this.hasLoop(param.itemType, vis); 81 | // } 82 | 83 | // // if any loop 84 | // if (res) 85 | // return true; 86 | // } 87 | // }); 88 | 89 | // return false; 90 | // } -------------------------------------------------------------------------------- /node-data.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ratneshsinghparihar/Node-Data/0f4beb2384678e1b973d55c01d7dbce68ec96602/node-data.png -------------------------------------------------------------------------------- /node-data.sln: -------------------------------------------------------------------------------- 1 |  2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio 14 4 | VisualStudioVersion = 14.0.24720.0 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{9092AA53-FB77-4645-B42D-1CCCA6BD08BD}") = "node-data", "node-data.njsproj", "{009BE828-1009-4422-9DCA-BAC09CA0289C}" 7 | EndProject 8 | Global 9 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 10 | Debug|Any CPU = Debug|Any CPU 11 | Release|Any CPU = Release|Any CPU 12 | EndGlobalSection 13 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 14 | {009BE828-1009-4422-9DCA-BAC09CA0289C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 15 | {009BE828-1009-4422-9DCA-BAC09CA0289C}.Debug|Any CPU.Build.0 = Debug|Any CPU 16 | {009BE828-1009-4422-9DCA-BAC09CA0289C}.Release|Any CPU.ActiveCfg = Release|Any CPU 17 | {009BE828-1009-4422-9DCA-BAC09CA0289C}.Release|Any CPU.Build.0 = Release|Any CPU 18 | EndGlobalSection 19 | GlobalSection(SolutionProperties) = preSolution 20 | HideSolutionNode = FALSE 21 | EndGlobalSection 22 | EndGlobal 23 | -------------------------------------------------------------------------------- /node-data1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ratneshsinghparihar/Node-Data/0f4beb2384678e1b973d55c01d7dbce68ec96602/node-data1.png -------------------------------------------------------------------------------- /postman_scripts/Embedded_child.postman_collection.json: -------------------------------------------------------------------------------- 1 | { 2 | "id": "1f1dd3c5-9f3c-9033-f444-a3688845e76c", 3 | "name": "Embedded_child", 4 | "description": "", 5 | "order": [ 6 | "4ceb5ee8-114b-3092-ef58-7af3c96ad403", 7 | "0f1087b4-20ba-3c04-1f44-d4647882cead" 8 | ], 9 | "folders": [], 10 | "owner": "1223943", 11 | "hasRequests": true, 12 | "requests": [ 13 | { 14 | "id": "0f1087b4-20ba-3c04-1f44-d4647882cead", 15 | "headers": "netsessionid: 28ad0ac0-bf74-479e-9e13-13bab456038f\nContent-Type: application/json\n", 16 | "url": "http://localhost:23548/data/teacher/{{teacherid}}", 17 | "preRequestScript": null, 18 | "pathVariables": {}, 19 | "method": "GET", 20 | "data": [], 21 | "dataMode": "raw", 22 | "tests": null, 23 | "currentHelper": "normal", 24 | "helperAttributes": {}, 25 | "time": 1498817749964, 26 | "name": "http://localhost:23548/data/teacher/5956002e6ab1dc8c52cf45a0", 27 | "description": "", 28 | "collectionId": "1f1dd3c5-9f3c-9033-f444-a3688845e76c", 29 | "responses": [], 30 | "rawModeData": "{\n\t\"courseOTM\":[{}],\n\t\"physics\":[{}]\n\t\n}" 31 | }, 32 | { 33 | "id": "4ceb5ee8-114b-3092-ef58-7af3c96ad403", 34 | "headers": "netsessionid: 28ad0ac0-bf74-479e-9e13-13bab456038f\nContent-Type: application/json\n", 35 | "url": "http://localhost:23548/data/teacher", 36 | "preRequestScript": null, 37 | "pathVariables": {}, 38 | "method": "POST", 39 | "data": [], 40 | "dataMode": "raw", 41 | "tests": "tests[\"Status code is 200\"] = responseCode.code === 200;\n\nvar jsonData = JSON.parse(responseBody);\npostman.setEnvironmentVariable(\"teacherid\", jsonData._id);\n\n", 42 | "currentHelper": "normal", 43 | "helperAttributes": {}, 44 | "time": 1498817748336, 45 | "name": "http://localhost:23548/data/teacher", 46 | "description": "", 47 | "collectionId": "1f1dd3c5-9f3c-9033-f444-a3688845e76c", 48 | "responses": [], 49 | "rawModeData": "{\n\t\"name\": \"Teacher1\",\n\t\"physicsOne\":{\"name\":\"p1\", \"createdDate\": 2, \"updateddate\": 3},\n\t\"physicsMany\":[\n\t\t{\"name\":\"pm1\", \"createdDate\": 3, \"updateddate\": 5},\n\t\t{\"name\":\"pm2\", \"createdDate\": 1, \"updateddate\": 7,\"delete\":true}\n\t\t]\n}" 50 | } 51 | ] 52 | } -------------------------------------------------------------------------------- /postman_scripts/WorkerAndProcessControlTest.json: -------------------------------------------------------------------------------- 1 | { 2 | "id": "aea1ab17-0375-620d-2998-0fbeba5384b9", 3 | "name": "WorkerAndProcessControl", 4 | "description": "", 5 | "order": [ 6 | "c97a1537-a280-f2a6-cfea-69874b6bd844", 7 | "92f2edc3-7b11-1cb5-cb95-b2aebad7985c", 8 | "e5dc69c1-1ba2-5b4c-d086-12803363ca80" 9 | ], 10 | "folders": [], 11 | "timestamp": 1499403789869, 12 | "owner": "", 13 | "public": false, 14 | "requests": [ 15 | { 16 | "id": "92f2edc3-7b11-1cb5-cb95-b2aebad7985c", 17 | "headers": "Content-Type: application/json\n", 18 | "headerData": [ 19 | { 20 | "key": "Content-Type", 21 | "value": "application/json", 22 | "description": "", 23 | "enabled": true 24 | } 25 | ], 26 | "url": "http://localhost:23548/data/teacher/action/doAddTeacherProcessControl", 27 | "queryParams": [], 28 | "pathVariables": {}, 29 | "pathVariableData": [], 30 | "preRequestScript": null, 31 | "method": "POST", 32 | "collectionId": "aea1ab17-0375-620d-2998-0fbeba5384b9", 33 | "data": [], 34 | "dataMode": "raw", 35 | "name": "http://localhost:23548/data/teacher/action/doAddTeacherProcessControl", 36 | "description": "Add teacher with Process control", 37 | "descriptionFormat": "html", 38 | "time": 1499403861153, 39 | "version": 2, 40 | "responses": [], 41 | "tests": null, 42 | "currentHelper": "normal", 43 | "helperAttributes": {}, 44 | "rawModeData": "{\n\t\"obj\":{\n\t\t\"name\":\"teacher1\"\n\t}\n}" 45 | }, 46 | { 47 | "id": "c97a1537-a280-f2a6-cfea-69874b6bd844", 48 | "headers": "Content-Type: application/json\n", 49 | "headerData": [ 50 | { 51 | "key": "Content-Type", 52 | "value": "application/json", 53 | "description": "", 54 | "enabled": true 55 | } 56 | ], 57 | "url": "http://localhost:23548/data/teacher/action/doAddTeacherWorker", 58 | "queryParams": [], 59 | "pathVariables": {}, 60 | "pathVariableData": [], 61 | "preRequestScript": null, 62 | "method": "POST", 63 | "collectionId": "aea1ab17-0375-620d-2998-0fbeba5384b9", 64 | "data": [], 65 | "dataMode": "raw", 66 | "name": "http://localhost:23548/data/teacher/action/doAddTeacherWorker", 67 | "description": "Add teacher through worker", 68 | "descriptionFormat": "html", 69 | "time": 1499403789868, 70 | "version": 2, 71 | "responses": [], 72 | "tests": null, 73 | "currentHelper": "normal", 74 | "helperAttributes": {}, 75 | "rawModeData": "{\n\t\"obj\":{\n\t\t\"name\":\"teacher1\"\n\t}\n}" 76 | }, 77 | { 78 | "id": "e5dc69c1-1ba2-5b4c-d086-12803363ca80", 79 | "headers": "Content-Type: application/json\n", 80 | "headerData": [ 81 | { 82 | "key": "Content-Type", 83 | "value": "application/json", 84 | "description": "", 85 | "enabled": true 86 | } 87 | ], 88 | "url": "http://localhost:23548/data/teacher/action/doUpdateTeacherProcessControlAndWorker", 89 | "queryParams": [], 90 | "pathVariables": {}, 91 | "pathVariableData": [], 92 | "preRequestScript": null, 93 | "method": "POST", 94 | "collectionId": "aea1ab17-0375-620d-2998-0fbeba5384b9", 95 | "data": [], 96 | "dataMode": "raw", 97 | "name": "http://localhost:23548/data/teacher/action/doUpdateTeacherProcessControlAndWorker", 98 | "description": "Add teacher through worker and monitor with process control", 99 | "descriptionFormat": "html", 100 | "time": 1499403920092, 101 | "version": 2, 102 | "responses": [], 103 | "tests": null, 104 | "currentHelper": "normal", 105 | "helperAttributes": {}, 106 | "rawModeData": "{\n\t\"obj\":{\n\t\t\"name\":\"teacher1\"\n\t}\n}" 107 | } 108 | ] 109 | } -------------------------------------------------------------------------------- /publish.bat: -------------------------------------------------------------------------------- 1 | call gulp compile-ts 2 | call npm version patch 3 | call npm publish -------------------------------------------------------------------------------- /readme-code-uniformity.md: -------------------------------------------------------------------------------- 1 | #####File names 2 | Filename should be in lowercase with "_" to separate words in the name and "-" to separate type of the file (service, controller etc.). 3 | Eg. user-service.ts, user_role-service.ts, user_login_logout-service.ts 4 | 5 | #####Code Formatting 6 | 1. Indentation: 4 spaces (some people might disagree, but we have to fix something) 7 | 2. EOL: LF (default for git) 8 | 9 | #####Naming Conventions 10 | 1. private variables - prefixed with "\_", camelCase 11 | 2. public/static variables - camelCase 12 | 3. constants - ALL\_CAPS 13 | 4. methods - camelCase 14 | 5. classes - PascalCase 15 | 6. enums - name PascalCase, fields ALL\_CAPS 16 | 17 | -------------------------------------------------------------------------------- /repositories/blogPostsqlrepository.ts: -------------------------------------------------------------------------------- 1 | //import * as Express from "express"; 2 | import * as decorator from "../core/decorators/repository"; 3 | import {BlogPostSqlModel} from '../models/blogPostSqlModel'; 4 | 5 | @decorator.repository({ path: 'blogPosts', model: BlogPostSqlModel }) 6 | //@decorator.repository('blog', BlogModel) 7 | export default class BlogPostSqlRepository { 8 | 9 | constructor() { 10 | //super(RoleRepository.path, role.IRole); 11 | //new BaseRepository1(this.path, User1); 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /repositories/blogsqlrepository.ts: -------------------------------------------------------------------------------- 1 | //import * as Express from "express"; 2 | import * as decorator from "../core/decorators/repository"; 3 | import {BlogSqlModel} from '../models/blogSqlModel'; 4 | 5 | @decorator.repository({ path: 'story', model: BlogSqlModel }) 6 | //@decorator.repository('blog', BlogModel) 7 | export default class BlogSqlRepository { 8 | 9 | constructor() { 10 | //super(RoleRepository.path, role.IRole); 11 | //new BaseRepository1(this.path, User1); 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /repositories/schoolRepository.ts: -------------------------------------------------------------------------------- 1 | import * as decorator from "../core/decorators/repository"; 2 | import { DynamicRepository } from '../core/dynamic/dynamic-repository'; 3 | import {SequelizeSchool} from '../models/sequelizeSchool'; 4 | 5 | @decorator.repository({ path: 'school', model: SequelizeSchool }) 6 | export class SchoolRepository extends DynamicRepository { 7 | 8 | doGetSchoolWithProps(id, properties){ 9 | return this.findWhere({Id:id}, properties); 10 | } 11 | 12 | } 13 | 14 | export default SchoolRepository -------------------------------------------------------------------------------- /repositories/storyrepository.ts: -------------------------------------------------------------------------------- 1 | //import * as Express from "express"; 2 | import * as decorator from "../core/decorators/repository"; 3 | import {StoryModel} from '../models/storyModel'; 4 | 5 | @decorator.repository({ path: 'story', model: StoryModel }) 6 | //@decorator.repository('blog', BlogModel) 7 | export default class StorySqlRepository { 8 | 9 | constructor() { 10 | //super(RoleRepository.path, role.IRole); 11 | //new BaseRepository1(this.path, User1); 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /repositories/studentRepository.ts: -------------------------------------------------------------------------------- 1 | import * as decorator from "../core/decorators/repository"; 2 | import { DynamicRepository } from '../core/dynamic/dynamic-repository'; 3 | import {SequelizeStudent} from '../models/sequelizeStudent'; 4 | 5 | @decorator.repository({ path: 'student', model: SequelizeStudent }) 6 | export class StudentRepository extends DynamicRepository { 7 | 8 | } 9 | 10 | export default StudentRepository -------------------------------------------------------------------------------- /repositories/teacherRepository.ts: -------------------------------------------------------------------------------- 1 | import * as decorator from "../core/decorators/repository"; 2 | import { DynamicRepository } from '../core/dynamic/dynamic-repository'; 3 | import {SequelizeTeacher} from '../models/sequelizeTeacher'; 4 | 5 | @decorator.repository({ path: 'teacher', model: SequelizeTeacher }) 6 | export class TeacherRepository extends DynamicRepository { 7 | 8 | } 9 | 10 | export default TeacherRepository -------------------------------------------------------------------------------- /scripts/ci-version-devbuild.js: -------------------------------------------------------------------------------- 1 | "use strict"; 2 | const fs = require("fs"); 3 | function setNewDevBuildVersion(pkgJsonPath) { 4 | let pkgJsonParsed = JSON.parse(fs.readFileSync(pkgJsonPath, 'utf8')); 5 | let oldVersion = pkgJsonParsed.version; 6 | // Update the version 7 | let newDevVersion = getNextDevVersion(pkgJsonParsed.version); 8 | pkgJsonParsed.version = newDevVersion; 9 | fs.writeFileSync(pkgJsonPath, JSON.stringify(pkgJsonParsed, undefined, 2), { encoding: 'utf8' }); 10 | let pkgJsonParsedNew = JSON.parse(fs.readFileSync(pkgJsonPath, 'utf8')); 11 | if (pkgJsonParsed.version === oldVersion) { 12 | throw 'Version update failed'; 13 | } 14 | } 15 | exports.setNewDevBuildVersion = setNewDevBuildVersion; 16 | function getNextDevVersion(versionString) { 17 | // Get date and time string in the format YYMMDDHHMMSS 18 | let timeStamp = new Date().toISOString().replace(/[TZ:\-\.]/g, "").slice(2, 14); 19 | if (versionString.indexOf('-') != -1) { 20 | versionString = versionString.slice(0, versionString.indexOf('-')); 21 | } 22 | return versionString + '-dev.' + timeStamp; 23 | } 24 | -------------------------------------------------------------------------------- /search/elasticSearchUtils.ts: -------------------------------------------------------------------------------- 1 | var mongoosastic = require("mongoosastic"); 2 | var elasticsearch = require("elasticsearch"); 3 | 4 | import {Config} from "../config"; 5 | 6 | /** 7 | * ElastticSearchUtils 8 | */ 9 | class ElastticSearchUtils { 10 | private esClient: any; 11 | constructor() { 12 | if (Config.ApplyElasticSearch) { 13 | this.esClient = new elasticsearch.Client({ host: Config.ElasticSearchConnection }); 14 | } 15 | } 16 | 17 | insertMongoosasticToSchema(schema: any) { 18 | if (Config.ApplyElasticSearch) { 19 | schema.plugin(mongoosastic, { 20 | esClient: this.esClient 21 | }); 22 | } 23 | } 24 | 25 | registerToMongoosastic(mongooseModel: any) { 26 | // This will be called only in the case if the mongoosastic plugin was attached to the mongoose model. 27 | if (Config.ApplyElasticSearch && mongooseModel.createMapping) { 28 | mongooseModel.createMapping((err: any, mapping: any) => { 29 | if (err) { 30 | console.error(err); 31 | } 32 | else { 33 | console.log(mapping); 34 | } 35 | }); 36 | } 37 | } 38 | } 39 | 40 | export var searchUtils = new ElastticSearchUtils(); -------------------------------------------------------------------------------- /security-config.d.ts: -------------------------------------------------------------------------------- 1 | export declare class SecurityConfig { 2 | static ResourceAccess: any; 3 | static tokenSecretkey: string; 4 | static tokenExpiresInMinutes: number; 5 | static issuer: string; 6 | static audience: string; 7 | } 8 | export declare enum AccessMask { 9 | view = 1, 10 | edit = 2, 11 | delete = 4, 12 | approve = 8, 13 | } 14 | export declare enum RoleEnum { 15 | ROLE_ADMIN = 1, 16 | ROLE_USER = 2, 17 | ROLE_AUTHOR = 3, 18 | ROLE_PUBLISHER = 4, 19 | } 20 | export declare enum AuthenticationType { 21 | passwordBased = 1, 22 | TokenBased = 2, 23 | } 24 | export declare enum AuthenticationEnabled { 25 | disabled = 1, 26 | enabledWithoutAuthorization = 2, 27 | enabledWithAuthorization = 3, 28 | } 29 | -------------------------------------------------------------------------------- /security-config.ts: -------------------------------------------------------------------------------- 1 | 2 | export class SecurityConfig { 3 | public static ResourceAccess: Array<{ name: string, acl: Array<{ role: string, accessmask: number, acl?: boolean }> }> = [{ 4 | "name": "blogs", 5 | "acl": [{ "role": "ROLE_ADMIN", "accessmask": 7 }, 6 | { "role": "ROLE_USER", "accessmask": 1 }, 7 | { "role": "ROLE_AUTHOR", "accessmask": 7 } 8 | ] 9 | }, 10 | { 11 | "name": "comment", 12 | "acl": [{ "role": "ROLE_ADMIN", "accessmask": 7 }, 13 | { "role": "ROLE_USER", "accessmask": 7 }, 14 | { "role": "ROLE_AUTHOR", "accessmask": 7 } 15 | ] 16 | }]; 17 | public static tokenSecretkey: string = 'ericthered'; 18 | public static tokenExpiresInMinutes: number = 2;//2 months 19 | 20 | public static issuer: string = "accounts.examplesoft.com"; 21 | public static audience: string = "yoursite.net"; 22 | } 23 | 24 | 25 | export enum AccessMask { 26 | view = 1, 27 | edit = 2, 28 | delete = 4, 29 | approve = 8 30 | }; 31 | 32 | export enum RoleEnum { 33 | ROLE_ADMIN = 1, 34 | ROLE_USER, 35 | ROLE_AUTHOR, 36 | ROLE_PUBLISHER 37 | }; 38 | 39 | export enum AuthenticationType { 40 | passwordBased = 1, 41 | TokenBased = 2 42 | }; 43 | 44 | export enum AuthenticationEnabled { 45 | disabled = 1, 46 | enabledWithoutAuthorization = 2, 47 | enabledWithAuthorization = 3 48 | }; 49 | -------------------------------------------------------------------------------- /security/auth/auth-service.spec.ts: -------------------------------------------------------------------------------- 1 | require('reflect-metadata/reflect'); 2 | import {AuthController} from './authcontroller'; 3 | import {UserRepositoryMock} from '../../unit-test/repository/user-repository-mock'; 4 | import {Container} from '../../di/di'; 5 | import UserRepository from '../../tests/repositories/userRepository'; 6 | import {AuthService} from './auth-service'; 7 | import {MockAuthService} from '../../unit-test/services/MockService'; 8 | import * as securityUtils from './security-utils'; 9 | import * as configUtils from '../../core/utils'; 10 | import {UserDetailService} from './user-detail-service'; 11 | 12 | describe('AuthServiceFunc', () => { 13 | beforeEach(() => { 14 | spyOn(Container, 'resolve').and.callFake((val) => { 15 | switch (val) { 16 | case AuthService: 17 | return new MockAuthService(); 18 | } 19 | }); 20 | spyOn(configUtils, 'config').and.returnValue( 21 | { 22 | 'Security': { 23 | 'isAutheticationEnabled': 'disabled', 24 | 'authenticationType': 'passwordBased' 25 | }, 26 | 'facebookAuth': { 27 | 'clientID': '11', 28 | 'clientSecret': 'aa', 29 | 'callbackURL': 'http://localhost:23548/auth/facebook/callback' 30 | }, 31 | 'Config': { 32 | 'DbConnection': 'mongodb://localhost:27017/userDatabase', 33 | 'basePath': "data", 34 | 'apiversion': "v1", 35 | 'ElasticSearchConnection': 'http://localhost:9200', 36 | 'ApplyElasticSearch': false 37 | } 38 | } 39 | ); 40 | }); 41 | 42 | it('authservice constructor with authentication disabled', () => { 43 | configUtils.config().Security.isAutheticationEnabled = 'disabled'; 44 | var authService = new AuthService(); 45 | expect(authService).not.toBeNull(); 46 | }); 47 | it('authservice constructor with authentication enabled without authorization', () => { 48 | configUtils.config().Security.isAutheticationEnabled = 'enabledWithoutAuthorization'; 49 | var authService = new AuthService(); 50 | expect(authService).not.toBeNull(); 51 | }); 52 | it('authservice constructor with authentication enabled with authorization', () => { 53 | configUtils.config().Security.isAutheticationEnabled = 'enabledWithAuthorization'; 54 | var authService = new AuthService(); 55 | expect(authService).not.toBeNull(); 56 | }); 57 | it('authservice authenticate method invoked with authentication disabled', () => { 58 | configUtils.config().Security.isAutheticationEnabled = 'disabled'; 59 | var authService = new AuthService(); 60 | authService.authenticate(); 61 | }); 62 | it('authservice authenticate method invoked with authentication enabled without authorization', () => { 63 | configUtils.config().Security.isAutheticationEnabled = 'enabledWithoutAuthorization'; 64 | var authService = new AuthService(); 65 | authService.authenticate(); 66 | }); 67 | it('authservice authenticate method invoked with authentication enabled with authorization', () => { 68 | configUtils.config().Security.isAutheticationEnabled = 'enabledWithAuthorization'; 69 | var authService = new AuthService(); 70 | authService.authenticate(); 71 | }); 72 | }); -------------------------------------------------------------------------------- /security/auth/autherizationParam.ts: -------------------------------------------------------------------------------- 1 |  2 | 3 | export interface IAutherizationParam 4 | { 5 | role: string, 6 | accessmask: number, 7 | acl?: boolean, 8 | emitToSingleWorker?: boolean 9 | } 10 | 11 | 12 | -------------------------------------------------------------------------------- /security/auth/principalContext.ts: -------------------------------------------------------------------------------- 1 | var domain = require('./domain'); 2 | var cls = require('continuation-local-storage'); 3 | 4 | export class PrincipalContext { 5 | private static session: any; 6 | 7 | static getSession() { 8 | if (PrincipalContext.session != null && PrincipalContext.session != 'undefined') { 9 | //cls = require('continuation-local-storage').getNamespace; 10 | PrincipalContext.session = cls.getNamespace('session'); 11 | } else { 12 | console.log('creating session from principal context'); 13 | //cls = require('continuation-local-storage').createNamespace; 14 | PrincipalContext.session = cls.createNamespace('session'); 15 | } 16 | return PrincipalContext.session; 17 | } 18 | 19 | static get User(): any { 20 | return domain.get('context:user'); 21 | //return PrincipalContext.getSession().get('user'); 22 | } 23 | 24 | static set User(user: any) { 25 | try { 26 | domain.set('context:user', user); 27 | PrincipalContext.setKeys('user'); 28 | } 29 | catch (exception) { 30 | console.log("no active context found"); 31 | } 32 | //PrincipalContext.getSession().set('user', user); 33 | } 34 | 35 | static save(key: string, value: any): any { 36 | if (!key) 37 | throw 'invalid key'; 38 | domain.set('context:' + key.trim(), value); 39 | PrincipalContext.setKeys(key); 40 | //PrincipalContext.getSession().set(key, value); 41 | } 42 | 43 | static get(key: string) { 44 | return domain.get('context:' + key.trim()); 45 | //return PrincipalContext.getSession().get(key); 46 | } 47 | 48 | private static setKeys(key: String) { 49 | var keys: Array = domain.get('context:_keys'); 50 | //var keys :Array = PrincipalContext.getSession().get('_keys'); 51 | if (keys == null) { 52 | domain.set('context:_keys', [key]); 53 | //PrincipalContext.getSession().set('_keys',[key]); 54 | } 55 | else { 56 | if (keys.indexOf(key) < 0) { 57 | keys.push(key); 58 | domain.set('context:_keys', keys); 59 | //PrincipalContext.getSession().set('_keys',keys); 60 | } 61 | } 62 | //console.log("context: "+ JSON.stringify(PrincipalContext.getSession())); 63 | } 64 | 65 | static getAllKeys() { 66 | return domain.get('context:_keys'); 67 | //return PrincipalContext.getSession().get('_keys'); 68 | } 69 | 70 | static getAllKeyValues(): any { 71 | var keys: Array = PrincipalContext.getAllKeys(); 72 | var ret = {}; 73 | keys.forEach(x => { 74 | var val = PrincipalContext.get(x); 75 | if (x && val) { 76 | try { 77 | val = JSON.parse(val); 78 | } 79 | catch (e) { 80 | } 81 | ret[x] = val; 82 | } 83 | }); 84 | return ret; 85 | } 86 | } -------------------------------------------------------------------------------- /security/auth/user-detail-service.ts: -------------------------------------------------------------------------------- 1 | import {UserDetails} from './user-details'; 2 | import Q = require('q'); 3 | export interface UserDetailService { 4 | loadUserByUsername(userName: string): Q.Promise; 5 | loadUserById(id: number): Q.Promise; 6 | loadUserByField(field: any, value: any): Q.Promise; 7 | createNewUser(userObject): Q.Promise; 8 | updateExistingUser(id, userObject): Q.Promise; 9 | getNewUser(req, res); 10 | getCurrentUser(sessionId): Q.Promise; 11 | verifyUser(req, res); 12 | resendToken(req, res); 13 | forgotPasswordRequest(req, res); 14 | forgotPassword(req, res); 15 | resetPassword(req, res); 16 | } -------------------------------------------------------------------------------- /security/auth/user-details.ts: -------------------------------------------------------------------------------- 1 | export interface UserDetails { 2 | getAuthorities(): Array; 3 | 4 | getPassword(): string; 5 | 6 | getUsername(): string; 7 | 8 | isAccountNonExpired(): boolean; 9 | 10 | isAccountNonLocked(): boolean; 11 | 12 | isCredentialsNonExpired(): boolean; 13 | 14 | isEnabled(): boolean; 15 | 16 | getUserObject(): any; 17 | } -------------------------------------------------------------------------------- /security/auth/user.ts: -------------------------------------------------------------------------------- 1 | import {UserDetails} from './user-details'; 2 | export class User implements UserDetails { 3 | private password: string; 4 | username: string; 5 | private authorities: Array; 6 | private accountNonExpired: boolean; 7 | private accountNonLocked: boolean; 8 | private credentialsNonExpired: boolean; 9 | private enabled: boolean; 10 | private userObject: any; 11 | private dbName: string; 12 | 13 | public constructor(username: string, password: string, user: any, authorities?: Array, dbName?: string) { 14 | this.setUser(username, password, true, true, true, true, authorities); 15 | this.userObject = user; 16 | } 17 | 18 | public setUser(username: string, password: string, 19 | enabled: boolean, accountNonExpired: boolean, 20 | credentialsNonExpired: boolean, accountNonLocked: boolean, 21 | authorities: Array,dbName?: string) { 22 | if (username != null && username != "" && password != null) { 23 | this.username = username; 24 | this.password = password; 25 | this.enabled = enabled; 26 | this.accountNonExpired = accountNonExpired; 27 | this.credentialsNonExpired = credentialsNonExpired; 28 | this.accountNonLocked = accountNonLocked; 29 | this.authorities = authorities; 30 | this.dbName = dbName; 31 | } else { 32 | throw "Cannot pass null or empty values to constructor"; 33 | } 34 | } 35 | 36 | getAuthorities(): Array { 37 | return this.authorities; 38 | }; 39 | 40 | getPassword(): string { 41 | return this.password; 42 | }; 43 | 44 | getDbName(): string { 45 | return this.dbName; 46 | }; 47 | 48 | getUsername(): string { 49 | return this.username; 50 | }; 51 | 52 | isAccountNonExpired(): boolean { 53 | return this.accountNonExpired; 54 | }; 55 | 56 | isAccountNonLocked(): boolean { 57 | return this.accountNonLocked; 58 | }; 59 | 60 | isCredentialsNonExpired(): boolean { 61 | return this.credentialsNonExpired; 62 | }; 63 | 64 | isEnabled(): boolean { 65 | return this.enabled; 66 | }; 67 | 68 | eraseCredentials() { 69 | this.password = null; 70 | } 71 | 72 | getUserObject(): any { 73 | return this.userObject; 74 | }; 75 | } -------------------------------------------------------------------------------- /sequelizeimp/constants/decorators.ts: -------------------------------------------------------------------------------- 1 |  2 | export class Decorators { 3 | public static ENTITY = 'entity'; 4 | public static COLUMN = 'column'; 5 | public static TRANSIENT = 'transient'; 6 | } -------------------------------------------------------------------------------- /sequelizeimp/constants/index.ts: -------------------------------------------------------------------------------- 1 | export {Decorators} from './decorators'; -------------------------------------------------------------------------------- /sequelizeimp/datatype.ts: -------------------------------------------------------------------------------- 1 | import Mongoose = require('mongoose'); 2 | 3 | export import ObjectId = Mongoose.Types.ObjectId; 4 | export import Mixed = Mongoose.SchemaType; 5 | 6 | export var Types = { 7 | ObjectId: ObjectId, 8 | Mixed: Mixed 9 | } -------------------------------------------------------------------------------- /sequelizeimp/decorators/column.ts: -------------------------------------------------------------------------------- 1 | import {MetaUtils} from "../../core/metadata/utils"; 2 | import {DecoratorType} from '../../core/enums/decorator-type'; 3 | import {Decorators} from '../constants'; 4 | import * as Sequelize from "sequelize"; 5 | 6 | export function column(params?: {name:string, 7 | type?: any, allowNull?: boolean,defaultValue?:any, 8 | primaryKey?:boolean,unique?:boolean,validate?:any, autogenerated?: boolean, searchIndex?: boolean,autoIncrement? : boolean 9 | }) { 10 | return function (target: Object, propertyKey: string) { 11 | console.log('field - propertyKey: ', propertyKey, ', target:', target); 12 | MetaUtils.addMetaData(target, 13 | { 14 | decorator: Decorators.COLUMN, 15 | decoratorType: DecoratorType.PROPERTY, 16 | params: params, 17 | propertyKey: propertyKey 18 | }); 19 | } 20 | } -------------------------------------------------------------------------------- /sequelizeimp/decorators/entity.ts: -------------------------------------------------------------------------------- 1 | import {MetaUtils} from "../../core/metadata/utils"; 2 | import {Decorators} from '../../core/constants'; 3 | import {DecoratorType} from '../../core/enums/decorator-type'; 4 | import {Strict} from '../enums/entity-strict'; 5 | 6 | export function entity(params: {name:string, tableName: string, timestamps?: boolean, createdAt?: string|boolean, updatedAt?: string|boolean, freezeTableName?:boolean }) { 7 | params = params || {}; 8 | return function(target: Object){ 9 | // add metadata to prototype 10 | MetaUtils.addMetaData(((target).prototype || target), 11 | { 12 | decorator: Decorators.ENTITY, 13 | decoratorType: DecoratorType.CLASS, 14 | modelType: DecoratorType.MODEL, 15 | params: params 16 | }); 17 | } 18 | } -------------------------------------------------------------------------------- /sequelizeimp/decorators/index.ts: -------------------------------------------------------------------------------- 1 | export {column} from './column'; 2 | export {entity} from './entity'; 3 | export {transient} from './transient'; -------------------------------------------------------------------------------- /sequelizeimp/decorators/interfaces/column-params.ts: -------------------------------------------------------------------------------- 1 | export interface IColumnParams { 2 | type: any, 3 | primaryKey?: boolean, 4 | unique?: boolean, 5 | allowNull?: boolean, 6 | validate?:any 7 | } -------------------------------------------------------------------------------- /sequelizeimp/decorators/interfaces/entity-params.ts: -------------------------------------------------------------------------------- 1 | import {IDecoratorParams} from '../../../core/decorators/interfaces/decorator-params'; 2 | 3 | export interface IEntityParams extends IDecoratorParams { 4 | tableName: string, 5 | timestamps: boolean 6 | } -------------------------------------------------------------------------------- /sequelizeimp/decorators/interfaces/index.ts: -------------------------------------------------------------------------------- 1 | export {IColumnParams} from './column-params'; 2 | export {IEntityParams} from './entity-params'; -------------------------------------------------------------------------------- /sequelizeimp/decorators/transient.ts: -------------------------------------------------------------------------------- 1 | import {MetaUtils} from "../../core/metadata/utils"; 2 | import {DecoratorType} from '../../core/enums/decorator-type'; 3 | import {Decorators} from '../constants'; 4 | 5 | export function transient() { 6 | return function (target: Object, propertyKey: string) { 7 | console.log('field - propertyKey: ', propertyKey, ', target:', target); 8 | MetaUtils.addMetaData(target, 9 | { 10 | decorator: Decorators.TRANSIENT, 11 | decoratorType: DecoratorType.PROPERTY, 12 | propertyKey: propertyKey 13 | }); 14 | } 15 | } -------------------------------------------------------------------------------- /sequelizeimp/enums/entity-strict.ts: -------------------------------------------------------------------------------- 1 | export enum Strict { 2 | false, 3 | true, 4 | throw 5 | } 6 | -------------------------------------------------------------------------------- /sequelizeimp/enums/index.ts: -------------------------------------------------------------------------------- 1 |  2 | export {Strict} from './entity-strict'; -------------------------------------------------------------------------------- /sequelizeimp/index.ts: -------------------------------------------------------------------------------- 1 |  2 | export {sequelizeService} from './sequelizeService'; 3 | export {generateSchema} from './schema'; 4 | -------------------------------------------------------------------------------- /sequelizeimp/utils/index.ts: -------------------------------------------------------------------------------- 1 | import * as Sequelize from "sequelize"; 2 | 3 | export function castToSequelizeType(value, schemaType) { 4 | var newVal; 5 | switch (schemaType) { 6 | //case Sequelize.UUID: 7 | // if (value instanceof Sequelize.UUID) { 8 | // newVal = value; 9 | // } else if (typeof value === 'string') { 10 | // newVal = new Sequelize.UUID(value); 11 | // } else { 12 | // throw 'cannot cast to primary key type'; 13 | // } 14 | // break; 15 | case String: 16 | if (typeof value === 'string') { 17 | newVal = value; 18 | } 19 | newVal = value.toString(); 20 | break; 21 | case Number: 22 | if (typeof value === 'number') { 23 | newVal = value; 24 | } 25 | newVal = parseInt(value); 26 | if (isNaN(newVal)) { 27 | throw 'cannot cast to primary key type'; 28 | } 29 | break; 30 | default: newVal = value; break; 31 | } 32 | return newVal; 33 | } -------------------------------------------------------------------------------- /server.ts: -------------------------------------------------------------------------------- 1 | /* tslint:disable */ 2 | require('reflect-metadata'); 3 | import http = require("http"); 4 | import express = require("express"); 5 | var bodyParser = require("body-parser"); 6 | var passport = require('passport'); 7 | var LocalStrategy = require('passport-local').Strategy; 8 | import * as config from './config'; 9 | import * as securityConfig from './security-config'; 10 | import {router} from './core/exports'; 11 | import {repositoryMap} from './core/exports'; 12 | import {Container} from './di'; 13 | 14 | import * as data from './mongoose'; 15 | //---------sequelize setting----------------------------- 16 | import * as seqData from "./sequelizeimp"; 17 | var Main = require('./core'); 18 | Main(config, securityConfig, __dirname, data.entityServiceInst, seqData.sequelizeService); 19 | //var Main = require('./core')(config, securityConfig, __dirname, data.entityServiceInst, seqData.sequelizeService); 20 | data.connect(); 21 | data.generateSchema(); 22 | seqData.sequelizeService.connect(); 23 | seqData.generateSchema(); 24 | 25 | var app = express(); 26 | Main.register(app); 27 | app.set('views', __dirname + '/views'); 28 | app.set('view engine', 'ejs'); 29 | app.use(require('morgan')('combined')); 30 | app.use(require('cookie-parser')()); 31 | var expressSession = require('express-session'); 32 | app.use(expressSession({ secret: 'mySecretKey', resave: false, saveUninitialized: false })); 33 | app.use(bodyParser.json()); 34 | app.use(passport.initialize()); 35 | app.use(passport.session()); 36 | app.use("/", router); 37 | var server = (http).createServer(app); 38 | server.listen(23548); 39 | -------------------------------------------------------------------------------- /spec/support/jasmine.json: -------------------------------------------------------------------------------- 1 | { 2 | "spec_dir":"./", 3 | "spec_files":[ 4 | "core/**/*[sS]pec.js", 5 | "di/**/*[sS]pec.js", 6 | "mongoose/**/*[sS]pec.js", 7 | "search/**/*[sS]pec.js", 8 | "security/**/*[sS]pec.js", 9 | "tests/**/*[sS]pec.js", 10 | "views/**/*[sS]pec.js", 11 | "*[sS]pec.js" 12 | ], 13 | "helpers":["helpers/**/ *.js"], 14 | "stopSpecOnExpectationFailure":false, 15 | "random":false 16 | } -------------------------------------------------------------------------------- /tests/models/baseModel.ts: -------------------------------------------------------------------------------- 1 | import {field, document} from '../../mongoose/decorators'; 2 | import {Types} from 'mongoose'; 3 | import {CrudEntity} from '../../core/dynamic/crud.entity'; 4 | 5 | export class baseModel extends CrudEntity { 6 | constructor(object?: any) { 7 | super(); 8 | } 9 | 10 | @field({ primary: true, autogenerated: true }) 11 | _id: Types.ObjectId; 12 | 13 | @field() 14 | name: String; 15 | 16 | @field() 17 | parent: any; 18 | 19 | @field() 20 | batch: any; 21 | 22 | /* 23 | nodedata internal use for caching, use for findWhere case 24 | */ 25 | __selectedFindWhere: string; 26 | 27 | /* 28 | nodedata internal use for caching, to marked as partial load for findMany (egar load case not load) 29 | */ 30 | __partialLoaded: boolean; 31 | } 32 | 33 | export default baseModel; -------------------------------------------------------------------------------- /tests/models/city.ts: -------------------------------------------------------------------------------- 1 | import Mongoose = require("mongoose"); 2 | import {Types} from 'mongoose'; 3 | import {field, document} from '../../mongoose/decorators'; 4 | import {Strict} from '../../mongoose/enums/'; 5 | import {baseModel} from './baseModel'; 6 | import {school} from './school'; 7 | import {onetomany, manytoone, manytomany, onetoone} from '../../core/decorators'; 8 | 9 | @document({ name: 'city', strict: Strict.false }) 10 | export class city extends baseModel { 11 | @field() 12 | age: string; 13 | 14 | @field({ searchIndex: true }) 15 | name: string; 16 | 17 | @field() 18 | createdDate: string; 19 | 20 | @field() 21 | updatedDate: string; 22 | 23 | @onetomany({ rel: 'school', itemType: school, embedded: true, persist: true, eagerLoading: false, deleteCascade: true, properties: ['name'] }) 24 | //@onetomany({ rel: 'school', itemType: school, embedded: true, persist: true, eagerLoading: false}) 25 | schools: Array; 26 | } 27 | 28 | export default city; -------------------------------------------------------------------------------- /tests/models/company.ts: -------------------------------------------------------------------------------- 1 | import Mongoose = require("mongoose"); 2 | import {Types} from 'mongoose'; 3 | import {employee} from './employee'; 4 | import {field, document, transient} from '../../mongoose/decorators'; 5 | import {Strict} from '../../mongoose/enums/'; 6 | import {onetomany, manytoone, manytomany, onetoone, promisable, IPromisableFetchParam} from '../../core/decorators'; 7 | import {baseModel} from './baseModel'; 8 | import { StorageType } from "../../core/enums/index"; 9 | 10 | @document({ name: 'company', strict: Strict.false }) 11 | export class company { 12 | 13 | @field({ primary: true, autogenerated: true }) 14 | _id: number; 15 | 16 | @onetoone({ rel: 'employee', itemType: employee, embedded: true, persist: true, eagerLoading: false, deleteCascade: true }) 17 | employeeOTO: employee; 18 | 19 | @onetomany({ rel: 'employee', itemType: employee, embedded: true, persist: true, eagerLoading: false, deleteCascade: true }) 20 | employeeOTM: Array; 21 | 22 | @onetoone({ rel: 'employee', itemType: employee, embedded: false, persist: true, eagerLoading: true, deleteCascade: true }) 23 | employeeOTOF: employee; 24 | 25 | @onetomany({ rel: 'employee', itemType: employee, embedded: false, persist: true, eagerLoading: true, deleteCascade: true }) 26 | employeeOTMF: Array; 27 | 28 | @onetomany({ rel: 'employee', itemType: employee, embedded: true, persist: true, eagerLoading: false, storageType: StorageType.JSONMAP, deleteCascade: true }) 29 | jEmployeeOTM: Array; 30 | 31 | } 32 | 33 | export default company; -------------------------------------------------------------------------------- /tests/models/employee.ts: -------------------------------------------------------------------------------- 1 | import Mongoose = require("mongoose"); 2 | import {Types} from 'mongoose'; 3 | import {field, document} from '../../mongoose/decorators'; 4 | import {Strict} from '../../mongoose/enums/'; 5 | import {baseModel} from './baseModel'; 6 | import {topic} from './topic'; 7 | import {onetomany, manytoone, manytomany, onetoone, promisable, IPromisableFetchParam} from '../../core/decorators'; 8 | import { StorageType } from "../../core/enums/index"; 9 | 10 | @document({ name: 'employee', strict: Strict.false }) 11 | export class employee { 12 | 13 | @field({ primary: true, autogenerated: true }) 14 | _id: number; 15 | } 16 | 17 | export default employee; -------------------------------------------------------------------------------- /tests/models/planet.ts: -------------------------------------------------------------------------------- 1 | import {field, document} from '../../mongoose/decorators'; 2 | import {Strict} from '../../mongoose/enums/'; 3 | import {baseModel} from './baseModel'; 4 | 5 | @document({ name: 'PLANET', strict: Strict.true, dynamicName: false, pluralization: false }) 6 | export class planet extends baseModel { 7 | @field() 8 | age: string; 9 | 10 | @field() 11 | name: string; 12 | } 13 | 14 | export default planet; -------------------------------------------------------------------------------- /tests/models/processControlModel.ts: -------------------------------------------------------------------------------- 1 | import { field, document } from '../../mongoose/decorators'; 2 | import { Types } from 'mongoose'; 3 | import { Strict } from '../../mongoose/enums'; 4 | import {workerParamsDto} from "../../core/decorators/interfaces/workerParamsDto"; 5 | console.log('initializing ProcessControlModel'); 6 | @document({ name: 'processControl', strict: Strict.false }) 7 | export class ProcessControlModel { 8 | @field({ primary: true, autogenerated: true }) 9 | _id: Types.ObjectId; 10 | 11 | @field() 12 | processEntityType: string; 13 | 14 | @field() 15 | processEntityId: string; 16 | 17 | @field() 18 | processEntityAction: string; 19 | 20 | @field() 21 | previousStatus: string; 22 | 23 | @field() 24 | status: string; 25 | 26 | @field() 27 | args: any; 28 | 29 | @field() 30 | erroMessage: string; 31 | 32 | @field({ itemType: workerParamsDto }) 33 | workerDetails: workerParamsDto; 34 | 35 | @field() 36 | processId: number; 37 | 38 | @field() 39 | serviceName: string; 40 | 41 | @field() 42 | serviceMethodName: string; 43 | 44 | @field() 45 | serviceMethodArgs: Array; 46 | 47 | @field() 48 | responseData: any; 49 | } 50 | export default ProcessControlModel; -------------------------------------------------------------------------------- /tests/models/role.ts: -------------------------------------------------------------------------------- 1 | 2 | export interface IRole { 3 | _id: string; 4 | name : string; 5 | } 6 | 7 | -------------------------------------------------------------------------------- /tests/models/rolemodel.ts: -------------------------------------------------------------------------------- 1 | import {onetomany, manytoone, manytomany, jsonignore, required} from '../../core/decorators'; 2 | import {field, document} from '../../mongoose/decorators'; 3 | import {IRole} from './role'; 4 | import * as UM from './usermodel'; 5 | import {Strict} from '../../mongoose/enums/'; 6 | import {JsonIgnore} from '../../core/enums/jsonignore-enum'; 7 | 8 | @document({ name: 'roles', strict: Strict.false }) 9 | export class RoleModel{ 10 | @field({primary: true, autogenerated: true}) 11 | _id: any; 12 | 13 | @field() 14 | name: any; 15 | 16 | 17 | @field() 18 | @required() 19 | test: any; 20 | 21 | constructor(userDto: IRole) { 22 | this._id = userDto._id; 23 | this.name = userDto.name; 24 | } 25 | } 26 | 27 | export default RoleModel; -------------------------------------------------------------------------------- /tests/models/school.ts: -------------------------------------------------------------------------------- 1 | import Mongoose = require("mongoose"); 2 | import {Types} from 'mongoose'; 3 | import {field, document} from '../../mongoose/decorators'; 4 | import {Strict} from '../../mongoose/enums/'; 5 | import {baseModel} from './baseModel'; 6 | import {teacher} from './teacher'; 7 | import {onetomany, manytoone, manytomany, onetoone} from '../../core/decorators'; 8 | import {StorageType} from '../../core/enums/index'; 9 | 10 | @document({ name: 'school', strict: Strict.true }) 11 | export class school extends baseModel { 12 | @field() 13 | age: string; 14 | 15 | @onetomany({ rel: 'teacher', itemType: teacher, embedded: true, persist: true, eagerLoading: false, deleteCascade: true, properties: ['name'],storageType: StorageType.JSONMAP}) 16 | //@onetomany({ rel: 'teacher', itemType: teacher, embedded: true, persist: true, eagerLoading: false}) 17 | teachers: Array; 18 | } 19 | 20 | export default school; -------------------------------------------------------------------------------- /tests/models/subject.ts: -------------------------------------------------------------------------------- 1 | import Mongoose = require("mongoose"); 2 | import {Types} from 'mongoose'; 3 | import {field, document} from '../../mongoose/decorators'; 4 | import {Strict} from '../../mongoose/enums/'; 5 | import {baseModel} from './baseModel'; 6 | import {topic} from './topic'; 7 | import {onetomany, manytoone, manytomany, onetoone, promisable, IPromisableFetchParam} from '../../core/decorators'; 8 | import { StorageType } from "../../core/enums/index"; 9 | 10 | @document({ name: 'subject', strict: Strict.false }) 11 | export class subject extends baseModel { 12 | 13 | constructor(object?: any) { 14 | super(object); 15 | if (!object || !object._id) { 16 | this.createdDate = Date.now().toString(); 17 | } 18 | // set default properties 19 | this.updatedDate = Date.now().toString(); 20 | } 21 | 22 | @field() 23 | createdDate: string; 24 | 25 | @field() 26 | updatedDate: string; 27 | 28 | // sharding: dynamic collection example 29 | @onetomany({ rel: 'topic', itemType: topic, embedded: true, persist: true, eagerLoading: false, deleteCascade: true, storageType: StorageType.JSONMAP }) 30 | topicOTM: Array; 31 | } 32 | 33 | export default subject; -------------------------------------------------------------------------------- /tests/models/teacher.ts: -------------------------------------------------------------------------------- 1 | import Mongoose = require("mongoose"); 2 | import {Types} from 'mongoose'; 3 | import {subject} from './subject'; 4 | import {field, document, transient} from '../../mongoose/decorators'; 5 | import {Strict} from '../../mongoose/enums/'; 6 | import {onetomany, manytoone, manytomany, onetoone, promisable, IPromisableFetchParam} from '../../core/decorators'; 7 | import {baseModel} from './baseModel'; 8 | import { StorageType } from "../../core/enums/index"; 9 | 10 | @document({ name: 'teacher', strict: Strict.false }) 11 | export class teacher extends baseModel { 12 | 13 | @transient() 14 | isSinger: boolean; 15 | 16 | @onetoone({ rel: 'subject', itemType: subject, embedded: true, persist: true, eagerLoading: false, deleteCascade: true }) 17 | courseOTO: subject; 18 | 19 | @onetoone({ rel: 'subject', itemType: subject, embedded: false, persist: true, eagerLoading: false, deleteCascade: true }) 20 | courseIdOTO: subject; 21 | 22 | @onetomany({ rel: 'subject', itemType: subject, embedded: true, persist: true, eagerLoading: false, deleteCascade: true }) 23 | courseOTM: Array; 24 | 25 | @onetomany({ rel: 'subject', itemType: subject, embedded: false, persist: true, eagerLoading: false, deleteCascade: true }) 26 | courseIdOTM: Array; 27 | 28 | @onetomany({ rel: 'subject', itemType: subject, embedded: false, persist: true, eagerLoading: false, deleteCascade: true }) 29 | physics: Array; 30 | 31 | @promisable({ targetKey: "physics" }) 32 | physics_LAZY: (param?: IPromisableFetchParam) => Promise | any; 33 | 34 | @onetomany({ rel: 'subject', itemType: subject, embedded: false, persist: true, eagerLoading: false, deleteCascade: true }) 35 | physics1: Array; 36 | 37 | @promisable({ targetKey: "physics1" }) 38 | physics1_LAZY: (param?: IPromisableFetchParam) => Promise | any; 39 | 40 | @onetoone({ rel: 'subject', itemType: subject, embedded: true, persist: true, eagerLoading: false, deleteCascade: true }) 41 | physicsOne: subject; 42 | 43 | @onetomany({ rel: 'subject', itemType: subject, embedded: true, persist: true, eagerLoading: false, deleteCascade: true }) 44 | physicsMany: Array; 45 | 46 | @onetomany({ rel: 'subject', itemType: subject, embedded: true, persist: true, eagerLoading: false, storageType: StorageType.JSONMAP, deleteCascade: true }) 47 | jsonCourseOTM: Array; 48 | 49 | } 50 | 51 | export default teacher; -------------------------------------------------------------------------------- /tests/models/topic.ts: -------------------------------------------------------------------------------- 1 | import Mongoose = require("mongoose"); 2 | import {Types} from 'mongoose'; 3 | import {field, document} from '../../mongoose/decorators'; 4 | import {Strict} from '../../mongoose/enums/'; 5 | import {baseModel} from './baseModel'; 6 | import {ShardInfo} from '../../core/interfaces/shard-Info'; 7 | 8 | @document({ name: 'topic', strict: Strict.false }) 9 | export class topic extends baseModel implements ShardInfo { 10 | static count: number = 0; 11 | static enableSharding: boolean = true; 12 | static collectionName: string = 'topic'; 13 | 14 | constructor(object?: any) { 15 | super(object); 16 | if (!object || !object._id) { 17 | this.createdDate = Date.now().toString(); 18 | } 19 | // set default properties 20 | this.updatedDate = Date.now().toString(); 21 | } 22 | 23 | @field() 24 | createdDate: string; 25 | 26 | @field() 27 | updatedDate: string; 28 | 29 | @field() 30 | shardKey: string; 31 | 32 | getShardKey() { 33 | return "shardKey"; 34 | } 35 | 36 | getUniqueId() { 37 | if (topic.enableSharding && this._id) { 38 | let newId = this.shardKey + this._id.toString().substr(1, 23); 39 | return Mongoose.Types.ObjectId(newId); 40 | } 41 | return (new Mongoose.Types.ObjectId()); 42 | } 43 | 44 | getCollectionNameFromSelf() { 45 | let id = this._id.toString(); 46 | if (topic.enableSharding && id) { 47 | return topic.collectionName + id.substr(0, 1); 48 | } 49 | return id; 50 | } 51 | 52 | getCollectionNameFromShardKey(id: string) { 53 | return topic.collectionName; 54 | } 55 | 56 | getAllShardCollectionNames(): Array { 57 | let allColection = [topic.collectionName]; 58 | if (topic.enableSharding) { 59 | for (var i = 0; i < 5; i++) { 60 | allColection.push(topic.collectionName + i); 61 | } 62 | } 63 | return allColection; 64 | } 65 | } 66 | 67 | export default topic; -------------------------------------------------------------------------------- /tests/models/user.ts: -------------------------------------------------------------------------------- 1 | 2 | 3 | export interface IUser{ 4 | _id: string; 5 | name : string; 6 | email : string; 7 | password : string; 8 | age : string; 9 | roles: any; 10 | 11 | /** 12 | * used to set a context to fetch data from db with respect to given viewContext. 13 | * use case: if you do not interested to run acl/security logic in your entity then set this as databse_context 14 | * and write its logic by pass security and fetch all db data objects. 15 | */ 16 | viewContext: number; 17 | 18 | /** 19 | * internal use for caching 20 | */ 21 | cacheContext: number; 22 | entityCache: any; 23 | }; 24 | 25 | 26 | -------------------------------------------------------------------------------- /tests/models/usermodel.ts: -------------------------------------------------------------------------------- 1 | import * as RM from './rolemodel'; 2 | import {onetomany, manytoone, manytomany, jsonignore, required, transient} from '../../core/decorators'; 3 | import {field, document} from '../../mongoose/decorators'; import {IUser} from './user'; 4 | import {Types} from 'mongoose'; 5 | import {Strict} from '../../mongoose/enums/'; 6 | import {RoleModel} from './rolemodel'; 7 | import {JsonIgnore} from '../../core/enums/jsonignore-enum'; 8 | 9 | @document({ name: 'users', strict: Strict.false }) 10 | export class UserModel { 11 | @field({ primary: true, autogenerated: true }) 12 | _id: Types.ObjectId; 13 | 14 | @field() 15 | name: String; 16 | 17 | @field({ itemType: String}) 18 | courses: Array; 19 | 20 | @field() 21 | @required() 22 | email: String; 23 | 24 | @field() 25 | accessToken: String; 26 | 27 | @field() 28 | refreshToken: String; 29 | 30 | @field() 31 | password: String; 32 | 33 | @field() 34 | @transient() 35 | transs: any; 36 | 37 | @field() 38 | @jsonignore() 39 | age: String; 40 | 41 | @manytomany({ rel: 'roles', itemType: RoleModel, embedded: true, persist: true, eagerLoading: true }) 42 | roles: Array; 43 | 44 | @manytoone({ rel: 'roles', itemType: RoleModel, embedded: true, persist: true, eagerLoading: true }) 45 | r: RoleModel; 46 | 47 | } 48 | 49 | export default UserModel; -------------------------------------------------------------------------------- /tests/preauth-service.ts: -------------------------------------------------------------------------------- 1 | import {service} from "../di/decorators"; 2 | import {PrincipalContext} from "../security/auth/principalContext"; 3 | 4 | @service({ singleton: false, serviceName:'preauthservice'}) 5 | export class PreauthService { 6 | 7 | CanEdit(entity: any) { 8 | var user = PrincipalContext.User; 9 | console.log('CanEdit is called'); 10 | return false; 11 | } 12 | 13 | CanEdit1() { 14 | var user = PrincipalContext.User; 15 | console.log('CanEdit is called'); 16 | return true; 17 | } 18 | 19 | CanEditWithParams(entity: any) { 20 | console.log('CanEditWithParams is called'); 21 | return entity.allow; 22 | } 23 | 24 | PostFilter(result: Array) { 25 | return result; 26 | } 27 | } 28 | 29 | export default PreauthService; -------------------------------------------------------------------------------- /tests/repositories/cityRepository.ts: -------------------------------------------------------------------------------- 1 | import {repository} from "../../core/decorators"; 2 | import {city} from '../models/city'; 3 | import {DynamicRepository} from '../../core/dynamic/dynamic-repository'; 4 | 5 | @repository({ path: 'city', model: city }) 6 | export default class CityRepository extends DynamicRepository { 7 | 8 | dotest() { 9 | return [new city()].bulkPost(); 10 | } 11 | 12 | findByName() { 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /tests/repositories/companyRepository.ts: -------------------------------------------------------------------------------- 1 | import {repository} from "../../core/decorators"; 2 | import {company} from '../models/company'; 3 | import {DynamicRepository} from '../../core/dynamic/dynamic-repository'; 4 | 5 | @repository({ path: 'company', model: company }) 6 | export default class CompanyRepository extends DynamicRepository { 7 | } 8 | -------------------------------------------------------------------------------- /tests/repositories/employeeRepository.ts: -------------------------------------------------------------------------------- 1 | import {repository} from "../../core/decorators"; 2 | import {employee} from '../models/employee'; 3 | import {DynamicRepository} from '../../core/dynamic/dynamic-repository'; 4 | 5 | @repository({ path: 'employee', model: employee }) 6 | export default class EmployeeRepository extends DynamicRepository { 7 | } 8 | -------------------------------------------------------------------------------- /tests/repositories/planetRepository.ts: -------------------------------------------------------------------------------- 1 | import {repository} from "../../core/decorators"; 2 | import {DynamicRepository} from "../../core/dynamic/dynamic-repository"; 3 | import {planet} from '../models/planet'; 4 | 5 | @repository({ path: 'planet', model: planet }) 6 | export class PlanetRepository extends DynamicRepository { 7 | 8 | } 9 | export default PlanetRepository; -------------------------------------------------------------------------------- /tests/repositories/processControlRepository.ts: -------------------------------------------------------------------------------- 1 | import { repository } from "../../core/decorators"; 2 | import { DynamicRepository } from '../../core/dynamic/dynamic-repository'; 3 | import { ProcessControlModel } from '../models/processControlModel'; 4 | 5 | @repository({ path: 'processControl', model: ProcessControlModel }) 6 | export class ProcessControlrepository extends DynamicRepository { 7 | } 8 | 9 | export default ProcessControlrepository; -------------------------------------------------------------------------------- /tests/repositories/promisableTestRepository.ts: -------------------------------------------------------------------------------- 1 | import {repository} from "../../core/decorators"; 2 | import {postfilter} from "../../core/decorators/postfilter"; 3 | import {teacher} from '../models/teacher'; 4 | import {DynamicRepository} from '../../core/dynamic/dynamic-repository'; 5 | 6 | @repository({ path: 'promisableTest', model: teacher }) 7 | export default class PromisableTestRepository extends DynamicRepository { 8 | 9 | findOne(id: any): Q.Promise { 10 | 11 | return super.findOne(id).then((result: teacher) => { 12 | let a = null; 13 | return result.physics_LAZY().then(val => { 14 | a = result.physics_LAZY(); 15 | return result.physics1_LAZY().then(val => { 16 | let a = result.physics1_LAZY(); 17 | return result.physics1_LAZY({refresh: true, query: undefined}).then(val => { 18 | return result; 19 | }); 20 | }); 21 | }); 22 | }); 23 | } 24 | 25 | doFindValue(id) { 26 | return this.findOne(id).then((result: teacher) => { 27 | var a = result.physics_LAZY(); 28 | var b = result["__ghostKey_physics"]; 29 | return result; 30 | }); 31 | } 32 | 33 | } -------------------------------------------------------------------------------- /tests/repositories/role.repository.ts: -------------------------------------------------------------------------------- 1 | import {repository} from "../../core/decorators"; 2 | import {RoleModel} from '../models/rolemodel'; 3 | import {DynamicRepository} from '../../core/dynamic/dynamic-repository'; 4 | import {authorize} from '../../core/decorators/authorize'; 5 | import {preauthorize} from '../../core/decorators/preauthorize'; 6 | var Q = require('q'); 7 | 8 | @repository({ path: 'roles', model: RoleModel }) 9 | export default class RoleRepository extends DynamicRepository { 10 | 11 | } 12 | -------------------------------------------------------------------------------- /tests/repositories/schoolRepository.ts: -------------------------------------------------------------------------------- 1 | import {repository} from "../../core/decorators"; 2 | import {school} from '../models/school'; 3 | import {DynamicRepository} from '../../core/dynamic/dynamic-repository'; 4 | 5 | @repository({ path: 'school', model: school }) 6 | export default class SchoolRepository1 extends DynamicRepository { 7 | } 8 | -------------------------------------------------------------------------------- /tests/repositories/subjectRepository.ts: -------------------------------------------------------------------------------- 1 | import {repository, allowanonymous, OptimisticLocking} from "../../core/decorators"; 2 | import {OptimisticLockType} from "../../core/enums/optimisticlock-type"; 3 | import {subject} from '../models/subject'; 4 | import {DynamicRepository} from '../../core/dynamic/dynamic-repository'; 5 | import {authorize} from '../../core/decorators/authorize'; 6 | import {preauthorize} from '../../core/decorators/preauthorize'; 7 | import {postfilter} from '../../core/decorators/postfilter'; 8 | import {AuthorizationRepository} from '../../repositories/authorizationRepository'; 9 | import {entityAction, EntityActionParam} from '../../core/decorators/entityAction'; 10 | import Q = require('q'); 11 | 12 | @repository({ path: 'subject', model: subject }) 13 | export default class CourseRepository extends AuthorizationRepository { 14 | 15 | //@authorize({ roles: ['ROLE_A'] }) 16 | //@postfilter({ serviceName: "preauthservice", methodName: "PostFilter" }) 17 | @preauthorize({ serviceName: "preauthservice", methodName: "CanEdit" })//, params: { id: '#id', entity: '#entity', other: [false] } }) 18 | @allowanonymous() 19 | findAll(): Q.Promise { 20 | return super.findAll(); 21 | } 22 | 23 | //@OptimisticLocking({ type: OptimisticLockType.VERSION }) 24 | put(id: any, obj: any): Q.Promise { 25 | return super.put(id, obj); 26 | } 27 | 28 | @preauthorize({ serviceName: "preauthservice", methodName: "CanEdit1" }) 29 | doProcess(id: any, val: any) { 30 | return 'success'; 31 | } 32 | 33 | @preauthorize({ serviceName: "preauthservice", methodName: "CanEdit1" }) 34 | @postfilter({ serviceName: "preauthservice", methodName: "PostFilter" }) 35 | public findByField(fieldName, value): Q.Promise { 36 | return super.findByField(fieldName, value); 37 | } 38 | 39 | preRead(params: EntityActionParam): Q.Promise { 40 | return Q.when(params); 41 | } 42 | 43 | postRead(params: EntityActionParam): Q.Promise { 44 | let curEntity = params.newPersistentEntity; 45 | if (curEntity.delete) { 46 | return Q.when(undefined); 47 | } 48 | return Q.when(params); 49 | } 50 | 51 | postBulkRead(params: Array): Q.Promise> { 52 | return Q.when(params.filter((entity) => { return !entity.newPersistentEntity.delete })); 53 | } 54 | 55 | preBulkRead(params: Array): Q.Promise> { 56 | return Q.when(params); 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /tests/repositories/teacherRepository.ts: -------------------------------------------------------------------------------- 1 | import {repository} from "../../core/decorators"; 2 | import {DynamicRepository} from "../../core/dynamic/dynamic-repository"; 3 | import {inject} from "../../di/decorators"; 4 | import {entityAction, EntityActionParam} from '../../core/decorators/entityAction'; 5 | import {teacher} from '../models/teacher'; 6 | import {AuthorizationRepository} from '../../repositories/authorizationRepository'; 7 | import * as TeacherService from '../services/teacherService'; 8 | import {Types} from 'mongoose'; 9 | import Q = require('q'); 10 | 11 | @repository({ path: 'teacher', model: teacher }) 12 | export class TeacherRepository extends DynamicRepository { 13 | 14 | @inject(TeacherService) 15 | private _teacherService: TeacherService.TeacherService; 16 | 17 | findOne(id, donotLoadChilds?: boolean): Q.Promise { 18 | return super.findOne(id).then(x => { 19 | return super.findOne(id).then(r => { 20 | let re = r; 21 | return re; 22 | }); 23 | }); 24 | } 25 | 26 | findMany(ids: Array, toLoadEmbededChilds?: boolean): Q.Promise { 27 | return super.findMany(ids, toLoadEmbededChilds); 28 | } 29 | 30 | preRead(params: EntityActionParam): Q.Promise { 31 | return Q.when(params); 32 | } 33 | 34 | postRead(params: EntityActionParam): Q.Promise { 35 | return Q.when(params); 36 | } 37 | 38 | preBulkRead(params: Array): Q.Promise> { 39 | return Q.when(params); 40 | } 41 | 42 | postBulkRead(params: Array): Q.Promise> { 43 | return Q.when(params); 44 | } 45 | 46 | doFindValue(id) { 47 | return this.findOne(id).then((result: teacher) => { 48 | var a = result.physics_LAZY(); 49 | return result; 50 | }); 51 | } 52 | 53 | doAddTeacherWorker(obj: teacher) { 54 | return this._teacherService.addTeacherWorker(obj); 55 | } 56 | 57 | doAddTeacherProcessControl(obj: teacher) { 58 | return this._teacherService.addTeacherProcessControl(obj); 59 | } 60 | 61 | doUpdateTeacherProcessControlAndWorker(obj: teacher) { 62 | return this._teacherService.addTeacherProcessControlAndWorker(obj); 63 | } 64 | 65 | doLongTask() { 66 | return this._teacherService.longTask(); 67 | } 68 | 69 | doUpdateMany(ids, obj) { 70 | return this.bulkPutMany(ids, obj);; 71 | } 72 | 73 | doFindWhere() { 74 | return this.findWhere({ 75 | _id: { 76 | $in: [Types.ObjectId("596a72000f404ef43c8e1a5a"), Types.ObjectId("59a3dee5c21673e8200c6d8f")] 77 | } 78 | }).then(rs => { 79 | return this.findMany([Types.ObjectId("596a72000f404ef43c8e1a5a"), Types.ObjectId("59a3dee5c21673e8200c6d8f")]).then(r => { 80 | return this.delete(Types.ObjectId("596a72000f404ef43c8e1a5a")).then(d => { 81 | return this.findMany([Types.ObjectId("596a72000f404ef43c8e1a5a"), Types.ObjectId("59a3dee5c21673e8200c6d8f")]).then(r => { 82 | let t = r; 83 | return t; 84 | }); 85 | }); 86 | }); 87 | }); 88 | 89 | } 90 | 91 | } 92 | export default TeacherRepository; -------------------------------------------------------------------------------- /tests/repositories/topicRepository.ts: -------------------------------------------------------------------------------- 1 | import {repository} from "../../core/decorators"; 2 | import {topic} from '../models/topic'; 3 | import {DynamicRepository} from '../../core/dynamic/dynamic-repository'; 4 | 5 | @repository({ path: 'topic', model: topic }) 6 | export default class TopicRepository extends DynamicRepository { 7 | doTestFindWhere(query: any) { 8 | return this.findWhere(query); 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /tests/repositories/userRepository.ts: -------------------------------------------------------------------------------- 1 | import {repository} from "../../core/decorators"; 2 | import {UserModel} from '../models/usermodel'; 3 | import {DynamicRepository} from '../../core/dynamic/dynamic-repository'; 4 | import {authorize} from '../../core/decorators/authorize'; 5 | import {preauthorize} from '../../core/decorators/preauthorize'; 6 | var Q = require('q'); 7 | 8 | @repository({ path: 'users', model: UserModel }) 9 | export default class UserRepository extends DynamicRepository { 10 | 11 | //@authorize({ roles: ['ROLE_A'] }) 12 | //@preauthorize({ serviceName: "preauthservice", methodName: "CanEditWithParams", params: { id: '#id', entity: '#entity' } }) 13 | findAll(): Q.Promise { 14 | return super.findAll(); 15 | } 16 | 17 | doFindByName() { 18 | } 19 | 20 | doFindByNameAndAge(name: any): Q.Promise { 21 | return Q.when(name); 22 | //return Q.fcall(this.getCaps(name); 23 | } 24 | 25 | getCaps(name): string { 26 | return name + ' ' + name; 27 | } 28 | 29 | @authorize({ roles: ['ROLE_A'] }) 30 | @preauthorize({ serviceName: "preauthservice", methodName: "CanEdit" })// params: { id: '#id', entity: '#entity' } }) 31 | doProcess(name: string, nam: string, type: any) { 32 | return type; 33 | } 34 | 35 | @preauthorize({ serviceName: "preauthservice", methodName: "CanEditWithParams" })// params: { id: '#id', entity: '#entity', other: [false] } }) 36 | doProcess1(name: boolean) { 37 | return name; 38 | } 39 | 40 | @authorize({roles: ['ROLE_A']}) 41 | public findByField(fieldName, value): Q.Promise { 42 | return super.findByField(fieldName, value); 43 | } 44 | 45 | } 46 | -------------------------------------------------------------------------------- /tests/services/authorizationService.ts: -------------------------------------------------------------------------------- 1 |  2 | import {inject, injectbyname} from '../../di/decorators/inject'; 3 | import {service} from '../../di/decorators/service'; 4 | import {entityAction, EntityActionParam} from '../../core/decorators/entityAction'; 5 | import Q = require('q'); 6 | 7 | @service({ singleton: true, serviceName: 'authorizationService' }) 8 | export class AuthorizationService { 9 | 10 | public canReadActionEntity(params: EntityActionParam) { 11 | return params.newPersistentEntity; 12 | } 13 | 14 | public canReadActionEntities(actionEntities: Array) { 15 | // TODO: need to return tri state entity (new, old, merged) when all get actions 16 | // (findOne, findAll, findwhere, findmany etc) will be implemented in EntityAction annotation 17 | let readableEntities = new Array(); 18 | actionEntities.forEach(entity => { 19 | let qualifiedEntity = this.canReadActionEntity(entity); 20 | qualifiedEntity && readableEntities.push(qualifiedEntity); 21 | }); 22 | 23 | return readableEntities; 24 | } 25 | 26 | canDeleteEntity(entityAction: EntityActionParam) { 27 | let entity = entityAction.oldPersistentEntity; 28 | return Q.when(true); 29 | } 30 | 31 | canSaveEntities(entityActions: Array) { 32 | return Q.when(true); 33 | } 34 | 35 | canSaveEntity(entityAction: EntityActionParam): Q.Promise { 36 | let entity = entityAction.newPersistentEntity; 37 | return Q.when(true); 38 | } 39 | } 40 | 41 | -------------------------------------------------------------------------------- /tests/services/teacherService.ts: -------------------------------------------------------------------------------- 1 | import {inject, injectbyname} from '../../di/decorators/inject'; 2 | import {service} from '../../di/decorators/service'; 3 | import * as teacherRepository from '../repositories/teacherRepository'; 4 | import {Worker, processStartEnd} from '../../core/decorators'; 5 | import {teacher} from '../models/teacher'; 6 | import Q = require('q'); 7 | 8 | @service({ singleton: true, serviceName: 'teacherService' }) 9 | export class TeacherService { 10 | @inject(teacherRepository) 11 | private _teacherRepository: teacherRepository.TeacherRepository; 12 | 13 | @Worker() 14 | addTeacherWorker(obj: teacher) { 15 | return this._teacherRepository.post(obj); 16 | } 17 | 18 | @processStartEnd({ type: 'teacher', action: 'update', indexofArgumentForTargetObject: 0}) 19 | addTeacherProcessControl(obj: teacher) { 20 | return this._teacherRepository.post(obj); 21 | } 22 | 23 | @processStartEnd({ type: 'teacher', action: 'update', indexofArgumentForTargetObject: 0, executeInWorker: true }) 24 | addTeacherProcessControlAndWorker(obj: teacher) { 25 | return this._teacherRepository.post(obj); 26 | } 27 | 28 | @processStartEnd({ type: 'teacher', action: 'update', indexofArgumentForTargetObject: 0, executeInWorker: true }) 29 | longTask() { 30 | let prom = new Promise( 31 | (resolve, reject) => { 32 | let asyncCall = setTimeout(() => { 33 | resolve("fg"); 34 | }, 5000) 35 | } 36 | ); 37 | 38 | return prom.then(s => { 39 | return s; 40 | }); 41 | 42 | 43 | } 44 | } 45 | 46 | export default TeacherService; 47 | 48 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "target": "es6", 4 | "module": "commonjs", 5 | "moduleResolution": "node", 6 | "isolatedModules": false, 7 | "jsx": "react", 8 | "experimentalDecorators": true, 9 | "emitDecoratorMetadata": true, 10 | "declaration": false, 11 | "noImplicitAny": false, 12 | "removeComments": false, 13 | "noLib": false, 14 | "preserveConstEnums": true, 15 | "suppressImplicitAnyIndexErrors": true, 16 | "sourceMap": true 17 | }, 18 | "compileOnSave": true, 19 | "buildOnSave": false, 20 | "atom": { 21 | "rewriteTsconfig": true 22 | }, 23 | "exclude": [ 24 | "node_modules","unit-test" ] 25 | } -------------------------------------------------------------------------------- /tsd.json: -------------------------------------------------------------------------------- 1 | { 2 | "version": "v4", 3 | "repo": "borisyankov/DefinitelyTyped", 4 | "ref": "master", 5 | "path": "typings", 6 | "bundle": "typings/tsd.d.ts", 7 | "installed": { 8 | "node/node.d.ts": { 9 | "commit": "d51cb64351dad6f50a890d8cd2ddb2c2a90e3104" 10 | }, 11 | "serve-static/serve-static.d.ts": { 12 | "commit": "627b6c158b73494c803f36fc2fe00ad75faa8fde" 13 | }, 14 | "express/express.d.ts": { 15 | "commit": "627b6c158b73494c803f36fc2fe00ad75faa8fde" 16 | }, 17 | "mime/mime.d.ts": { 18 | "commit": "627b6c158b73494c803f36fc2fe00ad75faa8fde" 19 | }, 20 | "q/Q.d.ts": { 21 | "commit": "627b6c158b73494c803f36fc2fe00ad75faa8fde" 22 | }, 23 | "mongoose/mongoose.d.ts": { 24 | "commit": "faa49cc68025118355b677b936892435b9be7247" 25 | }, 26 | "linq/linq.3.0.3-Beta4.d.ts": { 27 | "commit": "3030a4be536b6530c06b80081f1333dc0de4d703" 28 | }, 29 | "form-data/form-data.d.ts": { 30 | "commit": "d0db7bef6269878af5d8e183081693ca3c73953c" 31 | }, 32 | "jasmine/jasmine.d.ts": { 33 | "commit": "9f0f926a12026287b5a4a229e5672c01e7549313" 34 | }, 35 | "winston/winston.d.ts": { 36 | "commit": "d51cb64351dad6f50a890d8cd2ddb2c2a90e3104" 37 | }, 38 | "lodash/lodash.d.ts": { 39 | "commit": "d51cb64351dad6f50a890d8cd2ddb2c2a90e3104" 40 | }, 41 | "sequelize/sequelize.d.ts": { 42 | "commit": "d51cb64351dad6f50a890d8cd2ddb2c2a90e3104" 43 | }, 44 | "validator/validator.d.ts": { 45 | "commit": "d51cb64351dad6f50a890d8cd2ddb2c2a90e3104" 46 | }, 47 | "bluebird/bluebird-2.0.d.ts": { 48 | "commit": "d51cb64351dad6f50a890d8cd2ddb2c2a90e3104" 49 | } 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /tslint.json: -------------------------------------------------------------------------------- 1 | { 2 | "rules": { 3 | "chai-vague-errors": true, 4 | "class-name": true, 5 | "curly": true, 6 | "eofline": false, 7 | "export-name": true, 8 | "forin": true, 9 | "indent": [true, "spaces"], 10 | "jquery-deferred-must-complete": true, 11 | "label-position": true, 12 | "label-undefined": true, 13 | "max-line-length": [ true, 140 ], 14 | "missing-jsdoc": true, 15 | "missing-optional-annotation": true, 16 | "mocha-avoid-only": true, 17 | "no-arg": true, 18 | "no-backbone-get-set-outside-model": true, 19 | "no-banned-terms": true, 20 | "no-bitwise": true, 21 | "no-console": [ 22 | true, 23 | "debug", 24 | "info", 25 | "log", 26 | "time", 27 | "timeEnd", 28 | "trace" 29 | ], 30 | "no-constant-condition": true, 31 | "no-construct": true, 32 | "no-constructor-vars": true, 33 | "no-control-regex": true, 34 | "no-cookies": true, 35 | "no-debugger": true, 36 | "no-delete-expression": true, 37 | "no-disable-auto-sanitization": true, 38 | "no-document-write": true, 39 | "no-duplicate-case": true, 40 | "no-duplicate-key": true, 41 | "no-duplicate-parameter-names": true, 42 | "no-duplicate-variable": true, 43 | "no-empty": true, 44 | "no-empty-interfaces": true, 45 | "no-eval": true, 46 | "no-exec-script": true, 47 | "no-for-in": true, 48 | "no-function-constructor-with-string-args": true, 49 | "no-function-expression": true, 50 | "no-http-string": [ true, "http://www.example.com/?.*", "http://www.examples.com/?.*" ], 51 | "no-increment-decrement": true, 52 | "no-invalid-regexp": true, 53 | "no-missing-visibility-modifiers": true, 54 | "no-multiline-string": true, 55 | "no-multiple-var-decl": true, 56 | "no-octal-literal": true, 57 | "no-regex-spaces": true, 58 | "no-reserved-keywords": true, 59 | "no-sparse-arrays": true, 60 | "no-string-based-set-immediate": true, 61 | "no-string-based-set-interval": true, 62 | "no-string-based-set-timeout": true, 63 | "no-string-literal": true, 64 | "no-switch-case-fall-through": true, 65 | "no-trailing-whitespace": true, 66 | "no-unnecessary-bind": true, 67 | "no-unnecessary-semicolons": true, 68 | "no-unreachable": true, 69 | "no-unused-expression": true, 70 | "no-unused-imports": true, 71 | "no-unused-variable": true, 72 | "no-use-before-declare": true, 73 | "no-var-requires": true, 74 | "no-with-statement": true, 75 | "one-line": [ 76 | true, 77 | "check-open-brace", 78 | "check-catch", 79 | "check-else", 80 | "check-whitespace" 81 | ], 82 | "prefer-array-literal": true, 83 | "promise-must-complete": true, 84 | "quotemark": [ true, "single" ], 85 | "react-no-dangerous-html": true, 86 | "semicolon": [ true ], 87 | "trailing-comma": true, 88 | "triple-equals": [ true, "allow-null-check" ], 89 | "use-isnan": true, 90 | "use-named-parameter": true, 91 | "use-strict": [false], 92 | "valid-typeof": true, 93 | "variable-name": true, 94 | "whitespace": [ 95 | true, 96 | "check-branch", 97 | "check-decl", 98 | "check-operator", 99 | "check-separator", 100 | "check-type" 101 | ] 102 | } 103 | } -------------------------------------------------------------------------------- /typings.json: -------------------------------------------------------------------------------- 1 | { 2 | "globalDependencies": { 3 | "jasmine": "registry:dt/jasmine#2.5.0+20161025102649", 4 | "mongodb": "registry:dt/mongodb#2.1.0+20161110150902", 5 | "mongoose": "registry:dt/mongoose#4.5.9+20161010180758", 6 | "node": "registry:dt/node#6.0.0+20161110151007", 7 | "q": "registry:dt/q#0.0.0+20161004185634", 8 | "winston": "registry:dt/winston#0.0.0+20161108133445" 9 | }, 10 | "dependencies": { 11 | "express": "registry:npm/express#4.14.0+20160925001530", 12 | "linq": "registry:npm/linq#3.0.5+20160322032703", 13 | "sequelize": "registry:npm/sequelize#3.0.0+20161101121248" 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /unit-test/InitializeModels.ts: -------------------------------------------------------------------------------- 1 | require('reflect-metadata/reflect'); 2 | import * as models from './models/testModels'; 3 | import {Decorators} from '../core/constants'; 4 | import {DecoratorType} from '../core/enums'; 5 | import {Strict} from '../mongoose/enums'; 6 | import {MetaUtils} from "../core/metadata/utils"; 7 | 8 | export function initializeModels1() { 9 | var obj1 = new models.student(); 10 | var obj2 = new models.subject(); 11 | var obj3 = new models.teacher(); 12 | var obj4 = new models.division(); 13 | } 14 | 15 | export function initializeModels() { 16 | //MetaUtils.addMetaData(models.student.prototype, Decorators.DOCUMENT, DecoratorType.CLASS, { name: models.student.name, strict: Strict.true }); 17 | //MetaUtils.addMetaData(models.student.prototype, Decorators.FIELD, DecoratorType.PROPERTY, { primary: true, autogenerated: true }, '_id'); 18 | //MetaUtils.addMetaData(models.student.prototype, Decorators.FIELD, DecoratorType.PROPERTY, null, 'name'); 19 | //MetaUtils.addMetaData(models.student.prototype, Decorators.ONETOMANY, DecoratorType.PROPERTY, { rel: models.subject.name, itemType: models.subject, embedded: true }, 'subjects'); 20 | //MetaUtils.addMetaData(models.student.prototype, Decorators.FIELD, DecoratorType.PROPERTY, null, 'addresses'); 21 | 22 | //MetaUtils.addMetaData(models.subject, Decorators.DOCUMENT, DecoratorType.CLASS, { name: models.subject.name, strict: Strict.true }); 23 | //MetaUtils.addMetaData(models.subject, Decorators.FIELD, DecoratorType.PROPERTY, { primary: true, autogenerated: true }, '_id'); 24 | //MetaUtils.addMetaData(models.subject, Decorators.FIELD, DecoratorType.PROPERTY, null, 'name'); 25 | 26 | //MetaUtils.addMetaData(models.teacher, Decorators.DOCUMENT, DecoratorType.CLASS, { name: models.teacher.name, strict: Strict.true }); 27 | //MetaUtils.addMetaData(models.teacher, Decorators.FIELD, DecoratorType.PROPERTY, { primary: true, autogenerated: true }, '_id'); 28 | //MetaUtils.addMetaData(models.teacher, Decorators.FIELD, DecoratorType.PROPERTY, null, 'name'); 29 | 30 | //MetaUtils.addMetaData(models.division, Decorators.DOCUMENT, DecoratorType.CLASS, { name: models.division.name, strict: Strict.true }); 31 | //MetaUtils.addMetaData(models.division, Decorators.FIELD, DecoratorType.PROPERTY, { primary: true, autogenerated: true }, '_id'); 32 | //MetaUtils.addMetaData(models.division, Decorators.FIELD, DecoratorType.PROPERTY, null, 'name'); 33 | //MetaUtils.addMetaData(models.division, Decorators.ONETOMANY, DecoratorType.PROPERTY, { rel: models.student.name, itemType: models.student, embedded: true }, 'students'); 34 | }; -------------------------------------------------------------------------------- /unit-test/OutputFiles/file.txt: -------------------------------------------------------------------------------- 1 | Hello -------------------------------------------------------------------------------- /unit-test/OutputFiles/file1.txt: -------------------------------------------------------------------------------- 1 | unit-test/OutputFiles/file1.txt -------------------------------------------------------------------------------- /unit-test/Sample/GlobalObject.ts: -------------------------------------------------------------------------------- 1 |  2 | var i: number = 0; 3 | 4 | export function GetCounterValue(): number { 5 | return 1; 6 | } 7 | 8 | export function GetSquare(val: number): number { 9 | return (val * val); 10 | } -------------------------------------------------------------------------------- /unit-test/Sample/MockService.ts: -------------------------------------------------------------------------------- 1 | export class MockAuthService { 2 | 3 | authenticate() { 4 | console.log('mock service message'); 5 | } 6 | } -------------------------------------------------------------------------------- /unit-test/Sample/SampleClassA.ts: -------------------------------------------------------------------------------- 1 | import * as global from './GlobalObject'; 2 | import {B} from './SampleClassB'; 3 | import {service, inject} from '../../di/decorators'; 4 | import {AuthService} from '../../security/auth/auth-service'; 5 | 6 | export class A { 7 | @inject() 8 | private authService: AuthService; 9 | 10 | constructor(B: B) { 11 | console.log(B.getName()); 12 | } 13 | 14 | nestedGlobalFunctionCall() { 15 | var b_obj = new B(); 16 | console.log(global.GetCounterValue()); 17 | } 18 | 19 | nestedGlobalFunctionWithParam(val: number) { 20 | console.log(global.GetSquare(val)); 21 | } 22 | 23 | authenticate(): boolean { 24 | this.authService.authenticate(); 25 | return true; 26 | } 27 | } -------------------------------------------------------------------------------- /unit-test/Sample/SampleClassB.ts: -------------------------------------------------------------------------------- 1 | import {router} from "../../core/exports/router"; 2 | import * as global from './GlobalObject'; 3 | var Q = require('q'); 4 | 5 | export class B { 6 | 7 | counter: number = 0; 8 | private name; 9 | 10 | constructor(name?: string) { 11 | this.name = name; 12 | this.addRoutes(); 13 | } 14 | 15 | getName(): string { 16 | //this.privatePrint(); 17 | console.log(global.GetCounterValue()); 18 | return "class B"; 19 | } 20 | 21 | private addRoutes() { 22 | router.get('/', 23 | this.ensureLoggedIn(), 24 | (req, res) => { 25 | console.log('callback is called'); 26 | res.set("Content-Type", "application/json"); 27 | this.counter++; 28 | var result = {}; 29 | result['name'] = this.name; 30 | res.send(result); 31 | }); 32 | } 33 | 34 | private ensureLoggedIn() { 35 | return function (req, res, next) { 36 | next(); 37 | } 38 | } 39 | 40 | // should not be tested seperately 41 | private privatePrint() { 42 | console.log("private function from B"); 43 | } 44 | 45 | asyncWithQnBind(): Q.Promise { 46 | return Q.nbind(this.asyncEvaluation, this)({}) 47 | .then(result => { 48 | console.log('nbind executed'); 49 | return result; 50 | }); 51 | } 52 | 53 | asyncEvaluation(): Q.Promise { 54 | var prom = Q.fcall(this.wait).then(x => { 55 | console.log('async completed'); 56 | x = !x; 57 | return x; 58 | }); 59 | console.log('asyncEvaluation() is called'); 60 | return prom; 61 | } 62 | 63 | private wait(): boolean { 64 | var stop = new Date().getTime(); 65 | console.log('wait() is called'); 66 | //while (new Date().getTime() < stop + time) { 67 | // ; 68 | //} 69 | return true; 70 | } 71 | } 72 | -------------------------------------------------------------------------------- /unit-test/controllers/format.ts: -------------------------------------------------------------------------------- 1 | ////describe('Sample description', function () { 2 | 3 | // beforeEach(function () { 4 | 5 | // }); 6 | 7 | // it('executing task 1', function () { 8 | 9 | // }); 10 | 11 | // it('executing task 2', function () { 12 | 13 | // }); 14 | //}); -------------------------------------------------------------------------------- /unit-test/controllers/usercontroller.spec.ts: -------------------------------------------------------------------------------- 1 | 2 | describe("GET Server", function(){ 3 | describe("GET /users", function() { 4 | it("returns status code 200", function(done) { 5 | request.get(base_url, function(error, response, body) { 6 | expect(response.statusCode).toBe(402); 7 | done(); 8 | }); 9 | }); 10 | }); 11 | }); 12 | -------------------------------------------------------------------------------- /unit-test/dto/blogDto.ts: -------------------------------------------------------------------------------- 1 | export class blogDto{ 2 | blogName: string; 3 | } -------------------------------------------------------------------------------- /unit-test/dto/format.ts: -------------------------------------------------------------------------------- 1 | ////describe('Sample description', function () { 2 | 3 | // beforeEach(function () { 4 | 5 | // }); 6 | 7 | // it('executing task 1', function () { 8 | 9 | // }); 10 | 11 | // it('executing task 2', function () { 12 | 13 | // }); 14 | //}); -------------------------------------------------------------------------------- /unit-test/models/blog.ts: -------------------------------------------------------------------------------- 1 | import Mongoose = require("mongoose"); 2 | import {Types} from 'mongoose'; 3 | import {Strict} from '../../mongoose/enums/'; 4 | import {field, document} from '../../mongoose/decorators'; 5 | 6 | @document({ name: 'blog', strict: Strict.throw }) 7 | export class blog{ 8 | schema(): {} { 9 | return { 10 | '_id': Mongoose.Schema.Types.ObjectId, 11 | 'name': String 12 | }; 13 | } 14 | @field({ primary: true, autogenerated: true }) 15 | _id: Types.ObjectId; 16 | 17 | @field() 18 | name: string; 19 | 20 | } 21 | export default blog; -------------------------------------------------------------------------------- /unit-test/models/course.ts: -------------------------------------------------------------------------------- 1 | import Mongoose = require("mongoose"); 2 | import {Types} from 'mongoose'; 3 | import {field, document} from '../../mongoose/decorators'; 4 | import {Strict} from '../../mongoose/enums/'; 5 | 6 | @document({ name: 'course', strict: Strict.throw }) 7 | export class course { 8 | schema(): {} { 9 | return { 10 | '_id': Mongoose.Schema.Types.ObjectId, 11 | 'name': String 12 | }; 13 | } 14 | 15 | @field({ primary: true, autogenerated: true }) 16 | _id: Types.ObjectId; 17 | 18 | @field() 19 | name: String; 20 | } 21 | 22 | export default course; -------------------------------------------------------------------------------- /unit-test/models/format.ts: -------------------------------------------------------------------------------- 1 | ////describe('Sample description', function () { 2 | 3 | // beforeEach(function () { 4 | 5 | // }); 6 | 7 | // it('executing task 1', function () { 8 | 9 | // }); 10 | 11 | // it('executing task 2', function () { 12 | 13 | // }); 14 | //}); -------------------------------------------------------------------------------- /unit-test/models/student.ts: -------------------------------------------------------------------------------- 1 | import Mongoose = require("mongoose"); 2 | import {Types} from 'mongoose'; 3 | import {course} from './course'; 4 | import {field, document} from '../../mongoose/decorators'; 5 | import {Strict} from '../../mongoose/enums/'; 6 | import {onetomany, manytoone, manytomany, onetoone} from '../../core/decorators'; 7 | 8 | @document({ name: 'student', strict: Strict.throw }) 9 | export class student { 10 | schema(): {} { 11 | return { 12 | '_id': Mongoose.Schema.Types.ObjectId, 13 | 'name': String, 14 | 'courses': Mongoose.Schema.Types.Mixed 15 | }; 16 | } 17 | 18 | @field({ primary: true, autogenerated: true }) 19 | _id: Types.ObjectId; 20 | 21 | @field() 22 | name: String; 23 | 24 | @onetoone({ rel: 'course', itemType: course, embedded: true, persist: true, eagerLoading: false }) 25 | courseOTO: course; 26 | 27 | @onetoone({ rel: 'course', itemType: course, embedded: false, persist: true, eagerLoading: false }) 28 | courseIdOTO: course; 29 | 30 | @onetomany({ rel: 'course', itemType: course, embedded: true, persist: true, eagerLoading: false }) 31 | courseOTM: Array; 32 | 33 | @onetomany({ rel: 'course', itemType: course, embedded: false, persist: true, eagerLoading: false }) 34 | courseIdOTM: Array; 35 | 36 | @manytoone({ rel: 'course', itemType: course, embedded: true, persist: true, eagerLoading: false }) 37 | courseMTO: course; 38 | 39 | @manytoone({ rel: 'course', itemType: course, embedded: false, persist: true, eagerLoading: false }) 40 | courseIdMTO: course; 41 | 42 | @manytomany({ rel: 'course', itemType: course, embedded: true, persist: true, eagerLoading: false }) 43 | courseMTM: Array; 44 | 45 | @manytomany({ rel: 'course', itemType: course, embedded: false, persist: true, eagerLoading: false }) 46 | courseIdMTM: Array; 47 | 48 | @manytomany({ rel: 'course', itemType: course, embedded: true, persist: true, eagerLoading: false, deleteCascade: true }) 49 | courseDelCascase: Array; 50 | } 51 | 52 | export default student; -------------------------------------------------------------------------------- /unit-test/models/testModels.ts: -------------------------------------------------------------------------------- 1 | import {Types} from 'mongoose'; 2 | 3 | //@document({ name: 'students', strict: Strict.true }) 4 | export class student { 5 | _id: Types.ObjectId; 6 | 7 | //@field() 8 | name: string; 9 | addresses: Array; 10 | 11 | //@onetomany({ rel: 'subjects', itemType: subject, embedded: true }) 12 | subjects: Array; 13 | } 14 | 15 | //@document({ name: 'subjects', strict: Strict.true }) 16 | export class subject { 17 | _id: string; 18 | name: string; 19 | } 20 | 21 | export class teacher { 22 | _id: string; 23 | name: string; 24 | } 25 | 26 | //@document({ name: 'divisions', strict: Strict.true }) 27 | export class division { 28 | //@field({ primary: true, autogenerated: true }) 29 | _id: string; 30 | 31 | //@field() 32 | name: string; 33 | 34 | //@onetomany({ rel: 'students', itemType: student, embedded: true }) 35 | students: Array; 36 | } -------------------------------------------------------------------------------- /unit-test/repository/blogRepository.ts: -------------------------------------------------------------------------------- 1 | import Q = require('q'); 2 | import {repository} from "../../core/decorators/repository"; 3 | import {inject} from "../../di/decorators/inject"; 4 | import {blog} from "../models/blog"; 5 | import {blogServiceImpl} from "../services/blogServiceImpl"; 6 | 7 | @repository({path:"blogRepo",model:blog}) 8 | export class BlogRepository { 9 | 10 | // @inject(blogServiceImpl) 11 | // blogServiceImpl1: blogServiceImpl; 12 | 13 | findByField(field: string, value: string): Q.Promise { 14 | return Q.fcall(() => { 15 | var blogObject = { 16 | "_id": "56b07218fc2e4f4427e9ff8f", 17 | "name": "john", 18 | "post": "welcome to Node-Data" 19 | } 20 | return blogObject; 21 | }); 22 | } 23 | 24 | // doWorkerTask(){ 25 | // var filePath="/Users/asishs/Projects/Node-Data/Enhancement_On_Node_Data/Node-Data/spec/OutputFiles/file.txt"; 26 | // this.blogServiceImpl1.writeBlog(filePath,"Hello"); 27 | // } 28 | 29 | } -------------------------------------------------------------------------------- /unit-test/repository/user-repository-mock.ts: -------------------------------------------------------------------------------- 1 | import Q = require('q'); 2 | export class UserRepositoryMock { 3 | 4 | findByName() { 5 | } 6 | 7 | findByField(field: string, value: string): Q.Promise { 8 | return Q.fcall(() => { 9 | var userObject = { 10 | "_id": "56b07218fc2e4f4427e9ff8f", 11 | "name": "pratikv1", 12 | "email": "abc11@xyz.com", 13 | "age": 30, 14 | "password": "dsfs", 15 | "__v": 0, 16 | "refreshToken": "56b07218fc2e4f4427e9ff8f.b97bd654e5a6603ca442c8bfb6185a017d4b66a96f3aebb3a92d384dda5e95c88830ca7e157557ce", 17 | "accessToken": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpZCI6IjU2YjA3MjE4ZmMyZTRmNDQyN2U5ZmY4ZiIsImlhdCI6MTQ1NjgzMzUxNSwiZXhwIjoxNDU2ODMzNjM1fQ.WMYbdJeCBfj_t-_Tk94ys5K6LGCIW0pfmhitdC-Hs_U", 18 | "id": "56b07218fc2e4f4427e9ff8f", 19 | "roles": [ 20 | { 21 | "__v": 0, 22 | "name": "ROLE_ADMIN", 23 | "_id": "56ea7d4379be4a40221380a4" 24 | }, 25 | { 26 | "__v": 0, 27 | "name": "ROLE_USER", 28 | "_id": "56ea7d4b79be4a40221380a5" 29 | } 30 | ] 31 | } 32 | return userObject; 33 | }); 34 | } 35 | 36 | public getEntityType() { 37 | return this; 38 | } 39 | 40 | public put(a,b) { 41 | 42 | } 43 | 44 | getUser() { 45 | var userObject = { 46 | "_id": "56b07218fc2e4f4427e9ff8f", 47 | "name": "pratikv1", 48 | "email": "abc11@xyz.com", 49 | "age": 30, 50 | "password": "dsfs", 51 | "__v": 0, 52 | "refreshToken": "56b07218fc2e4f4427e9ff8f.b97bd654e5a6603ca442c8bfb6185a017d4b66a96f3aebb3a92d384dda5e95c88830ca7e157557ce", 53 | "accessToken": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpZCI6IjU2YjA3MjE4ZmMyZTRmNDQyN2U5ZmY4ZiIsImlhdCI6MTQ1NjgzMzUxNSwiZXhwIjoxNDU2ODMzNjM1fQ.WMYbdJeCBfj_t-_Tk94ys5K6LGCIW0pfmhitdC-Hs_U", 54 | "id": "56b07218fc2e4f4427e9ff8f", 55 | "rolenames": "ROLE_ADMIN" , 56 | "roles": [ 57 | { 58 | "__v": 0, 59 | "name": "ROLE_ADMIN", 60 | "_id": "56ea7d4379be4a40221380a4" 61 | }, 62 | { 63 | "__v": 0, 64 | "name": "ROLE_USER", 65 | "_id": "56ea7d4b79be4a40221380a5" 66 | } 67 | ] 68 | } 69 | return userObject; 70 | } 71 | } 72 | -------------------------------------------------------------------------------- /unit-test/sample-tests/GlobalObject.ts: -------------------------------------------------------------------------------- 1 |  2 | var i: number = 0; 3 | 4 | export function GetCounterValue(): number { 5 | return 1; 6 | } 7 | 8 | export function GetSquare(val: number): number { 9 | return (val * val); 10 | } -------------------------------------------------------------------------------- /unit-test/sample-tests/MockService.ts: -------------------------------------------------------------------------------- 1 |  2 | export class MockAuthService { 3 | 4 | authenticate() { 5 | console.log('mock service message'); 6 | } 7 | } -------------------------------------------------------------------------------- /unit-test/sample-tests/SampleClassA.ts: -------------------------------------------------------------------------------- 1 | import * as global from './GlobalObject'; 2 | import {B} from './SampleClassB'; 3 | import {inject} from '../../di/decorators'; 4 | import {AuthService} from '../../security/auth/auth-service'; 5 | 6 | export class A { 7 | @inject() 8 | private authService: AuthService; 9 | 10 | constructor(B: B) { 11 | console.log(B.getName()); 12 | } 13 | 14 | nestedGlobalFunctionCall() { 15 | var b_obj = new B(); 16 | console.log(global.GetCounterValue()); 17 | } 18 | 19 | nestedGlobalFunctionWithParam(val: number) { 20 | console.log(global.GetSquare(val)); 21 | } 22 | 23 | authenticate(): boolean { 24 | this.authService.authenticate(); 25 | return true; 26 | } 27 | } -------------------------------------------------------------------------------- /unit-test/sample-tests/SampleClassB.ts: -------------------------------------------------------------------------------- 1 | import * as global from './GlobalObject'; 2 | 3 | export class B { 4 | constructor() { 5 | } 6 | 7 | getName(): string { 8 | //this.privatePrint(); 9 | console.log(global.GetCounterValue()); 10 | return "class B"; 11 | } 12 | 13 | // should not be tested seperately 14 | private privatePrint() { 15 | console.log("private function from B"); 16 | } 17 | } -------------------------------------------------------------------------------- /unit-test/sample-tests/format.spec.ts: -------------------------------------------------------------------------------- 1 | // spyon should be created for all the external dependencies 2 | // each spyon should be checked with number of paramaters and type of parameters and return type if any 3 | require('reflect-metadata/reflect'); 4 | 5 | import {AuthService} from '../../security/auth/auth-service'; 6 | import {MockAuthService} from './MockService'; 7 | import {Container} from '../../di'; 8 | import * as global from './GlobalObject'; 9 | import {A} from './SampleClassA'; 10 | import {B} from './SampleClassB'; 11 | 12 | describe('sample', function () { 13 | 14 | var getCounterValue = global.GetCounterValue; 15 | var a_obj, b_obj; 16 | 17 | beforeEach(() => { 18 | // Before creating object, mock the service first 19 | spyOn(Container, 'resolve').and.callFake((val) => { 20 | switch (val) { 21 | case AuthService: 22 | return new MockAuthService(); 23 | } 24 | }); 25 | 26 | b_obj = new B(); 27 | spyOn(b_obj, "getName").and.callThrough(); 28 | spyOn(global, "GetCounterValue").and.callThrough(); 29 | spyOn(global, "GetSquare").and.callFake((val) => { 30 | console.log(val + val); 31 | }); 32 | }); 33 | 34 | it('check getName() of B object is called', function () { 35 | a_obj = new A(b_obj); 36 | expect(b_obj.getName).toHaveBeenCalled(); 37 | }); 38 | 39 | it('check GetCounterValue() of global is called', function () { 40 | // restoring the original definition so that we can again spyon the function with different behavior 41 | global.GetCounterValue = getCounterValue; 42 | spyOn(global, "GetCounterValue").and.returnValue(10); 43 | 44 | a_obj = new A(b_obj); 45 | a_obj.nestedGlobalFunctionCall(); 46 | expect(global.GetCounterValue).toHaveBeenCalled(); 47 | }); 48 | 49 | it('check GetSquare() of global is called which takes paramaterized value', function () { 50 | a_obj = new A(b_obj); 51 | a_obj.nestedGlobalFunctionWithParam(10); 52 | expect(global.GetSquare).toHaveBeenCalled(); 53 | }); 54 | 55 | it('dependency injection for Authservice using mock object', function () { 56 | a_obj = new A(b_obj); 57 | var val = a_obj.authenticate(); 58 | expect(val).toEqual(true); 59 | }); 60 | }); -------------------------------------------------------------------------------- /unit-test/services/MockAuthService.ts: -------------------------------------------------------------------------------- 1 | import {AuthService} from '../../security/auth/auth-service'; 2 | import {UserRepositoryMock} from '../../unit-test/repository/user-repository-mock'; 3 | import {User} from '../../security/auth/user'; 4 | import {UserDetails} from '../../security/auth/user-details'; 5 | import Q = require('q'); 6 | export class MockAuthServiceNew { 7 | 8 | } -------------------------------------------------------------------------------- /unit-test/services/MockService.ts: -------------------------------------------------------------------------------- 1 | import {AuthService} from '../../security/auth/auth-service'; 2 | import {UserRepositoryMock} from '../../unit-test/repository/user-repository-mock'; 3 | import {User} from '../../security/auth/user'; 4 | import {UserDetails} from '../../security/auth/user-details'; 5 | import Q = require('q'); 6 | export class MockAuthService { 7 | 8 | authenticate() { 9 | console.log('mock service message'); 10 | } 11 | 12 | mockRepo = new UserRepositoryMock(); 13 | loadUserByUsername(userName: string): Q.Promise { 14 | var userDetail: UserDetails; 15 | return this.mockRepo.findByField("name", "a").then((user) => { 16 | userDetail = new User(user.name, user.password, user); 17 | return userDetail; 18 | }); 19 | }; 20 | loadUserById(id: number): Q.Promise { 21 | var userDetail: UserDetails; 22 | return this.mockRepo.findByField("name", "a").then((user) => { 23 | userDetail = new User(user.name, user.password, user); 24 | return userDetail; 25 | }); 26 | }; 27 | loadUserByField(field: any, value: any): Q.Promise { 28 | var userDetail: UserDetails; 29 | return this.mockRepo.findByField("name", "a").then((user) => { 30 | userDetail = new User(user.name, user.password, user); 31 | return userDetail; 32 | }); 33 | }; 34 | createNewUser(userObject): Q.Promise { 35 | var userDetail: UserDetails; 36 | return this.mockRepo.findByField("name", "a").then((user) => { 37 | userDetail = new User(user.name, user.password, user); 38 | return userDetail; 39 | }); 40 | }; 41 | updateExistingUser(id, userObject): Q.Promise { 42 | var userDetail: UserDetails; 43 | return this.mockRepo.findByField("name", "a").then((user) => { 44 | userDetail = new User(user.name, user.password, user); 45 | return userDetail; 46 | }); 47 | }; 48 | } -------------------------------------------------------------------------------- /unit-test/services/blogServiceImpl.ts: -------------------------------------------------------------------------------- 1 | import {BlogRepository} from '../repository/blogRepository'; 2 | import {blog} from '../models/blog'; 3 | import Q = require('q'); 4 | import {Worker} from '../../core/decorators/workerAssociation'; 5 | import {BlogService} from './interface/blogService' 6 | import {service} from '../../di/decorators/service'; 7 | import fs = require('fs'); 8 | import {PrincipalContext} from '../../security/auth/principalContext'; 9 | 10 | @service({ 'singleton': true, 'serviceName': 'blogService' }) 11 | export class blogServiceImpl implements BlogService{ 12 | ///blogRepo= new BlogRepository(); 13 | 14 | 15 | //@Worker({name: 'workerThread', workerParams:{workerName:'', serviceName:'' ,servicemethodName:'', arguments:["john"]}}) 16 | @Worker({name: 'workerThread'}) 17 | checkApplicationContext(fileName: any): Q.Promise { 18 | var blog: blog; 19 | console.log("Value returned...... ******** ......."); 20 | console.log("Appliation Context Value...... ******** ......." + 21 | JSON.stringify(PrincipalContext.getSession())); 22 | var argument=PrincipalContext.getSession().get('workerParams').arguments; 23 | console.log("Value in principal context: "+ argument); 24 | return Q.nbind(fs.writeFile,fs)(fileName,argument).then(ret=>{ 25 | return ret; 26 | }); 27 | // return this.blogRepo.findByField("name", value).then((blog) => { 28 | // return blog.name; 29 | // }); 30 | }; 31 | 32 | 33 | // @Worker({name: 'workerThread'}) 34 | // @Worker({name: 'workerThread', workerParams:{workerName:'', serviceName:'' ,servicemethodName:'', 35 | // arguments:["unit-test/OutputFiles/file.txt","Hello"]}}) 36 | @Worker() 37 | writeBlog(fileName: any, data: any): Q.Promise { 38 | var blog: blog; 39 | console.log("file name:" + fileName + " and data: "+ data); 40 | console.log("Value returned...... ******** ......."); 41 | return Q.nbind(fs.writeFile,fs)(fileName,data).then(ret=>{ 42 | console.log('file writing error'+ret); 43 | return ret; 44 | }); 45 | }; 46 | } -------------------------------------------------------------------------------- /unit-test/services/interface/blogService.ts: -------------------------------------------------------------------------------- 1 | import Q = require('q'); 2 | 3 | 4 | export interface BlogService { 5 | checkApplicationContext(field: any, value: any): Q.Promise; 6 | writeBlog(fileName: any, data: any): Q.Promise; 7 | } -------------------------------------------------------------------------------- /views/authlogin.ejs: -------------------------------------------------------------------------------- 1 |
2 |
3 | 4 |
5 |
6 |
7 | 8 | 9 |
10 |
11 | 12 |
13 | 16 |
17 | -------------------------------------------------------------------------------- /views/home.ejs: -------------------------------------------------------------------------------- 1 | <% if (!user) { %> 2 |

Welcome! Please log in.

3 | <% } else { %> 4 |

Hello, <%= user.username %>. View your profile.

5 | <% } %> -------------------------------------------------------------------------------- /views/login.ejs: -------------------------------------------------------------------------------- 1 |
2 |
3 | 4 |
5 |
6 |
7 | 8 | 9 |
10 |
11 | 12 |
13 | 16 |
17 | --------------------------------------------------------------------------------