diff --git a/README.md b/README.md index 70d0cef533ac..f7bb17d3171d 100644 --- a/README.md +++ b/README.md @@ -64,7 +64,6 @@ midway is comprised of many specialized packages. This repository contains all t | [`midway-init`](https://github.com/midwayjs/midway/tree/master/packages/midway-init) | [![npm (scoped)](https://img.shields.io/npm/v/midway-init.svg?maxAge=86400)](https://github.com/midwayjs/midway/tree/master/midway-init/CHANGELOG.md) | [![Dependency Status](https://david-dm.org/midwayjs/midway.svg?path=packages/midway-init)](https://david-dm.org/midwayjs/midway.svg?path=packages/midway-init) | [![devDependency Status](https://david-dm.org/midwayjs/midway/dev-status.svg?path=packages/midway-init)](https://david-dm.org/midwayjs/midway?path=packages/midway-init#info=devDependencies) | | [`midway-bin`](https://github.com/midwayjs/midway/tree/master/packages/midway-bin) | [![npm (scoped)](https://img.shields.io/npm/v/midway-bin.svg?maxAge=86400)](https://github.com/midwayjs/midway/tree/master/midway-bin/CHANGELOG.md) | [![Dependency Status](https://david-dm.org/midwayjs/midway.svg?path=packages/midway-bin)](https://david-dm.org/midwayjs/midway.svg?path=packages/midway-bin) | [![devDependency Status](https://david-dm.org/midwayjs/midway/dev-status.svg?path=packages/midway-bin)](https://david-dm.org/midwayjs/midway?path=packages/midway-bin#info=devDependencies) | | [`midway-schedule`](https://github.com/midwayjs/midway/tree/master/packages/midway-schedule) | [![npm (scoped)](https://img.shields.io/npm/v/midway-schedule.svg?maxAge=86400)](https://github.com/midwayjs/midway/tree/master/midway-schedule/CHANGELOG.md) | [![Dependency Status](https://david-dm.org/midwayjs/midway.svg?path=packages/midway-schedule)](https://david-dm.org/midwayjs/midway.svg?path=packages/midway-schedule) | [![devDependency Status](https://david-dm.org/midwayjs/midway/dev-status.svg?path=packages/midway-schedule)](https://david-dm.org/midwayjs/midway?path=packages/midway-schedule#info=devDependencies) | -| [`injection`](https://github.com/midwayjs/midway/tree/master/packages/context) | [![npm (scoped)](https://img.shields.io/npm/v/injection.svg?maxAge=86400)](https://github.com/midwayjs/midway/tree/master/context/CHANGELOG.md) | [![Dependency Status](https://david-dm.org/midwayjs/midway.svg?path=packages/context)](https://david-dm.org/midwayjs/midway.svg?path=packages/context) | [![devDependency Status](https://david-dm.org/midwayjs/midway/dev-status.svg?path=packages/context)](https://david-dm.org/midwayjs/midway?path=packages/context#info=devDependencies) | Globally: [![Build Status](https://img.shields.io/travis/midwayjs/midway/master.svg?style=flat)](https://travis-ci.org/midwayjs/midway) [![devDependency Status](https://david-dm.org/midwayjs/midway/dev-status.svg)](https://david-dm.org/midwayjs/midway#info=devDependencies) diff --git a/packages/context/.autod.conf.js b/packages/context/.autod.conf.js deleted file mode 100644 index d7c3cb24536a..000000000000 --- a/packages/context/.autod.conf.js +++ /dev/null @@ -1,19 +0,0 @@ -'use strict'; - -module.exports = { - write: true, - prefix: '^', - devprefix: '^', - exclude: [ - 'test/fixtures', - 'examples', - 'docs', - 'run', - ], - dep: [ - ], - devdep: [ - ], - keep: [ - ] -}; diff --git a/packages/context/CHANGELOG.md b/packages/context/CHANGELOG.md deleted file mode 100644 index cbbe2fdfad46..000000000000 --- a/packages/context/CHANGELOG.md +++ /dev/null @@ -1,251 +0,0 @@ -# Change Log - -All notable changes to this project will be documented in this file. -See [Conventional Commits](https://conventionalcommits.org) for commit guidelines. - -# [1.1.0](https://github.com/midwayjs/midway/compare/v1.0.5...v1.1.0) (2019-01-23) - -**Note:** Version bump only for package injection - - - - - -## [1.0.2](https://github.com/midwayjs/midway/compare/v1.0.1...v1.0.2) (2018-12-26) - -**Note:** Version bump only for package injection - - - - - -## [1.0.1](https://github.com/midwayjs/midway/compare/v1.0.0...v1.0.1) (2018-12-23) - -**Note:** Version bump only for package injection - - - - - -# [0.7.0](https://github.com/midwayjs/midway/compare/v0.6.5...v0.7.0) (2018-12-09) - - -### Bug Fixes - -* Boolean type resolution error in xml ([b3a35e4](https://github.com/midwayjs/midway/commit/b3a35e4)) - - - - - -## [0.6.5](https://github.com/midwayjs/midway/compare/v0.6.4...v0.6.5) (2018-11-27) - -**Note:** Version bump only for package injection - - - - - -## [0.6.4](https://github.com/midwayjs/midway/compare/v0.6.3...v0.6.4) (2018-11-21) - -**Note:** Version bump only for package injection - - - - - -## [0.6.3](https://github.com/midwayjs/midway/compare/v0.6.2...v0.6.3) (2018-11-20) - -**Note:** Version bump only for package injection - - - - - -## [0.6.2](https://github.com/midwayjs/midway/compare/v0.6.1...v0.6.2) (2018-11-20) - - -### Bug Fixes - -* not only inject properties that declared on the property ([b1fe4e2](https://github.com/midwayjs/midway/commit/b1fe4e2)) - - - - - -# [0.6.0](https://github.com/midwayjs/midway/compare/v0.4.7...v0.6.0) (2018-11-15) - -**Note:** Version bump only for package injection - - - - - - -# [0.5.0](https://github.com/midwayjs/midway/compare/v0.4.5...v0.5.0) (2018-11-15) - -**Note:** Version bump only for package injection - - -## [0.4.6](https://github.com/midwayjs/midway/compare/v0.4.5...v0.4.6) (2018-11-14) - - -### Bug Fixes - -* fix dep map generator err in constructor inject ([9d7abe6](https://github.com/midwayjs/midway/commit/9d7abe6)) -* fix set app use defineProperty ([d94d5e9](https://github.com/midwayjs/midway/commit/d94d5e9)) - - - -## [0.4.5](https://github.com/midwayjs/midway/compare/v0.4.4...v0.4.5) (2018-11-05) - - -### Bug Fixes - -* fix app.root ([33d730c](https://github.com/midwayjs/midway/commit/33d730c)) - - - - - - -## [0.4.1](https://github.com/midwayjs/midway/compare/v0.4.0...v0.4.1) (2018-09-28) - - - - -**Note:** Version bump only for package injection - - -## [0.3.8](https://github.com/midwayjs/midway/compare/v0.3.7...v0.3.8) (2018-09-25) - - - - -**Note:** Version bump only for package injection - - -## [0.3.2](https://github.com/midwayjs/midway/compare/v0.3.1...v0.3.2) (2018-08-30) - - - - -**Note:** Version bump only for package injection - - -## [0.3.1](https://github.com/midwayjs/midway/compare/v0.3.0...v0.3.1) (2018-08-30) - - - - -**Note:** Version bump only for package injection - - -# [0.3.0](https://github.com/midwayjs/midway/compare/v0.2.10...v0.3.0) (2018-08-29) - - -### Features - -* add request scope for injection ([50782ed](https://github.com/midwayjs/midway/commit/50782ed)) - - - - - -## [0.2.10](https://github.com/midwayjs/midway/compare/v0.2.9...v0.2.10) (2018-08-20) - -**Note:** Version bump only for package injection - - - - - - -## [0.2.7](https://github.com/midwayjs/midway/compare/v0.2.6...v0.2.7) (2018-08-10) - - -### Bug Fixes - -* bind method definition missing ([79685db](https://github.com/midwayjs/midway/commit/79685db)) - - - - - - -## [0.2.4](https://github.com/midwayjs/midway/compare/v0.2.3...v0.2.4) (2018-08-06) - - - - -**Note:** Version bump only for package injection - - -## [0.2.3](https://github.com/midwayjs/midway/compare/v0.2.2...v0.2.3) (2018-08-03) - - -### Bug Fixes - -* remove nyc config ([58f99de](https://github.com/midwayjs/midway/commit/58f99de)) - - - - - -## [0.2.2](https://github.com/midwayjs/midway/compare/v0.2.1...v0.2.2) (2018-08-03) - - -### Bug Fixes - -* source map include local path ([a8acb01](https://github.com/midwayjs/midway/commit/a8acb01)) - - - - - -## [0.2.1](https://github.com/midwayjs/midway/compare/v0.2.0...v0.2.1) (2018-08-03) - - - - -**Note:** Version bump only for package injection - - -# [0.2.0](https://github.com/midwayjs/midway/compare/v0.1.6...v0.2.0) (2018-08-01) - - - - -**Note:** Version bump only for package injection - - -## [0.1.6](https://github.com/midwayjs/midway/compare/v0.1.5...v0.1.6) (2018-07-30) - - - - -**Note:** Version bump only for package injection - - -# [0.2.0-alpha.1663751b](https://github.com/midwayjs/midway/compare/v0.1.5...v0.2.0-alpha.1663751b) (2018-07-30) - - - - -**Note:** Version bump only for package injection - - -## [0.1.5](https://github.com/midwayjs/midway/compare/v0.1.4...v0.1.5) (2018-07-30) - - - - -**Note:** Version bump only for package injection - - -## [0.1.4](https://github.com/midwayjs/midway/compare/v0.1.3...v0.1.4) (2018-07-30) - - - - -**Note:** Version bump only for package injection diff --git a/packages/context/README.md b/packages/context/README.md deleted file mode 100644 index a8438b3f830d..000000000000 --- a/packages/context/README.md +++ /dev/null @@ -1,67 +0,0 @@ -# Injection - -[![Package Quality](http://npm.packagequality.com/shield/injection.svg)](http://packagequality.com/#?package=injection) -[![PRs Welcome](https://img.shields.io/badge/PRs-welcome-brightgreen.svg)](https://github.com/midwayjs/midway/pulls) - -Injection is a powerful inversion of control container that is widely used in the midway framework and brings good user experience. - -## Installation - -```bash -$ npm install injection reflect-metadata --save -``` - -Node.js >= 8.0.0 required. - -> Injection requires TypeScript >= 2.0 and the experimentalDecorators, emitDecoratorMetadata, types and lib compilation options in your tsconfig.json file. - -```json -{ - "compilerOptions": { - "target": "ES2017", - "lib": ["es2017", "dom"], - "types": ["reflect-metadata"], - "module": "commonjs", - "moduleResolution": "node", - "experimentalDecorators": true, - "emitDecoratorMetadata": true - } -} -``` - -## Getting Started - -```ts - -import {container, provide, inject} from 'injection'; - -@provide('userModel') -class UserModel { - -} - -@provide('userService') -class UserService { - - @inject() - private userModel; - - async getUser(uid) { - // TODO - } -} - - -const container = new Container(); -container.bind(UserService); -container.bind(UserModel); - -const userService = await container.getAsync('userService'); -const data = await userService.getUser(123); -``` - -Document: [https://midwayjs.org/midway/ioc.html](https://midwayjs.org/midway/ioc.html#) - -## License - -[MIT]((http://github.com/midwayjs/midway/blob/master/LICENSE)) diff --git a/packages/context/benchmark/index.ts b/packages/context/benchmark/index.ts deleted file mode 100644 index 1a9784dbdbd1..000000000000 --- a/packages/context/benchmark/index.ts +++ /dev/null @@ -1,30 +0,0 @@ -import {Container, RequestContainer} from '../src'; -import {UserService} from './singleton-scope/userService'; -import {UserController} from './singleton-scope/userController'; - -const Benchmark = require('benchmark'); - -const suite = new Benchmark.Suite; - -const applicationContext = new Container(); -applicationContext.bind(UserService); -applicationContext.bind(UserController); - -// add tests -suite - .add('RequestContext#get', async () => { - const requestContext = new RequestContainer({}, applicationContext); - await requestContext.getAsync(UserController); - }) - .add('Container#get', async () => { - await applicationContext.getAsync(UserController); - }) - // add listeners - .on('cycle', function(event) { - console.log(String(event.target)); - }) - .on('complete', function() { - console.log('Fastest is ' + this.filter('fastest').map('name')); - }) - // run async - .run({'async': true}); diff --git a/packages/context/benchmark/req-scope/userController.ts b/packages/context/benchmark/req-scope/userController.ts deleted file mode 100644 index 7e4da2e76769..000000000000 --- a/packages/context/benchmark/req-scope/userController.ts +++ /dev/null @@ -1,20 +0,0 @@ -import {UserService} from './userService'; -import {scope, inject, provide, ScopeEnum} from '../../src/'; - -@provide() -@scope(ScopeEnum.Request) -export class UserController { - - @inject('ctx') - ctx; - - @inject() - userService: UserService; - - async index() { - const { ctx } = this; - ctx.body = await this.userService.getUsers(); - ctx.status = 200; - } - -} diff --git a/packages/context/benchmark/req-scope/userService.ts b/packages/context/benchmark/req-scope/userService.ts deleted file mode 100644 index f703f7898ad9..000000000000 --- a/packages/context/benchmark/req-scope/userService.ts +++ /dev/null @@ -1,14 +0,0 @@ -import {provide, scope, ScopeEnum} from '../../src/'; - -@provide() -@scope(ScopeEnum.Request) -export class UserService { - - async getUsers() { - return new Promise(resolve => { - setTimeout(() => { - resolve(['harry', 'jiakun.du']); - }, 100); - }); - } -} diff --git a/packages/context/benchmark/requestContainer.ts b/packages/context/benchmark/requestContainer.ts deleted file mode 100644 index e544f88522cf..000000000000 --- a/packages/context/benchmark/requestContainer.ts +++ /dev/null @@ -1,52 +0,0 @@ -import 'reflect-metadata'; -import {Container, IContainer} from '../src'; - -export class RequestContainer extends Container { - - applicationContext: IContainer; - - constructor(ctx, applicationContext) { - super(); - this.registerObject('ctx', ctx); - this.parent = applicationContext; - this.applicationContext = applicationContext; - } - - get(identifier: any, args?: any) { - if (typeof identifier !== 'string') { - identifier = this.getIdentifier(identifier); - } - if (this.registry.hasObject(identifier)) { - return this.registry.getObject(identifier); - } - const definition = this.applicationContext.registry.getDefinition(identifier); - if(definition && definition.isRequestScope()) { - // create object from applicationContext definition for requestScope - return this.resolverFactory.create(definition, args); - } - - if (this.parent) { - return this.parent.get(identifier, args); - } - } - - async getAsync(identifier: any, args?: any) { - if (typeof identifier !== 'string') { - identifier = this.getIdentifier(identifier); - } - if (this.registry.hasObject(identifier)) { - return this.registry.getObject(identifier); - } - - const definition = this.applicationContext.registry.getDefinition(identifier); - if(definition && definition.isRequestScope()) { - // create object from applicationContext definition for requestScope - return await this.resolverFactory.createAsync(definition, args); - } - - if (this.parent) { - return await this.parent.getAsync(identifier, args); - } - } - -} diff --git a/packages/context/benchmark/singleton-scope/userController.ts b/packages/context/benchmark/singleton-scope/userController.ts deleted file mode 100644 index 6dc92f49c180..000000000000 --- a/packages/context/benchmark/singleton-scope/userController.ts +++ /dev/null @@ -1,17 +0,0 @@ -import {UserService} from './userService'; -import {scope, inject, provide, ScopeEnum} from '../../src/'; - -@provide() -@scope(ScopeEnum.Singleton) -export class UserController { - - @inject() - userService: UserService; - - async index() { - let ctx = {body: null, status: 200}; - ctx.body = await this.userService.getUsers(); - ctx.status = 200; - } - -} diff --git a/packages/context/benchmark/singleton-scope/userService.ts b/packages/context/benchmark/singleton-scope/userService.ts deleted file mode 100644 index 72f6282cffc4..000000000000 --- a/packages/context/benchmark/singleton-scope/userService.ts +++ /dev/null @@ -1,14 +0,0 @@ -import {provide, scope, ScopeEnum} from '../../src/'; - -@provide() -@scope(ScopeEnum.Singleton) -export class UserService { - - async getUsers() { - return new Promise(resolve => { - setTimeout(() => { - resolve(['harry', 'jiakun.du']); - }, 100); - }); - } -} diff --git a/packages/context/package.json b/packages/context/package.json deleted file mode 100644 index fcc13f492042..000000000000 --- a/packages/context/package.json +++ /dev/null @@ -1,49 +0,0 @@ -{ - "name": "injection", - "version": "1.1.0", - "description": "A New IoC Container For All Node.js Application", - "main": "dist/index", - "typings": "dist/index.d.ts", - "scripts": { - "build": "npm run lint && midway-bin build -c", - "start": "npm run build && node dist/index", - "lint": "../../node_modules/.bin/tslint --format prose -c ../../tslint.json src/**/*.ts test/**/*.ts", - "test": "midway-bin test --ts", - "cov": "midway-bin cov --ts", - "ci": "npm run test", - "autod": "midway-bin autod" - }, - "keywords": [ - "midway", - "IoC" - ], - "files": [ - "dist", - "src" - ], - "license": "MIT", - "devDependencies": { - "benchmark": "^2.1.4", - "chai": "^4.1.2", - "midway-bin": "^1.1.0", - "sdk-base": "^3.4.0", - "sinon": "^7.2.2", - "supertest": "^3.1.0" - }, - "dependencies": { - "camelcase": "^5.0.0", - "co": "^4.6.0", - "debug": "^4.1.1", - "graphviz": "^0.0.8", - "is-type-of": "^1.2.1", - "lodash": "^4.17.11", - "reflect-metadata": "^0.1.12", - "uuid": "^3.3.2", - "xmldom": "^0.1.27" - }, - "author": "Harry Chen ", - "repository": { - "type": "git", - "url": "http://github.com/midwayjs/midway.git" - } -} diff --git a/packages/context/src/annotation/index.ts b/packages/context/src/annotation/index.ts deleted file mode 100644 index f5ea5d6ecbe1..000000000000 --- a/packages/context/src/annotation/index.ts +++ /dev/null @@ -1,3 +0,0 @@ -export { async, init, destroy, scope, autowire, initOrGetObjectDefProps } from './objectDef'; -export { provide } from './provide'; -export { inject } from './inject'; diff --git a/packages/context/src/annotation/inject.ts b/packages/context/src/annotation/inject.ts deleted file mode 100644 index d01a808b2a73..000000000000 --- a/packages/context/src/annotation/inject.ts +++ /dev/null @@ -1,41 +0,0 @@ -import {tagParameter, tagProperty} from '../utils/decorator'; -import {INJECT_TAG} from '..'; -import {Metadata} from '../utils/Metadata'; -import {ObjectIdentifier} from '../interfaces'; - -const STRIP_COMMENTS = /((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg; -const ARGUMENT_NAMES = /([^\s,]+)/g; - -function getParamNames(func) { - const fnStr = func.toString().replace(STRIP_COMMENTS, ''); - let result = fnStr.slice(fnStr.indexOf('(') + 1, fnStr.indexOf(')')).match(ARGUMENT_NAMES); - if (result === null) { - result = []; - } - return result; -} - -function inject(identifier?: ObjectIdentifier) { - return function (target: any, targetKey: string, index?: number): void { - - if (typeof index === 'number') { - if (!identifier) { - const args = getParamNames(target); - if (target.length === args.length && index < target.length) { - identifier = args[index]; - } - } - const metadata = new Metadata(INJECT_TAG, identifier); - tagParameter(target, targetKey, index, metadata); - } else { - if (!identifier) { - identifier = targetKey; - } - const metadata = new Metadata(INJECT_TAG, identifier); - tagProperty(target, targetKey, metadata); - } - }; -} - -export {inject}; - diff --git a/packages/context/src/annotation/objectDef.ts b/packages/context/src/annotation/objectDef.ts deleted file mode 100644 index 1adc53dc462a..000000000000 --- a/packages/context/src/annotation/objectDef.ts +++ /dev/null @@ -1,55 +0,0 @@ -import 'reflect-metadata'; -import { OBJ_DEF_CLS } from '../utils/metaKeys'; -import { Scope } from '../interfaces'; -import { ObjectDefinitionOptions, ScopeEnum } from '..'; - -const debug = require('debug')('midway:context:obj_def'); - -function attachObjectDefProps(target, options) { - let data = initOrGetObjectDefProps(target); - Reflect.defineMetadata(OBJ_DEF_CLS, Object.assign(data, options), target); - return target; -} - -export function initOrGetObjectDefProps(target): ObjectDefinitionOptions { - let result = Reflect.hasMetadata(OBJ_DEF_CLS, target); - if (!result) { - Reflect.defineMetadata(OBJ_DEF_CLS, {}, target); - } - return Reflect.getMetadata(OBJ_DEF_CLS, target); -} - -export function async() { - return function (target: any): void { - debug(`set [async] property in [${target.name}]`); - return attachObjectDefProps(target, {isAsync: true}); - }; -} - -export function init() { - return function (target: any, propertyKey: string): void { - debug(`set [init] property in [${target.constructor.name}]`); - return attachObjectDefProps(target.constructor, {initMethod: propertyKey}); - }; -} - -export function destroy() { - return function (target: any, propertyKey: string): void { - debug(`set [destroy] property in [${target.constructor.name}]`); - return attachObjectDefProps(target.constructor, {destroyMethod: propertyKey}); - }; -} - -export function scope(scope: Scope = ScopeEnum.Singleton) { - return function (target: any): void { - debug(`set [scope] property in [${target.name}]`); - return attachObjectDefProps(target, {scope}); - }; -} - -export function autowire(isAutowire: boolean = true) { - return function (target: any): void { - debug(`set [autowire] property in [${target.name}]`); - return attachObjectDefProps(target, {isAutowire}); - }; -} diff --git a/packages/context/src/annotation/provide.ts b/packages/context/src/annotation/provide.ts deleted file mode 100644 index d56b99e4e55b..000000000000 --- a/packages/context/src/annotation/provide.ts +++ /dev/null @@ -1,30 +0,0 @@ -import 'reflect-metadata'; -import {DUPLICATED_INJECTABLE_DECORATOR} from '../utils/errMsg'; -import { initOrGetObjectDefProps, TAGGED_CLS } from '..'; -import {ObjectIdentifier, TagClsMetadata} from '../interfaces'; - -const camelCase = require('camelcase'); - -function provide(identifier?: ObjectIdentifier) { - return function (target: any) { - if (Reflect.hasOwnMetadata(TAGGED_CLS, target)) { - throw new Error(DUPLICATED_INJECTABLE_DECORATOR); - } - - if (!identifier) { - identifier = camelCase(target.name); - } - - Reflect.defineMetadata(TAGGED_CLS, { - id: identifier, - originName: target.name, - }, target); - - // init property here - initOrGetObjectDefProps(target); - - return target; - }; -} - -export {provide}; diff --git a/packages/context/src/base/Configuration.ts b/packages/context/src/base/Configuration.ts deleted file mode 100644 index 51518eaab551..000000000000 --- a/packages/context/src/base/Configuration.ts +++ /dev/null @@ -1,206 +0,0 @@ -import { format } from 'util'; -import * as _ from 'lodash'; -import { ObjectIdentifier, - IConfiguration -} from '../interfaces'; - -export class BaseConfiguration implements IConfiguration { - get size(): number { - return 0; - } - - keys(): ObjectIdentifier[] { - return null; - } - - get(key: ObjectIdentifier, ...args: any[]): any { - return null; - } - - dup(key: ObjectIdentifier): any { - return null; - } - - has(key: ObjectIdentifier): boolean { - return false; - } - - set(key: ObjectIdentifier, value: any): any { - return null; - } - - putAll(props: IConfiguration): void { - - } - - stringPropertyNames(): ObjectIdentifier[] { - return this.keys(); - } - - getProperty(key: ObjectIdentifier, defaultValue?: any): any { - if (this.has(key)) { - return this.get(key); - } - - return defaultValue; - } - - addProperty(key: ObjectIdentifier, value: any): void { - this.set(key, value); - } - - setProperty(key: ObjectIdentifier, value: any): any { - return this.set(key, value); - } - - clear(): void { } - - toJSON(): Object { - return null; - } - - clone(): IConfiguration { - return null; - } -} - -export class BasicConfiguration extends BaseConfiguration { - private _config = new Map(); - get size(): number { - return this._config.size; - } - - keys(): ObjectIdentifier[] { - const keys = []; - const iter = this._config.keys(); - for (let key of iter) { - keys.push(key); - } - return keys; - } - - get(key: ObjectIdentifier, ...args: any[]): any { - if (args && args.length > 0) { - args.unshift(this._config.get(key)); - return format.apply(null, args); - } - return this._config.get(key); - } - - dup(key: ObjectIdentifier): any { - if (!this.has(key)) { - return null; - } - return JSON.parse(JSON.stringify(this._config.get(key))); - } - - has(key: ObjectIdentifier): boolean { - return this._config.has(key); - } - - set(key: ObjectIdentifier, value: any): any { - const origin = this._config.get(key); - this._config.set(key, value); - return origin; - } - - putAll(props: IConfiguration): void { - const keys = props.keys(); - for (let i = 0; i < keys.length; i++) { - const key = keys[i]; - if (typeof this._config.get(key) === 'object') { - this._config.set(key, - _.defaultsDeep(props.get(key), this._config.get(key))); - } else { - this._config.set(key, props.get(key)); - } - } - } - - clear(): void { - this._config.clear(); - } - - toJSON(): Object { - const oo = {}; - for (let key of this._config.keys()) { - oo[key] = JSON.parse(JSON.stringify(this._config.get(key))); - } - return oo; - } -} - -export class ObjectConfiguration extends BaseConfiguration { - private _config = {}; - - get size(): number { - return this.keys().length; - } - - keys(): ObjectIdentifier[] { - return _.keys(this._config); - } - - get(key: ObjectIdentifier, ...args: any[]): any { - if (args && args.length > 0) { - args.unshift(_.get(this._config, key)); - return format.apply(null, args); - } - return _.get(this._config, key); - } - - dup(key: ObjectIdentifier): any { - if (!this.has(key)) { - return null; - } - return JSON.parse(JSON.stringify(_.get(this._config, key))); - } - - has(key: ObjectIdentifier): boolean { - return _.has(this._config, key); - } - - set(key: ObjectIdentifier, value: any): any { - const origin = this.get(key); - _.set(this._config, key, value); - return origin; - } - - putAll(props: IConfiguration): void { - const keys = props.keys(); - for (let i = 0; i < keys.length; i++) { - const key = keys[i]; - if (typeof this._config[key] === 'object') { - this.set(key, - _.defaultsDeep(props.get(key), this._config[key])); - } else { - this.set(key, props.get(key)); - } - } - } - - putObject(props: Object, needClone = false) { - if (needClone) { - const tmp = _.cloneDeep(props); - _.defaultsDeep(tmp, this._config); - this._config = tmp; - } else { - _.defaultsDeep(props, this._config); - this._config = props; - } - } - - clear(): void { - this._config = {}; - } - - toJSON(): Object { - return JSON.parse(JSON.stringify(this._config)); - } - - clone(): IConfiguration { - const cfg = new ObjectConfiguration(); - cfg.putObject(this.toJSON()); - return cfg; - } -} diff --git a/packages/context/src/base/FunctionDefinition.ts b/packages/context/src/base/FunctionDefinition.ts deleted file mode 100644 index 1d65ee6caaac..000000000000 --- a/packages/context/src/base/FunctionDefinition.ts +++ /dev/null @@ -1,120 +0,0 @@ -import { ObjectCreator } from './ObjectCreator'; -import { - IApplicationContext, - IConfiguration, - IManagedInstance, - IObjectCreator, - IObjectDefinition, - ObjectIdentifier, - Scope -} from '../interfaces'; -import { ScopeEnum } from './Scope'; -import { ManagedValue } from '..'; - -class FunctionWrapperCreator extends ObjectCreator { - - context; - - constructor(definition: IObjectDefinition, context: IApplicationContext) { - super(definition); - this.context = context; - } - - doConstruct(Clzz: any, args: Array = []): any { - if (!Clzz) { - return null; - } - - if (args.length) { - return Clzz((args[0]).value); - } else { - return Clzz(this.context); - } - } - - async doConstructAsync(Clzz: any, args: Array = []): Promise { - if (!Clzz) { - return null; - } - if (args.length) { - return await Clzz(args[0]); - } else { - return await Clzz(this.context); - } - } -} - -export class FunctionDefinition implements IObjectDefinition { - - context; - - constructor(context: IApplicationContext) { - this.context = context; - this.creator = new FunctionWrapperCreator(this, context); - } - - constructMethod: string; - constructorArgs: IManagedInstance[] = []; - creator: IObjectCreator; - dependsOn: ObjectIdentifier[]; - destroyMethod: string; - export: string; - id: string; - name: string; - initMethod: string; - path: any; - properties: IConfiguration; - // 函数工厂创建的对象默认不需要自动装配 - protected _autowire: boolean = false; - protected _scope: Scope = ScopeEnum.Singleton; - - set autowire(autowire: boolean) { - this._autowire = autowire; - } - - getAttr(key: ObjectIdentifier): any { - } - - hasAttr(key: ObjectIdentifier): boolean { - return false; - } - - hasConstructorArgs(): boolean { - return false; - } - - hasDependsOn(): boolean { - return false; - } - - isAsync(): boolean { - return true; - } - - isAutowire(): boolean { - return this._autowire; - } - - isDirect(): boolean { - return false; - } - - isExternal(): boolean { - return false; - } - - set scope(scope: Scope) { - this._scope = scope; - } - - isSingletonScope(): boolean { - return this._scope === ScopeEnum.Singleton; - } - - isRequestScope(): boolean { - return this._scope === ScopeEnum.Request; - } - - setAttr(key: ObjectIdentifier, value: any): void { - } -} diff --git a/packages/context/src/base/MessageSource.ts b/packages/context/src/base/MessageSource.ts deleted file mode 100644 index 4eff2242e9a7..000000000000 --- a/packages/context/src/base/MessageSource.ts +++ /dev/null @@ -1,85 +0,0 @@ -import { format } from 'util'; -import * as _ from 'lodash'; -import { - Locale, - IResource, - IMessageSource -} from '../interfaces'; - -/** - * 多语言支持实现 - * 支持文件夹载入以及文件载入 - */ -export class MessageSource extends Map implements IMessageSource { - private _defaultLocale: Locale = null; - - constructor(defaultLocale: Locale) { - super(); - this._defaultLocale = defaultLocale; - } - - async load(locale: Locale, res: IResource): Promise { - if (res.isFile()) { - let messages = await res.getContentAsJSON(); - - if (this.has(locale)) { - _.assign(this.get(locale), messages); - } else { - this.set(locale, messages); - } - } - - if (res.isDir()) { - const resources = await res.getSubResources(); - for (let i = 0; i < resources.length; i++) { - await this.load(locale, resources[i]); - } - } - } - - async loadUseFileName(res: IResource): Promise { - if (res.isFile()) { - let messages = await res.getContentAsJSON(); - const locale = res.name; - - if (this.has(locale)) { - _.assign(this.get(locale), messages); - } else { - this.set(locale, messages); - } - } - - if (res.isDir()) { - const resources = await res.getSubResources(); - for (let i = 0; i < resources.length; i++) { - await this.loadUseFileName(resources[i]); - } - } - } - - getMessage(code: string, - args?: any[], - defaultMessage?: string, - locale?: Locale): string { - - let messages; - if (locale) { - messages = this.get(locale); - } else { - messages = this.get(this._defaultLocale); - } - - if (!messages) { - return null; - } - - if (!messages[code]) { - return defaultMessage; - } - - if (args && args.length > 0) { - return format(messages[code], args); - } - return messages[code]; - } -} diff --git a/packages/context/src/base/ObjectCreator.ts b/packages/context/src/base/ObjectCreator.ts deleted file mode 100644 index 5c30c0d49f12..000000000000 --- a/packages/context/src/base/ObjectCreator.ts +++ /dev/null @@ -1,165 +0,0 @@ -import * as is from 'is-type-of'; -import * as co from 'co'; -import { - IObjectDefinition, - IObjectCreator -} from '../interfaces'; - -export class ObjectCreator implements IObjectCreator { - protected definition: IObjectDefinition; - - constructor(definition: IObjectDefinition) { - this.definition = definition; - } - /** - * 加载对象class - * @returns {class} Clzz对象的Class - */ - load(): any { - let Clzz = null; - if (typeof this.definition.path === 'string') { - // 解析xml结果 默认 path = '' 需要兼容处理掉 - if (!this.definition.path) { - return Clzz; - } - const path = this.definition.path; - if (this.definition.export) { - Clzz = require(path)[this.definition.export]; - } else { - Clzz = require(path); - } - } else { - // if it is class and return direct - Clzz = this.definition.path; - } - return Clzz; - } - /** - * 构建对象实例 - * @param Clzz 对象class,通过load加载 - * @param args 对象初始化参数 - * @returns {any} 返回创建的对象实例 - */ - doConstruct(Clzz: any, args?: any): any { - if (!Clzz) { - return Object.create(null); - } - - if (this.definition.isDirect()) { - return Clzz; - } - let inst; - if (this.definition.constructMethod) { - inst = Clzz[this.definition.constructMethod].apply(Clzz, args); - } else { - inst = Reflect.construct(Clzz, args); - } - return inst; - } - /** - * 异步构造对象 - * @param Clzz 对象class,通过load加载 - * @param args 对象初始化参数 - * @returns {any} 返回创建的对象实例 - */ - async doConstructAsync(Clzz: any, args?: any): Promise { - if (!Clzz) { - return Object.create(null); - } - if (this.definition.isDirect()) { - return Clzz; - } - let inst; - if (this.definition.constructMethod) { - const fn = Clzz[this.definition.constructMethod]; - if (is.generatorFunction(fn)) { - inst = await co.wrap(fn).apply(Clzz, args); - } else if (is.asyncFunction(fn)) { - inst = await fn.apply(Clzz, args); - } else { - inst = fn.apply(Clzz, args); - } - } else { - inst = Reflect.construct(Clzz, args); - } - return inst; - } - /** - * 调用对象初始化方法进行初始化 - * @param obj 对象,由doConstruct返回 - * @returns {void} - */ - doInit(obj: any): void { - const inst = obj; - // after properties set then do init - if (this.definition.initMethod && inst[this.definition.initMethod]) { - if (is.generatorFunction(inst[this.definition.initMethod]) - || is.asyncFunction(inst[this.definition.initMethod])) { - - throw new Error(`${this.definition.id} not valid by context.get, Use context.getAsync instead!`); - } else { - const rt = inst[this.definition.initMethod].call(inst); - if (is.promise(rt)) { - throw new Error(`${this.definition.id} not valid by context.get, Use context.getAsync instead!`); - } - } - } - } - /** - * 调用对象初始化方法进行初始化 - * @param obj 对象,由doConstructAsync返回 - * @returns {void} - */ - async doInitAsync(obj: any): Promise { - const inst = obj; - if (this.definition.initMethod && inst[this.definition.initMethod]) { - const initFn = inst[this.definition.initMethod]; - if (is.generatorFunction(initFn)) { - await co.wrap(initFn).call(inst); - } else if (is.asyncFunction(initFn)) { - await initFn.call(inst); - } else { - if (initFn.length === 1) { - await new Promise(resolve => { - initFn.call(inst, resolve); - }); - } else { - initFn.call(inst); - } - } - } - } - /** - * 对象销毁 - * @param obj 对象,由doConstruct返回 - * @returns {void} - */ - doDestroy(obj: any): void { - if (this.definition.destroyMethod && obj[this.definition.destroyMethod]) { - obj[this.definition.destroyMethod].call(obj); - } - } - /** - * 对象销毁 - * @param obj 对象,由doConstructAsync返回 - * @returns {void} - */ - async doDestroyAsync(obj: any): Promise { - if (this.definition.destroyMethod && obj[this.definition.destroyMethod]) { - const fn = obj[this.definition.destroyMethod]; - if (is.generatorFunction(fn)) { - await co.wrap(fn).call(obj); - } else if (is.asyncFunction(fn)) { - await fn.call(obj); - } else { - if (fn.length === 1) { - await new Promise(resolve => { - fn.call(obj, resolve); - }); - } else { - fn.call(obj); - } - } - } - } -} diff --git a/packages/context/src/base/ObjectDefinition.ts b/packages/context/src/base/ObjectDefinition.ts deleted file mode 100644 index 135c12fe9bd0..000000000000 --- a/packages/context/src/base/ObjectDefinition.ts +++ /dev/null @@ -1,91 +0,0 @@ -import { IObjectCreator, IObjectDefinition, ObjectIdentifier, Scope } from '../interfaces'; -import { ScopeEnum } from './Scope'; -import { ObjectConfiguration } from './Configuration'; -import { ObjectCreator } from './ObjectCreator'; - -export class ObjectDefinition implements IObjectDefinition { - protected _attrs = new Map(); - protected _asynchronous: boolean = false; - // 对象定义默认需要自动装配 - protected _autowire: boolean = true; - protected _external: boolean = false; - protected _direct: boolean = false; - scope: Scope = ScopeEnum.Singleton; - creator: IObjectCreator = null; - id: string = null; - name: string = null; - initMethod: string = null; - destroyMethod: string = null; - constructMethod: string = null; - constructorArgs: any[] = []; - path: any = null; - export: string = null; - dependsOn: ObjectIdentifier[] = []; - properties = new ObjectConfiguration(); - - constructor() { - this.creator = new ObjectCreator(this); - } - - set autowire(autowire: boolean) { - this._autowire = autowire; - } - - isAutowire(): boolean { - return this._autowire; - } - - set asynchronous(asynchronous: boolean) { - this._asynchronous = asynchronous; - } - - isAsync(): boolean { - return this._asynchronous; - } - - isSingletonScope(): boolean { - return this.scope === ScopeEnum.Singleton; - } - - isRequestScope(): boolean { - return this.scope === ScopeEnum.Request; - } - - set external(external: boolean) { - this._external = external; - } - - isExternal(): boolean { - return this._external; - } - - set direct(direct: boolean) { - this._direct = direct; - } - - isDirect(): boolean { - return this._direct; - } - - hasDependsOn(): boolean { - return this.dependsOn.length > 0; - } - - hasConstructorArgs(): boolean { - return this.constructorArgs.length > 0; - } - - getAttr(key: ObjectIdentifier): any { - return this._attrs.get(key); - } - - hasAttr(key: ObjectIdentifier): boolean { - return this._attrs.has(key); - } - - setAttr(key: ObjectIdentifier, value: any): void { - this._attrs.set(key, value); - } -} - - diff --git a/packages/context/src/base/Resource.ts b/packages/context/src/base/Resource.ts deleted file mode 100644 index 3729966eefa9..000000000000 --- a/packages/context/src/base/Resource.ts +++ /dev/null @@ -1,127 +0,0 @@ -import { URL } from 'url'; // tslint:disable-line -import { existsSync, - readFileSync, - lstatSync, - readdirSync -} from 'fs'; -import { resolve, parse, dirname, join } from 'path'; -import { IResource } from '../interfaces'; - -export class Resource implements IResource { - private _baseDir: string = null; - private _path: string = null; - public encoding: string = 'UTF-8'; - - constructor(baseDir: string, path?: string) { - this._baseDir = baseDir; - this._path = path || '.'; // baseDir 目录 - } - - getPath(): string { - if (this._baseDir) { - return resolve(this._baseDir, this._path); - } - return this._path; - } - - exists(): boolean { - return existsSync(this.getPath()); - } - - isFile(): boolean { - const stats = lstatSync(this.getPath()); - return stats.isFile(); - } - - isDir(): boolean { - const stats = lstatSync(this.getPath()); - return stats.isDirectory(); - } - - isURL(): boolean { - return this.getPath().indexOf('http') > -1; - } - - getURL(): any { - if (this.isURL()) { - return new URL(this._path); - } - return null; - } - - /** - * 如果是文件则获取当前文件夹路径 - * 如果是文件夹则直接作为路径 - * @param path 相对路径 - */ - createRelative(path: string): IResource { - if (this.isFile()) { - path = join(dirname(this.getPath()), path); - } else { - path = join(this.getPath(), path); - } - return new Resource(this._baseDir, path); - } - - getSubResources(): IResource[] { - if (this.isDir()) { - const files: string[] = readdirSync(this.getPath()); - const arr = files.map(file => { - return new Resource(this.getPath(), file); - }); - - return arr; - } - return []; - } - - getContent(): Buffer { - if (!this.exists()) { - throw new Error(`${this.getPath()} not found!`); - } - if (!this.isFile()) { - throw new Error(`${this.getPath()} is not a file!`); - } - return readFileSync(this.getPath()); - } - - getContentAsJSON(): Object { - if (!this.exists()) { - throw new Error(`${this.getPath()} not found!`); - } - if (!this.isFile()) { - throw new Error(`${this.getPath()} is not a file!`); - } - if (parse(this.getPath()).ext === '.json') { - const buf = readFileSync(this.getPath()); - try { - return JSON.parse(buf.toString()); - } catch (e) {} - return {}; - } - return require(this.getPath()); - } - - get name(): string { - if (this.exists()) { - return parse(this.getPath()).name; - } - return null; - } - - get contentLength(): number { - if (this.exists()) { - const buf = readFileSync(this.getPath()); - return buf.length; - } - return 0; - } - - get lastModified(): number { - if (this.exists()) { - const stats = lstatSync(this.getPath()); - return stats.mtime.getTime(); - } - return 0; - } -} diff --git a/packages/context/src/base/Scope.ts b/packages/context/src/base/Scope.ts deleted file mode 100644 index 02b9c06a3648..000000000000 --- a/packages/context/src/base/Scope.ts +++ /dev/null @@ -1,7 +0,0 @@ -import { IScopeEnum } from '../interfaces'; - -export const ScopeEnum: IScopeEnum = { - Singleton: 'Singleton', - Request: 'Request', - Prototype: 'Prototype', -}; diff --git a/packages/context/src/factory/applicationContext.ts b/packages/context/src/factory/applicationContext.ts deleted file mode 100644 index 01ee60762521..000000000000 --- a/packages/context/src/factory/applicationContext.ts +++ /dev/null @@ -1,328 +0,0 @@ -/** - * 基础的ObjectFactory和ApplicationContext实现 - */ -import { EventEmitter } from 'events'; -import { - IApplicationContext, - ILifeCycle, - IMessageSource, - IObjectDefinition, - IObjectDefinitionRegistry, - IObjectFactory, - ObjectDependencyTree, - ObjectIdentifier -} from '../interfaces'; -import { ObjectConfiguration } from '../base/Configuration'; -import { ManagedResolverFactory } from './common/ManagedResolverFactory'; -import { NotFoundError } from '../utils/errorFactory'; - -const graphviz = require('graphviz'); - -export const ContextEvent = { - START: 'start', - READY: 'onReady', - ONREFRESH: 'onRefresh', - STOP: 'stop' -}; - -const PREFIX = '_id_default_'; - -export class ObjectDefinitionRegistry extends Map implements IObjectDefinitionRegistry { - get identifiers() { - const ids = []; - for (let key of this.keys()) { - if (key.indexOf(PREFIX) === -1) { - ids.push(key); - } - } - return ids; - } - - get count() { - return this.size; - } - - getDefinitionByName(name: string): IObjectDefinition[] { - const definitions = []; - for (let v of this.values()) { - const definition = v; - if (definition.name === name) { - definitions.push(definition); - } - } - return definitions; - } - - registerDefinition(identifier: ObjectIdentifier, definition: IObjectDefinition) { - this.set(identifier, definition); - } - - getDefinition(identifier: ObjectIdentifier): IObjectDefinition { - return this.get(identifier); - } - - getDefinitionByPath(path: string): IObjectDefinition { - for (let v of this.values()) { - const definition = v; - if (definition.path === path) { - return definition; - } - } - return null; - } - - removeDefinition(identifier: ObjectIdentifier): void { - this.delete(identifier); - } - - hasDefinition(identifier: ObjectIdentifier): boolean { - return this.has(identifier); - } - - clearAll(): void { - this.clear(); - } - - hasObject(identifier: ObjectIdentifier): boolean { - return this.has(PREFIX + identifier); - } - - registerObject(identifier: ObjectIdentifier, target: any) { - this.set(PREFIX + identifier, target); - } - - getObject(identifier: ObjectIdentifier): any { - return this.get(PREFIX + identifier); - } -} - -export class BaseApplicationContext extends EventEmitter implements IApplicationContext, IObjectFactory { - protected refreshing: boolean = false; - protected readied: boolean = false; - protected lifeCycles: ILifeCycle[] = []; - protected resolverFactory: ManagedResolverFactory; - baseDir: string; - registry: IObjectDefinitionRegistry; - parent: IApplicationContext; - props: ObjectConfiguration = new ObjectConfiguration(); - configLocations: string[] = []; - messageSource: IMessageSource; - dependencyMap: Map = new Map(); - - constructor(baseDir: string = process.cwd(), parent?: IApplicationContext) { - super(); - this.parent = parent; - this.baseDir = baseDir; - - this.registry = new ObjectDefinitionRegistry(); - this.resolverFactory = this.getManagedResolverFactory(); - - this.init(); - } - - protected getManagedResolverFactory() { - return new ManagedResolverFactory(this); - } - - /** - * 继承实现时需要调用super - */ - protected init(): void { - } - - async stop(): Promise { - await this.resolverFactory.destroyCache(); - this.registry.clearAll(); - this.readied = false; - this.emit(ContextEvent.STOP); - } - - async ready(): Promise { - return await this.refreshAsync(); - } - - async refreshAsync(): Promise { - if (this.refreshing) { - return; - } - this.refreshing = true; - this.emit(ContextEvent.ONREFRESH); - await this.loadDefinitions(this.configLocations); - this.refreshing = false; - this.readied = true; - this.emit(ContextEvent.READY); - } - - protected loadDefinitions(configLocations?: string[]): void { - // throw new Error('BaseApplicationContext not implement _loadDefinitions'); - } - - isAsync(identifier: ObjectIdentifier): boolean { - if (this.registry.hasDefinition(identifier)) { - this.registry.getDefinition(identifier).isAsync(); - } - return false; - } - - get(identifier: ObjectIdentifier, args?: any): T { - // 因为在这里拿不到类名, NotFoundError 类的错误信息在 ManagedResolverFactory.ts createAsync 方法中增加错误类名 - - if (this.registry.hasObject(identifier)) { - return this.registry.getObject(identifier); - } - - if (this.isAsync(identifier)) { - throw new Error(`${identifier} must use getAsync`); - } - - const definition = this.registry.getDefinition(identifier); - if (!definition && this.parent) { - if (this.parent.isAsync(identifier)) { - throw new Error(`${identifier} must use getAsync`); - } - - return this.parent.get(identifier, args); - } - if (!definition) { - throw new NotFoundError(identifier); - } - return this.resolverFactory.create(definition, args); - } - - async getAsync(identifier: ObjectIdentifier, args?: any): Promise { - // 因为在这里拿不到类名, NotFoundError 类的错误信息在 ManagedResolverFactory.ts createAsync 方法中增加错误类名 - - if (this.registry.hasObject(identifier)) { - return this.registry.getObject(identifier); - } - - const definition = this.registry.getDefinition(identifier); - if (!definition && this.parent) { - return await this.parent.getAsync(identifier, args); - } - - if (!definition) { - throw new NotFoundError(identifier); - } - return await this.resolverFactory.createAsync(definition, args); - } - - addLifeCycle(lifeCycle: ILifeCycle): void { - this.lifeCycles.push(lifeCycle); - - this.on(ContextEvent.START, lifeCycle.onStart); - this.on(ContextEvent.STOP, lifeCycle.onStop); - this.on(ContextEvent.READY, lifeCycle.onReady); - this.on(ContextEvent.ONREFRESH, lifeCycle.onRefresh); - } - - removeLifeCycle(lifeCycle: ILifeCycle): void { - let index = this.lifeCycles.indexOf(lifeCycle); - if (index === -1) { - for (let i = 0; i < this.lifeCycles.length; i++) { - if (this.lifeCycles[i].key = lifeCycle.key) { - index = i; - break; - } - } - } - - if (index > -1) { - const aa = this.lifeCycles.splice(index, 1); - for (let i = 0; i < aa.length; i++) { - const tmp = aa[i]; - this.removeListener(ContextEvent.START, tmp.onStart); - this.removeListener(ContextEvent.STOP, tmp.onStop); - this.removeListener(ContextEvent.READY, tmp.onReady); - this.removeListener(ContextEvent.ONREFRESH, tmp.onRefresh); - } - } - } - - get isReady(): boolean { - return this.readied; - } - - /** - * proxy registry.registerDefinition - * @param {ObjectIdentifier} identifier - * @param {IObjectDefinition} definition - */ - registerDefinition(identifier: ObjectIdentifier, definition: IObjectDefinition) { - this.registry.registerDefinition(identifier, definition); - this.createObjectDependencyTree(identifier, definition); - } - - /** - * proxy registry.registerObject - * @param {ObjectIdentifier} identifier - * @param target - */ - registerObject(identifier: ObjectIdentifier, target: any) { - this.registry.registerObject(identifier, target); - } - - /** - * register handler after instance create - * @param fn - */ - afterEachCreated(fn: (ins: any, context: IApplicationContext, definition?: IObjectDefinition) => void) { - this.resolverFactory.afterEachCreated(fn); - } - - /** - * register handler before instance create - * @param fn - */ - beforeEachCreated(fn: (Clzz: any, constructorArgs: Array, context: IApplicationContext) => void) { - this.resolverFactory.beforeEachCreated(fn); - } - - protected createObjectDependencyTree(identifier, definition) { - if (!this.dependencyMap.has(identifier)) { - - let constructorArgs = definition.constructorArgs || []; - constructorArgs = constructorArgs.map((ref) => { - return ref.name; - }).filter(name => { - return !!name; - }); - - const properties = (definition.properties && definition.properties.keys().map((key) => { - return definition.properties.get(key).name; - })) || []; - - this.dependencyMap.set(identifier, { - name: typeof definition.path !== 'string' ? definition.path.name : identifier, - scope: definition.scope, - constructorArgs: constructorArgs, - properties: properties, - }); - } - } - - dumpDependency() { - const g = graphviz.digraph('G'); - - for (let [id, module] of this.dependencyMap.entries()) { - - g.addNode(id, {label: `${id}(${module.name})\nscope:${module.scope}`, fontsize: '10'}); - - module.properties.forEach((depId) => { - g.addEdge(id, depId, {label: `properties`, fontsize: '8'}); - }); - - module.constructorArgs.forEach((depId) => { - g.addEdge(id, depId, {label: 'constructor', fontsize: '8'}); - }); - } - - try { - return g.to_dot(); - } catch (err) { - console.error('generate injection dependency tree fail, err = ', err.message); - } - } - -} - diff --git a/packages/context/src/factory/common/Autowire.ts b/packages/context/src/factory/common/Autowire.ts deleted file mode 100644 index 1e7f488988df..000000000000 --- a/packages/context/src/factory/common/Autowire.ts +++ /dev/null @@ -1,133 +0,0 @@ -/** - * 自动装配补丁 - * 遍历实例对象中 this.xx = null; 的属性 - * 或者是 this.xxx = inject('xxx'); 的属性 - * 调用时进行自动装配 - */ - -import * as _ from 'lodash'; -import { IApplicationContext } from '../../interfaces'; - -export class InjectionPoint { - defaultValue: any; - id: string; - - constructor(id: string, defaultValue: any) { - this.id = id; - this.defaultValue = defaultValue; - } - - static create(id: string, defaultValue?: any) { - return new InjectionPoint(id, defaultValue); - } -} - -export class Autowire { - /** - * 创建注入点,类似alias功能,用于注入其他id对象 - * @param id 替换id - * @param defaultValue 默认值,可选 - */ - static createInject(id: string, defaultValue?: any) { - return new InjectionPoint(id, defaultValue); - } - - static patchInject(instance: any, context: IApplicationContext) { - if (instance.__patched_inject__) { - return; - } - // 遍历 this.xxx = inject('xxx') 这样的属性 - let patched = false; - _.forOwn(instance, (v, k) => { - if (v instanceof InjectionPoint) { - patched = true; - Object.defineProperty(instance, k, { - get: () => { - let value = v.defaultValue; - try { - value = context.get(v.id || k); - } catch (e) { - if (e.message.indexOf('is not valid in current context') === -1) { - throw e; - } - } - return value; - }, - configurable: false, - enumerable: true - }); - return; - } - }); - - if (patched) { - instance.__patched_inject__ = true; - } - } - /** - * 自动装配 this.xxx = null; - * @param instance 实例对象 - * @param context ApplicationContext - * @param fn handle function - */ - static patchNoDollar(instance: any, context: IApplicationContext, fn?: any) { - if (instance.__patched_no_dollar__) { - return; - } - - let patched = false; - _.forOwn(instance, (v, k) => { - if (v === null && k[0] !== '$') { - patched = true; - Object.defineProperty(instance, k, { - get: () => { - if (fn && typeof fn === 'function') { - return fn(k); - } - return context.get(k); - }, - configurable: false, - enumerable: true - }); - } - }); - - if (patched) { - instance.__patched_no_dollar__ = true; - } - } - /** - * 自动装配 this.$xxx = null - * 插件、logger - * @param instance 实例对象 - * @param context ApplicationContext - * @param fn handle function - */ - static patchDollar(instance: any, context: IApplicationContext, fn?: any) { - if (instance.__patched_dollar__) { - return; - } - - let patched = false; - _.forOwn(instance, (v, k) => { - if (v === null && k[0] === '$') { - patched = true; - Object.defineProperty(instance, k, { - get: () => { - let kk = k.slice(1); - if (fn && typeof fn === 'function') { - return fn(kk); - } - return context.get(kk); - }, - configurable: false, - enumerable: true - }); - } - }); - - if (patched) { - instance.__patched_dollar__ = true; - } - } -} diff --git a/packages/context/src/factory/common/ManagedResolverFactory.ts b/packages/context/src/factory/common/ManagedResolverFactory.ts deleted file mode 100644 index 8b666666f138..000000000000 --- a/packages/context/src/factory/common/ManagedResolverFactory.ts +++ /dev/null @@ -1,522 +0,0 @@ -/** - * 管理对象解析构建 - */ - -import * as _ from 'lodash'; -import { KEYS, VALUE_TYPE } from './constants'; -import { - ManagedJSON, - ManagedList, - ManagedMap, - ManagedObject, - ManagedProperties, - ManagedProperty, - ManagedReference, - ManagedSet, - ManagedValue -} from './managed'; -import { - IApplicationContext, - IManagedInstance, - IManagedResolver, - IObjectDefinition, - ObjectIdentifier -} from '../../interfaces'; -import { ObjectConfiguration } from '../../base/Configuration'; -import { Autowire } from './Autowire'; -import { NotFoundError } from '../../utils/errorFactory'; - -/** - * 所有解析器基类 - */ -export class BaseManagedResolver implements IManagedResolver { - protected _factory: ManagedResolverFactory; - - constructor(factory: ManagedResolverFactory) { - this._factory = factory; - } - - get type(): string { - throw new Error('not implement'); - } - - resolve(managed: IManagedInstance): any { - throw new Error('not implement'); - } - - async resolveAsync(managed: IManagedInstance): Promise { - throw new Error('not implement'); - } -} - -/** - * 解析json - */ -class JSONResolver extends BaseManagedResolver { - get type(): string { - return KEYS.JSON_ELEMENT; - } - - resolve(managed: IManagedInstance): any { - const mjson = managed; - return JSON.parse(this._factory.tpl(mjson.value)); - } - - async resolveAsync(managed: IManagedInstance): Promise { - return this.resolve(managed); - } -} - -/** - * 解析值 - */ -class ValueResolver extends BaseManagedResolver { - get type(): string { - return KEYS.VALUE_ELEMENT; - } - - /** - * 解析不通类型的值 - * @param managed 类型接口 - * @param props 注入的属性值 - */ - _resolveCommon(managed: IManagedInstance): any { - const mv = managed; - switch (mv.valueType) { - case VALUE_TYPE.STRING: - case VALUE_TYPE.TEMPLATE: - return this._factory.tpl(mv.value); - case VALUE_TYPE.NUMBER: - return Number(this._factory.tpl(mv.value)); - case VALUE_TYPE.INTEGER: - return parseInt(this._factory.tpl(mv.value), 10); - case VALUE_TYPE.DATE: - return new Date(this._factory.tpl(mv.value)); - case VALUE_TYPE.BOOLEAN: - return mv.value === 'true'; - } - - return mv.value; - } - - resolve(managed: IManagedInstance): any { - const mv = managed; - if (mv.valueType === VALUE_TYPE.MANAGED) { - return this._factory.resolveManaged(mv.value); - } else { - return this._resolveCommon(managed); - } - } - - async resolveAsync(managed: IManagedInstance): Promise { - const mv = managed; - if (mv.valueType === VALUE_TYPE.MANAGED) { - return await this._factory.resolveManagedAsync(mv.value); - } else { - return this._resolveCommon(managed); - } - } -} - -/** - * 解析ref - */ -class RefResolver extends BaseManagedResolver { - get type(): string { - return KEYS.REF_ELEMENT; - } - - resolve(managed: IManagedInstance): any { - const mr = managed; - return this._factory.context.get(mr.name); - } - - async resolveAsync(managed: IManagedInstance): Promise { - const mr = managed; - return await this._factory.context.getAsync(mr.name); - } -} - -/** - * 解析 list - */ -class ListResolver extends BaseManagedResolver { - get type(): string { - return KEYS.LIST_ELEMENT; - } - - resolve(managed: IManagedInstance): any { - const ml = managed; - const arr = []; - for (let i = 0; i < ml.length; i++) { - arr.push(this._factory.resolveManaged(ml[i])); - } - return arr; - } - - async resolveAsync(managed: IManagedInstance): Promise { - const ml = managed; - const arr = []; - for (let i = 0; i < ml.length; i++) { - arr.push(await this._factory.resolveManagedAsync(ml[i])); - } - return arr; - } -} - -/** - * 解析set - */ -class SetResolver extends BaseManagedResolver { - get type(): string { - return KEYS.SET_ELEMENT; - } - - resolve(managed: IManagedInstance): any { - const ms = managed; - const s = new Set(); - for (let item of ms) { - s.add(this._factory.resolveManaged(item)); - } - return s; - } - - async resolveAsync(managed: IManagedInstance): Promise { - const ms = managed; - const s = new Set(); - for (let item of ms) { - s.add(await this._factory.resolveManagedAsync(item)); - } - return s; - } -} - -/** - * 解析map - */ -class MapResolver extends BaseManagedResolver { - get type(): string { - return KEYS.MAP_ELEMENT; - } - - resolve(managed: IManagedInstance): any { - const mm = managed; - const m = new Map(); - for (let key of mm.keys()) { - m.set(key, this._factory.resolveManaged(mm.get(key))); - } - return m; - } - - async resolveAsync(managed: IManagedInstance): Promise { - const mm = managed; - const m = new Map(); - for (let key of mm.keys()) { - m.set(key, await this._factory.resolveManagedAsync(mm.get(key))); - } - return m; - } -} - -/** - * 解析properties - */ -class PropertiesResolver extends BaseManagedResolver { - get type(): string { - return KEYS.PROPS_ELEMENT; - } - - resolve(managed: IManagedInstance): any { - const m = managed; - const cfg = new ObjectConfiguration(); - const keys = m.keys(); - for (let i = 0; i < keys.length; i++) { - const key = keys[i]; - cfg.setProperty(key, this._factory.resolveManaged(m.getProperty(key))); - } - return cfg; - } - - async resolveAsync(managed: IManagedInstance): Promise { - const m = managed; - const cfg = new ObjectConfiguration(); - const keys = m.keys(); - for (let i = 0; i < keys.length; i++) { - const key = keys[i]; - cfg.setProperty(key, await this._factory.resolveManagedAsync(m.getProperty(key))); - } - return cfg; - } -} - -/** - * 解析property - */ -class PropertyResolver extends BaseManagedResolver { - get type(): string { - return KEYS.PROPERTY_ELEMENT; - } - - resolve(managed: IManagedInstance): any { - const mp = managed; - return this._factory.resolveManaged(mp.value); - } - - async resolveAsync(managed: IManagedInstance): Promise { - const mp = managed; - return await this._factory.resolveManagedAsync(mp.value); - } -} - -/** - * 解析 object - */ -class ObjectResolver extends BaseManagedResolver { - get type(): string { - return KEYS.OBJECT_ELEMENT; - } - - resolve(managed: IManagedInstance): any { - const mo = managed; - return this._factory.create(mo.definition, null); - } - - async resolveAsync(managed: IManagedInstance): Promise { - const mo = managed; - return await this._factory.createAsync(mo.definition, null); - } -} - -/** - * 解析工厂 - */ -export class ManagedResolverFactory { - private resolvers = new Map(); - private _props = null; - singletonCache = new Map(); - context: IApplicationContext; - afterCreateHandler = []; - beforeCreateHandler = []; - - constructor(context: IApplicationContext) { - this.context = context; - - // 初始化解析器 - this.registerResolver(new JSONResolver(this)); - this.registerResolver(new ValueResolver(this)); - this.registerResolver(new ListResolver(this)); - this.registerResolver(new SetResolver(this)); - this.registerResolver(new MapResolver(this)); - this.registerResolver(new PropertiesResolver(this)); - this.registerResolver(new PropertyResolver(this)); - this.registerResolver(new ObjectResolver(this)); - this.registerResolver(new RefResolver(this)); - } - - get props() { - if (!this._props) { - this._props = this.context.props.toJSON(); - } - return this._props; - } - /** - * 用于解析模版化的值 - * example: {{aaa.bbb.ccc}} - * @param value 配置的模版值 - */ - tpl(value) { - if (value && value.indexOf('{{') > -1) { - return _.template(value, { - // use `{{` and `}}` as delimiters - interpolate: /{{([\s\S]+?)}}/g - })(this.props); - } - return value; - } - - registerResolver(resolver: IManagedResolver) { - this.resolvers.set(resolver.type, resolver); - } - - resolveManaged(managed: IManagedInstance): any { - if (!this.resolvers.has(managed.type)) { - throw new Error(`${managed.type} resolver is not exists!`); - } - return this.resolvers.get(managed.type).resolve(managed); - } - - async resolveManagedAsync(managed: IManagedInstance): Promise { - if (!this.resolvers.has(managed.type)) { - throw new Error(`${managed.type} resolver is not exists!`); - } - return await this.resolvers.get(managed.type).resolveAsync(managed); - } - - /** - * 同步创建对象 - * @param definition 对象定义 - * @param args 参数 - */ - create(definition: IObjectDefinition, args: any): any { - if (definition.isSingletonScope() && - this.singletonCache.has(definition.id)) { - return this.singletonCache.get(definition.id); - } - - // 预先初始化依赖 - if (definition.hasDependsOn()) { - for (let i = 0; i < definition.dependsOn.length; i++) { - this.context.get(definition.dependsOn[i], args); - } - } - - const Clzz = definition.creator.load(); - - let constructorArgs = []; - if (args && _.isArray(args) && args.length > 0) { - constructorArgs = args; - } else { - if (definition.constructorArgs) { - for (let i = 0; i < definition.constructorArgs.length; i++) { - constructorArgs.push(this.resolveManaged(definition.constructorArgs[i])); - } - } - } - - for (let handler of this.beforeCreateHandler) { - handler.call(this, Clzz, constructorArgs, this.context); - } - - const inst = definition.creator.doConstruct(Clzz, constructorArgs); - - if (definition.properties) { - const keys = definition.properties.keys(); - for (let i = 0; i < keys.length; i++) { - const key = keys[i]; - const identifier = definition.properties.getProperty(key); - try { - inst[key] = this.resolveManaged(identifier); - } catch (error) { - if(NotFoundError.isClosePrototypeOf(error)) { - const className = definition.path.name; - error.updateErrorMsg(className); - } - throw error; - } - } - } - - if (definition.isAutowire()) { - Autowire.patchInject(inst, this.context); - Autowire.patchNoDollar(inst, this.context); - } - - for (let handler of this.afterCreateHandler) { - handler.call(this, inst, this.context, definition); - } - - // after properties set then do init - definition.creator.doInit(inst); - - if (definition.isSingletonScope() && definition.id) { - this.singletonCache.set(definition.id, inst); - } - - return inst; - } - - /** - * 异步创建对象 - * @param definition 对象定义 - * @param args 参数 - */ - async createAsync(definition: IObjectDefinition, args: any): Promise { - if (definition.isSingletonScope() && - this.singletonCache.has(definition.id)) { - return this.singletonCache.get(definition.id); - } - - // 预先初始化依赖 - if (definition.hasDependsOn()) { - for (let i = 0; i < definition.dependsOn.length; i++) { - await this.context.getAsync(definition.dependsOn[i], args); - } - } - - const Clzz = definition.creator.load(); - let constructorArgs; - if (args && _.isArray(args) && args.length > 0) { - constructorArgs = args; - } else { - constructorArgs = []; - if (definition.constructorArgs) { - for (let i = 0; i < definition.constructorArgs.length; i++) { - constructorArgs.push(await this.resolveManagedAsync(definition.constructorArgs[i])); - } - } - } - - for (let handler of this.beforeCreateHandler) { - handler.call(this, Clzz, constructorArgs, this.context); - } - - const inst = await definition.creator.doConstructAsync(Clzz, constructorArgs); - if (!inst) { - throw new Error(`${definition.id} config no valid path`); - } - - if (definition.properties) { - const keys = definition.properties.keys(); - for (let i = 0; i < keys.length; i++) { - const key = keys[i]; - const identifier = definition.properties.getProperty(key); - try { - inst[key] = await this.resolveManagedAsync(identifier); - } catch (error) { - if(NotFoundError.isClosePrototypeOf(error)) { - const className = definition.path.name; - error.updateErrorMsg(className); - } - throw error; - } - } - } - - if (definition.isAutowire()) { - Autowire.patchInject(inst, this.context); - Autowire.patchNoDollar(inst, this.context); - } - - for (let handler of this.afterCreateHandler) { - handler.call(this, inst, this.context, definition); - } - - // after properties set then do init - await definition.creator.doInitAsync(inst); - - if (definition.isSingletonScope() && definition.id) { - this.singletonCache.set(definition.id, inst); - } - - return inst; - } - - async destroyCache(): Promise { - for (let key of this.singletonCache.keys()) { - const definition = this.context.registry.getDefinition(key); - if (definition.creator) { - await definition.creator.doDestroyAsync(this.singletonCache.get(key)); - } - } - this.singletonCache.clear(); - } - - beforeEachCreated(fn: (Clzz: any, constructorArgs: Array, context: IApplicationContext) => void) { - this.beforeCreateHandler.push(fn); - } - - afterEachCreated(fn: (ins: any, context: IApplicationContext, definition?: IObjectDefinition) => void) { - this.afterCreateHandler.push(fn); - } - -} diff --git a/packages/context/src/factory/common/constants.ts b/packages/context/src/factory/common/constants.ts deleted file mode 100644 index d03c00407942..000000000000 --- a/packages/context/src/factory/common/constants.ts +++ /dev/null @@ -1,74 +0,0 @@ -/** - * 静态参数 - * - */ - -export const KEYS = { - OBJECTS_ELEMENT: 'objects', - OBJECT_ELEMENT: 'object', - IMPORT_ELEMENT: 'import', - PROPERTY_ELEMENT: 'property', - LIST_ELEMENT: 'list', - MAP_ELEMENT: 'map', - ENTRY_ELEMENT: 'entry', - VALUE_ELEMENT: 'value', - PROPS_ELEMENT: 'props', - PROP_ELEMENT: 'prop', - SET_ELEMENT: 'set', - CONSTRUCTORARG_ELEMENT: 'constructor-arg', - REF_ELEMENT: 'ref', - JSON_ELEMENT: 'json', - CONFIGURATION_ELEMENT: 'configuration', - - ID_ATTRIBUTE: 'id', - PATH_ATTRIBUTE: 'path', - DIRECT_ATTRIBUTE: 'direct', - AUTOWIRE_ATTRIBUTE: 'autowire', - ASYNC_ATTRIBUTE: 'async', - NAME_ATTRIBUTE: 'name', - REF_ATTRIBUTE: 'ref', - KEY_ATTRIBUTE: 'key', - VALUE_ATTRIBUTE: 'value', - TYPE_ATTRIBUTE: 'type', - EXTERNAL_ATTRIBUTE: 'external', - OBJECT_ATTRIBUTE: 'object', - RESOURCE_ATTRIBUTE: 'resource', - SCOPE_ATTRIBUTE: 'scope', - - ASPECT_ELEMENT: 'aspect', - AROUND_ELEMENT: 'around', - EXPRESSION_ATTRIBUTE: 'expression', - EXECUTE_ATTRIBUTE: 'execute' -}; -/* - https://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/core.html#ID-1950641247 - ELEMENT_NODE = 1; - ATTRIBUTE_NODE = 2; - TEXT_NODE = 3; - CDATA_SECTION_NODE = 4; - ENTITY_REFERENCE_NODE = 5; - ENTITY_NODE = 6; - PROCESSING_INSTRUCTION_NODE = 7; - COMMENT_NODE = 8; - DOCUMENT_NODE = 9; - DOCUMENT_TYPE_NODE = 10; - DOCUMENT_FRAGMENT_NODE = 11; - NOTATION_NODE = 12; - */ -export const NODE_TYPE = { - ELEMENT: 1, - ATTRIBUTE: 2, - TEXT: 3, - CDATA: 4 -}; - -export const VALUE_TYPE = { - STRING: 'string', - DATE: 'date', - NUMBER: 'number', - INTEGER: 'int', - TEMPLATE: 'template', - MANAGED: 'managed', - OBJECT: 'object', // 仅仅在解析时使用 - BOOLEAN: 'boolean' -}; diff --git a/packages/context/src/factory/common/managed.ts b/packages/context/src/factory/common/managed.ts deleted file mode 100644 index 3bdc7133a5fc..000000000000 --- a/packages/context/src/factory/common/managed.ts +++ /dev/null @@ -1,57 +0,0 @@ -/** - * 用于抽象描述的属性、json、ref、set、map等内容 - */ - -import { IManagedInstance, IObjectDefinition } from '../../interfaces'; -import { ObjectConfiguration } from '../../base/Configuration'; -import { KEYS, VALUE_TYPE } from './constants'; - -export class ManagedValue implements IManagedInstance { - type = KEYS.VALUE_ELEMENT; - value: any; - valueType: string; - - constructor(value?: any, valueType?: string) { - this.value = value; - this.valueType = valueType || VALUE_TYPE.STRING; - } -} - -export class ManagedReference implements IManagedInstance { - type = KEYS.REF_ELEMENT; - name: string; -} - -export class ManagedJSON implements IManagedInstance { - type = KEYS.JSON_ELEMENT; - value: string; -} - -export class ManagedList extends Array implements IManagedInstance { - type = KEYS.LIST_ELEMENT; -} - -export class ManagedSet extends Set implements IManagedInstance { - type = KEYS.SET_ELEMENT; -} - -export class ManagedMap extends Map implements IManagedInstance { - type = KEYS.MAP_ELEMENT; -} - -export class ManagedProperties extends ObjectConfiguration implements IManagedInstance { - type = KEYS.PROPS_ELEMENT; -} - -export class ManagedProperty implements IManagedInstance { - type = KEYS.PROPERTY_ELEMENT; - name: string; - value: any; - valueType: string; -} - -export class ManagedObject implements IManagedInstance { - type = KEYS.OBJECT_ELEMENT; - name: string; - definition: IObjectDefinition; -} diff --git a/packages/context/src/factory/container.ts b/packages/context/src/factory/container.ts deleted file mode 100644 index 20a87a784818..000000000000 --- a/packages/context/src/factory/container.ts +++ /dev/null @@ -1,174 +0,0 @@ -import 'reflect-metadata'; -import { IContainer, ObjectDefinitionOptions, ObjectIdentifier } from '../interfaces'; -import { OBJ_DEF_CLS, ObjectDefinition, TAGGED, TAGGED_CLS, TAGGED_PROP } from '..'; -import { ManagedReference, ManagedValue } from './common/managed'; -import { FunctionDefinition } from '../base/FunctionDefinition'; -import { XmlApplicationContext } from './xml/XmlApplicationContext'; -import { recursiveGetMetadata } from '../utils/reflectTool'; -import { Autowire } from './common/Autowire'; - -const uuidv1 = require('uuid/v1'); -const is = require('is-type-of'); -const camelcase = require('camelcase'); -const debug = require('debug')(`injection:Container:${process.pid}`); - -export class Container extends XmlApplicationContext implements IContainer { - id: string = uuidv1(); - - init(): void { - super.init(); - this.registerObjectPropertyParser(); - } - - bind(target: T, options?: ObjectDefinitionOptions): void; - bind(identifier: ObjectIdentifier, target: T, options?: ObjectDefinitionOptions): void; - bind(identifier: ObjectIdentifier, target: T, options?: ObjectDefinitionOptions): void { - let definition; - // definition.autowire = true; - if (is.class(identifier) || is.function(identifier)) { - options = target; - target = identifier; - identifier = this.getIdentifier(target); - options = null; - } - - if (is.class(target)) { - definition = new ObjectDefinition(); - } else { - definition = new FunctionDefinition(this); - } - - definition.path = target; - definition.id = identifier; - - debug(`=> bind and build definition, id = [${definition.id}]`); - - // inject constructArgs - let constructorMetaData = Reflect.getMetadata(TAGGED, target); - if (constructorMetaData) { - debug(` register inject constructor length = ${target['length']}`); - const maxLength = Math.max.apply(null, Object.keys(constructorMetaData)); - for (let i = 0; i < maxLength + 1; i++) { - const propertyMeta = constructorMetaData[i]; - if (propertyMeta) { - const refManagedIns = new ManagedReference(); - refManagedIns.name = propertyMeta[0].value; - definition.constructorArgs.push(refManagedIns); - } else { - // inject empty value - const valueManagedIns = new ManagedValue(); - valueManagedIns.value = undefined; - definition.constructorArgs.push(valueManagedIns); - } - } - } - - // inject properties - let metaDatas = recursiveGetMetadata(TAGGED_PROP, target); - for (const metaData of metaDatas) { - debug(` register inject properties = [${Object.keys(metaData)}]`); - for (let metaKey in metaData) { - for (let propertyMeta of metaData[metaKey]) { - const refManaged = new ManagedReference(); - refManaged.name = propertyMeta.value; - definition.properties.set(metaKey, refManaged); - } - } - } - - this.convertOptionsToDefinition(options, definition); - // 对象自定义的annotations可以覆盖默认的属性 - this.registerCustomBinding(definition, target); - - this.registerDefinition(identifier, definition); - debug(` bind and build definition complete, id = [${definition.id}]`); - } - - registerCustomBinding(objectDefinition: ObjectDefinition, target: any) { - // @async, @init, @destroy @scope - let objDefOptions: ObjectDefinitionOptions = Reflect.getMetadata(OBJ_DEF_CLS, target); - - this.convertOptionsToDefinition(objDefOptions, objectDefinition); - } - - private convertOptionsToDefinition(options: ObjectDefinitionOptions, definition: ObjectDefinition): ObjectDefinition { - if (options) { - if (options.isAsync) { - debug(` register isAsync = true`); - definition.asynchronous = true; - } - - if (options.initMethod) { - debug(` register initMethod = ${definition.initMethod}`); - definition.initMethod = options.initMethod; - } - - if (options.destroyMethod) { - debug(` register destroyMethod = ${definition.destroyMethod}`); - definition.destroyMethod = options.destroyMethod; - } - - if (options.scope) { - debug(` register scope = ${definition.scope}`); - definition.scope = options.scope; - } - - if (options.constructorArgs) { - debug(` register constructorArgs = ${options.constructorArgs}`); - definition.constructorArgs = options.constructorArgs; - } - - if (options.isAutowire === false) { - debug(` register autowire = ${options.isAutowire}`); - definition.autowire = false; - } else if (options.isAutowire === true) { - debug(` register autowire = ${options.isAutowire}`); - definition.autowire = true; - } - } - - return definition; - } - - createChild(baseDir?: string): IContainer { - return new Container(baseDir || this.baseDir, this); - } - - protected registerObjectPropertyParser() { - this.afterEachCreated((instance, context, definition) => { - if (definition.isAutowire()) { - Autowire.patchNoDollar(instance, context); - } - }); - } - - resolve(target: T): T { - const tempContainer = new Container(); - tempContainer.bind(target); - tempContainer.parent = this; - return tempContainer.get(target); - } - - get(identifier: any, args?: any): T { - if (typeof identifier !== 'string') { - identifier = this.getIdentifier(identifier); - } - return super.get(identifier, args); - } - - async getAsync(identifier: any, args?: any): Promise { - if (typeof identifier !== 'string') { - identifier = this.getIdentifier(identifier); - } - return await super.getAsync(identifier, args); - } - - protected getIdentifier(target: any) { - const metaData = Reflect.getOwnMetadata(TAGGED_CLS, target); - if (metaData) { - return metaData.id; - } else { - return camelcase(target.name); - } - } -} diff --git a/packages/context/src/factory/requestContainer.ts b/packages/context/src/factory/requestContainer.ts deleted file mode 100644 index 613b3908a549..000000000000 --- a/packages/context/src/factory/requestContainer.ts +++ /dev/null @@ -1,53 +0,0 @@ -import 'reflect-metadata'; -import { Container } from './container'; -import { IContainer } from '../interfaces'; - -export class RequestContainer extends Container { - - applicationContext: IContainer; - - constructor(ctx, applicationContext) { - super(); - this.registerObject('ctx', ctx); - this.parent = applicationContext; - this.applicationContext = applicationContext; - } - - get(identifier: any, args?: any) { - if (typeof identifier !== 'string') { - identifier = this.getIdentifier(identifier); - } - if (this.registry.hasObject(identifier)) { - return this.registry.getObject(identifier); - } - const definition = this.applicationContext.registry.getDefinition(identifier); - if (definition && definition.isRequestScope()) { - // create object from applicationContext definition for requestScope - return this.resolverFactory.create(definition, args); - } - - if (this.parent) { - return this.parent.get(identifier, args); - } - } - - async getAsync(identifier: any, args?: any) { - if (typeof identifier !== 'string') { - identifier = this.getIdentifier(identifier); - } - if (this.registry.hasObject(identifier)) { - return this.registry.getObject(identifier); - } - - const definition = this.applicationContext.registry.getDefinition(identifier); - if (definition && definition.isRequestScope()) { - // create object from applicationContext definition for requestScope - return await this.resolverFactory.createAsync(definition, args); - } - - if (this.parent) { - return await this.parent.getAsync(identifier, args); - } - } - -} diff --git a/packages/context/src/factory/xml/XmlApplicationContext.ts b/packages/context/src/factory/xml/XmlApplicationContext.ts deleted file mode 100644 index 909a5f9aa820..000000000000 --- a/packages/context/src/factory/xml/XmlApplicationContext.ts +++ /dev/null @@ -1,39 +0,0 @@ -import { IResource } from '../../interfaces'; -import { BaseApplicationContext } from '../applicationContext'; -import { XmlObjectDefinitionParser } from './XmlObjectDefinitionParser'; -import { Resource } from '../../base/Resource'; - -export class XmlApplicationContext extends BaseApplicationContext { - parser: XmlObjectDefinitionParser; - - protected init(): void { - this.parser = new XmlObjectDefinitionParser(this.baseDir, this.registry); - } - - loadDefinitions(configLocations: string[]): void { - if (!Array.isArray(configLocations)) { - throw new Error('loadDefinitions fail configLocations is not array!'); - } - - if (configLocations.length > 0) { - for (let i = 0; i < configLocations.length; i++) { - this.loadResource(new Resource(this.baseDir, configLocations[i])); - } - - this.props.putAll(this.parser.configuration); - } - } - - loadResource(res: IResource): void { - if (res.isDir()) { - const resources = res.getSubResources(); - for (let i = 0; i < resources.length; i++) { - this.loadResource(resources[i]); - } - } - if (res.isFile()) { - this.parser.load(res); - } - // TODO: if url - } -} diff --git a/packages/context/src/factory/xml/XmlObjectDefinition.ts b/packages/context/src/factory/xml/XmlObjectDefinition.ts deleted file mode 100644 index a4cc20d48e17..000000000000 --- a/packages/context/src/factory/xml/XmlObjectDefinition.ts +++ /dev/null @@ -1,68 +0,0 @@ -import { ObjectIdentifier } from '../../interfaces'; -import { ScopeEnum } from '../../base/Scope'; -import { ObjectDefinition } from '../../base/ObjectDefinition'; -import * as utils from './utils'; - -export class XmlObjectDefinition extends ObjectDefinition { - private _ele: Element; - - constructor(ele: Element) { - super(); - - this._ele = ele; - this._asynchronous = this.getAttr('async') === 'true'; - this._external = this.getAttr('external') === 'true'; - // external not autowire - this._autowire = !this._external; - if (this.hasAttr('autowire')) { - if (this.getAttr('autowire') === 'false') { - this._autowire = false; - } else if (this.getAttr('autowire') === 'true') { - this._autowire = true; - } - } - this._direct = this.getAttr('direct') === 'true'; - this.path = this.getAttr('path'); - this.id = this.getAttr('id'); - this.name = utils.nodeName(this._ele); - - if (this.hasAttr('export')) { - this.export = this.getAttr('export'); - } - - if (this.hasAttr('construct-method')) { - this.constructMethod = this.getAttr('construct-method'); - } - if (this.hasAttr('init-method')) { - this.initMethod = this.getAttr('init-method'); - } - if (this.hasAttr('destroy-method')) { - this.destroyMethod = this.getAttr('destroy-method'); - } - - // default scope is singleton - this.scope = ScopeEnum.Singleton; - if (this.getAttr('scope') === 'request') { - this.scope = ScopeEnum.Request; - } - if (this.getAttr('scope') === 'prototype') { - this.scope = ScopeEnum.Prototype; - } - if (this.getAttr('scope') === 'singleton') { - this.scope = ScopeEnum.Singleton; - } - - } - - getAttr(key: ObjectIdentifier): any { - return this._ele.getAttribute(key); - } - - hasAttr(key: ObjectIdentifier): boolean { - return this._ele.hasAttribute(key); - } - - setAttr(key: ObjectIdentifier, value: any): void { - this._ele.setAttribute(key, value); - } -} diff --git a/packages/context/src/factory/xml/XmlObjectDefinitionParser.ts b/packages/context/src/factory/xml/XmlObjectDefinitionParser.ts deleted file mode 100644 index 51e32f1a7858..000000000000 --- a/packages/context/src/factory/xml/XmlObjectDefinitionParser.ts +++ /dev/null @@ -1,166 +0,0 @@ -import { join } from 'path'; -import { DOMParser } from 'xmldom'; -import { - IObjectDefinition, - IResource, - IObjectDefinitionRegistry -} from '../../interfaces'; -import { XmlObjectDefinition } from './XmlObjectDefinition'; -import { Resource } from '../../base/Resource'; -import { KEYS } from '../common/constants'; -import * as utils from './utils'; -import { ObjectConfiguration } from '../../base/Configuration'; -import { IXmlParser, IParserContext, IObjectDefinitionParser } from './interface'; -import { XmlObjectElementParser } from './XmlObjectElementParser'; - -export class ParserContext extends Map implements IParserContext { - defaults: IObjectDefinition; - parser: XmlObjectDefinitionParser; - currentResource: IResource; - - constructor(defaults: IObjectDefinition, - parser: XmlObjectDefinitionParser) { - super(); - - this.defaults = defaults; - this.parser = parser; - } -} - -export class XmlObjectDefinitionParser implements IXmlParser { - private parsers = new Map(); - objectElementParser = new XmlObjectElementParser(); - baseDir: string; - registry: IObjectDefinitionRegistry; - configuration: ObjectConfiguration; - - constructor(baseDir: string, registry: IObjectDefinitionRegistry) { - this.baseDir = baseDir; - - this.registry = registry; - this.configuration = new ObjectConfiguration(); - } - - registerParser(parser: IObjectDefinitionParser): void { - this.parsers.set(parser.name, parser); - } - - removeParser(parser: IObjectDefinitionParser): void { - this.parsers.delete(parser.name); - } - - hasParser(name: string): boolean { - return this.parsers.has(name); - } - - getParser(name: string): IObjectDefinitionParser { - return this.parsers.get(name); - } - - registerDefinition(definition: IObjectDefinition): void { - this.registry.registerDefinition(definition.id, definition); - } - - parse(root: Element, context: IParserContext): void { - if (utils.nodeNameEq(root, KEYS.OBJECTS_ELEMENT)) { - this.parseObjectsElement(root, context); - } else if (utils.nodeNameEq(root, KEYS.IMPORT_ELEMENT)) { - this.parseImportElement(root, context); - } else if (utils.nodeNameEq(root, KEYS.CONFIGURATION_ELEMENT)) { - this.parseConfigurationElement(root, context); - } else if (utils.nodeNameEq(root, KEYS.OBJECT_ELEMENT)) { - this.parseObjectElement(root, context); - } else { - this.parseCustomElement(root, context); - } - } - - /** - * 用于外部继承实现parse custom element内部使用 - * @param definition 当前definition - * @param ele xml elemnt - * @param context see ParserContext - */ - parseElementNodes(definition: IObjectDefinition, ele: Element, context: IParserContext): void { - utils.eachSubElementSync(ele, (node: Element) => { - if (utils.nodeNameEq(node, KEYS.CONSTRUCTORARG_ELEMENT)) { - utils.eachSubElementSync(node, (sele: Element) => { - const managed = this.objectElementParser.parseElement(sele, context); - definition.constructorArgs.push(managed); - }); - } else if (utils.nodeNameEq(node, KEYS.PROPERTY_ELEMENT)) { - const name = utils.nodeAttr(node, KEYS.NAME_ATTRIBUTE); - const managed = this.objectElementParser.parseElement(node, context); - definition.properties.addProperty(name, managed); - } - }); - } - - parseObjectsElement(ele: Element, context: IParserContext): void { - context.defaults = new XmlObjectDefinition(ele); - // 需要拼上当前路径 - if (context.defaults.path) { - context.defaults.path = join(this.baseDir, context.defaults.path); - } else { - context.defaults.path = this.baseDir; - } - - utils.eachSubElementSync(ele, (node: Element) => { - this.parse(node, context); - }); - } - - parseObjectElement(ele: Element, context: IParserContext): void { - const definition = this.objectElementParser.parse(ele, context); - this.registerDefinition(definition); - } - - parseImportElement(ele: Element, context: IParserContext): void { - const rpath = utils.nodeAttr(ele, KEYS.RESOURCE_ATTRIBUTE); - const external = utils.nodeAttr(ele, KEYS.EXTERNAL_ATTRIBUTE) === 'true'; - let res = this._createResource(rpath, external, context); - this.load(res); - } - - parseConfigurationElement(ele: Element, context: IParserContext): void { - const str = utils.nodeAttr(ele, KEYS.PATH_ATTRIBUTE); - const paths = str.split(','); - const external = utils.nodeAttr(ele, KEYS.EXTERNAL_ATTRIBUTE) === 'true'; - let res = this._createResource('.', external, context); - - for (let i = 0; i < paths.length; i++) { - const cfg = res.createRelative(paths[i]).getContentAsJSON(); - this.configuration.putObject(cfg); - } - } - - parseCustomElement(ele: Element, context: IParserContext): void { - const name = utils.nodeName(ele); - if (this.hasParser(name)) { - const parser = this.getParser(name); - const definition = parser.parse(ele, context); - this.registerDefinition(definition); - } - } - - load(res: IResource): void { - const buf = res.getContent(); - const doc: Document = new DOMParser().parseFromString(buf.toString(res.encoding)); - const context = new ParserContext(null, this); - context.currentResource = res; - this.parse(doc.documentElement, context); - } - - _createResource(path: string, external: boolean, context: IParserContext): IResource { - // 外部模块内的import - if (external) { - return new Resource(this.baseDir, join('node_modules', path)); - } - // 相对路径下的import - if (context.currentResource) { - return context.currentResource.createRelative(path); - } - - throw new Error(`${path} is not found`); - } -} diff --git a/packages/context/src/factory/xml/XmlObjectElementParser.ts b/packages/context/src/factory/xml/XmlObjectElementParser.ts deleted file mode 100644 index 6b704b13d4c1..000000000000 --- a/packages/context/src/factory/xml/XmlObjectElementParser.ts +++ /dev/null @@ -1,326 +0,0 @@ -import { join } from 'path'; -import * as utils from './utils'; -import { KEYS, VALUE_TYPE } from '../common/constants'; -import { ManagedValue, - ManagedReference, - ManagedJSON, - ManagedObject, - ManagedSet, - ManagedMap, - ManagedList, - ManagedProperty, - ManagedProperties} from '../common/managed'; -import { ScopeEnum } from '../../base/Scope'; -import { - IObjectDefinition, - IManagedInstance -} from '../../interfaces'; -import { XmlObjectDefinition } from './XmlObjectDefinition'; -import { IParserContext, IManagedParser } from './interface'; - -export class ManagedParser implements IManagedParser { - protected factory: XmlObjectElementParser; - - constructor(factory: XmlObjectElementParser) { - this.factory = factory; - } - - get name(): string { - throw new Error('ManagedParser not implement'); - } - - parse(ele: Element, context: IParserContext): IManagedInstance { - throw new Error('ManagedParser not implement'); - } -} - -class JSONParser implements IManagedParser { - get name(): string { - return KEYS.JSON_ELEMENT; - } - - parse(ele: Element, context: IParserContext): IManagedInstance { - const mjson = new ManagedJSON(); - mjson.value = utils.firstCDATAText(ele); - return mjson; - } -} - -class RefParser implements IManagedParser { - get name(): string { - return KEYS.REF_ELEMENT; - } - - parse(ele: Element, context: IParserContext): IManagedInstance { - const ref = new ManagedReference(); - ref.name = utils.nodeAttr(ele, KEYS.OBJECT_ATTRIBUTE); - return ref; - } -} - -class SetParser extends ManagedParser { - get name(): string { - return KEYS.SET_ELEMENT; - } - - parse(ele: Element, context: IParserContext): IManagedInstance { - const ms = new ManagedSet(); - utils.eachSubElementSync(ele, (node: Element) => { - const vv = this.factory.parseElement(node, context); - if (vv) { - ms.add(vv); - } - }); - return ms; - } -} - -class ListParser extends ManagedParser { - get name(): string { - return KEYS.LIST_ELEMENT; - } - - parse(ele: Element, context: IParserContext): IManagedInstance { - const ml = new ManagedList(); - utils.eachSubElementSync(ele, (node: Element) => { - const v = this.factory.parseElement(node, context); - if (v) { - ml.push(v); - } - }); - return ml; - } -} - -class MapParser extends ManagedParser { - get name(): string { - return KEYS.MAP_ELEMENT; - } - - parse(ele: Element, context: IParserContext): IManagedInstance { - const mm = new ManagedMap(); - utils.eachSubElementSync(ele, (node: Element) => { - if (!utils.nodeNameEq(node, KEYS.ENTRY_ELEMENT)) { - return; - } - const key = utils.nodeAttr(node, KEYS.KEY_ATTRIBUTE); - - if (utils.nodeHasAttr(node, KEYS.VALUE_ATTRIBUTE)) { - const v = new ManagedValue(utils.nodeAttr(node, KEYS.VALUE_ATTRIBUTE), - utils.nodeAttr(node, KEYS.TYPE_ATTRIBUTE)); - mm.set(key, v); - } else { - const subEle = utils.firstSubElement(node); - if (!subEle) { - return; - } - const vv = this.factory.parseElement(subEle, context); - if (vv) { - mm.set(key, vv); - } - } - }); - return mm; - } -} - -class ValueParser extends ManagedParser { - get name(): string { - return KEYS.VALUE_ELEMENT; - } - - parse(ele: Element, context: IParserContext): IManagedInstance { - const mv = new ManagedValue(utils.nodeText(ele), - utils.nodeAttr(ele, KEYS.TYPE_ATTRIBUTE)); - const vele = utils.firstSubElement(ele); - if (vele) { - mv.value = this.factory.parseElement(vele, context); - mv.valueType = VALUE_TYPE.MANAGED; - } - return mv; - } -} - -class PropertyParser extends ManagedParser { - get name(): string { - return KEYS.PROPERTY_ELEMENT; - } - - parse(ele: Element, context: IParserContext): IManagedInstance { - const mp = new ManagedProperty(); - mp.name = utils.nodeAttr(ele, KEYS.NAME_ATTRIBUTE); - mp.valueType = VALUE_TYPE.MANAGED; - - if (utils.nodeHasAttr(ele, KEYS.VALUE_ATTRIBUTE)) { - const mv = new ManagedValue(utils.nodeAttr(ele, KEYS.VALUE_ATTRIBUTE), - utils.nodeAttr(ele, KEYS.TYPE_ATTRIBUTE)); - mp.value = mv; - } else if (utils.nodeHasAttr(ele, KEYS.REF_ATTRIBUTE)) { - const ref = new ManagedReference(); - ref.name = utils.nodeAttr(ele, KEYS.REF_ATTRIBUTE); - mp.value = ref; - } else { - const subEle = utils.firstSubElement(ele); - if (subEle) { - mp.value = this.factory.parseElement(subEle, context); - } - } - - return mp; - } -} - -class PropsParser extends ManagedParser { - get name(): string { - return KEYS.PROPS_ELEMENT; - } - - parse(ele: Element, context: IParserContext): IManagedInstance { - const mprops = new ManagedProperties(); - utils.eachSubElementSync(ele, (node: Element) => { - if (!utils.nodeNameEq(node, KEYS.PROP_ELEMENT)) { - return; - } - const key = utils.nodeAttr(node, KEYS.KEY_ATTRIBUTE); - - if (utils.nodeHasAttr(node, KEYS.VALUE_ATTRIBUTE)) { - const mv = new ManagedValue(utils.nodeAttr(node, KEYS.VALUE_ATTRIBUTE), - utils.nodeAttr(node, KEYS.TYPE_ATTRIBUTE)); - mprops.set(key, mv); - return; - } - - const subEle = utils.firstSubElement(node); - if (subEle) { - const managed = this.factory.parseElement(subEle, context); - if (managed) { - mprops.set(key, managed); - } - } else { - const mv = new ManagedValue(utils.nodeText(node), - utils.nodeAttr(node, KEYS.TYPE_ATTRIBUTE)); - mprops.set(key, mv); - } - }); - return mprops; - } -} - -class ObjectParser extends ManagedParser { - get name(): string { - return KEYS.OBJECT_ELEMENT; - } - - overwriteByContext(target: XmlObjectDefinition, ele: Element, context: IParserContext) { - if (context.defaults) { - if (target.path) { - // 路径处理,外部依赖包要拼上node_modules - if (!target.isExternal()) { - // 拼上全路径 - target.path = join(context.defaults.path, target.path); - } else { - target.path = join(context.parser.baseDir, 'node_modules', target.path); - } - } - if (!context.defaults.isAutowire() && !utils.nodeHasAttr(ele, KEYS.AUTOWIRE_ATTRIBUTE)) { - target.autowire = context.defaults.isAutowire(); - } - if (utils.nodeHasAttr(ele, KEYS.SCOPE_ATTRIBUTE)) { - if (context.defaults.isSingletonScope()) { - target.scope = ScopeEnum.Singleton; - } - if (context.defaults.isRequestScope()) { - target.scope = ScopeEnum.Request; - } - } - } - } - - parseDefinition(ele: Element, context: IParserContext): IObjectDefinition { - const definition = new XmlObjectDefinition(ele); - // 属性重写 - this.overwriteByContext(definition, ele, context); - - utils.eachSubElementSync(ele, (node: Element) => { - - if (utils.nodeNameEq(node, KEYS.CONSTRUCTORARG_ELEMENT)) { - // constructor-arg - utils.eachSubElementSync(node, (snode: Element) => { - const managed = this.factory.parseElement(snode, context); - definition.constructorArgs.push(managed); - }); - - } else if (utils.nodeNameEq(node, KEYS.PROPERTY_ELEMENT)) { - - const name = utils.nodeAttr(node, KEYS.NAME_ATTRIBUTE); - const managed = this.factory.parseElement(node, context); - definition.properties.addProperty(name, managed); - } - }); - - this._validDefinition(definition); - - return definition; - } - - parse(ele: Element, context: IParserContext): IManagedInstance { - const mo = new ManagedObject(); - mo.name = utils.nodeAttr(ele, KEYS.ID_ATTRIBUTE); - mo.definition = this.parseDefinition(ele, context); - return mo; - } - - private _validDefinition(definition: IObjectDefinition) { - if (definition.isDirect()) { - if (definition.hasConstructorArgs()) { - throw new Error(`${definition.id}: direct object has no constructor-args element`); - } - if (definition.constructMethod || definition.initMethod) { - throw new Error(`${definition.id}: direct object has no construct-method or init-method attribute`); - } - } - if (definition.isAsync() && !definition.constructMethod) { - throw new Error(`${definition.id}: async object has no construct-method attribute`); - } - if (definition.constructMethod && definition.initMethod) { - throw new Error(`${definition.id}: object construct-method conflict with init-method attribute`); - } - } -} - -export class XmlObjectElementParser { - private parsers = new Map(); - - constructor() { - this.registerParser(new JSONParser()); - this.registerParser(new RefParser()); - this.registerParser(new ListParser(this)); - this.registerParser(new SetParser(this)); - this.registerParser(new MapParser(this)); - this.registerParser(new ValueParser(this)); - this.registerParser(new PropertyParser(this)); - this.registerParser(new PropsParser(this)); - this.registerParser(new ObjectParser(this)); - } - - registerParser(parser: IManagedParser) { - this.parsers.set(parser.name, parser); - } - - parseElement(ele: Element, context: IParserContext): IManagedInstance { - const nodeName = utils.nodeName(ele); - if (this.parsers.has(nodeName)) { - return this.parsers.get(nodeName).parse(ele, context); - } - - return null; - } - - parse(ele: Element, context: IParserContext): IObjectDefinition { - const managed = this.parseElement(ele, context); - if (managed && managed.type === KEYS.OBJECT_ELEMENT) { - return ( managed).definition; - } - return null; - } -} diff --git a/packages/context/src/factory/xml/example.xml b/packages/context/src/factory/xml/example.xml deleted file mode 100644 index 23774d1f25f1..000000000000 --- a/packages/context/src/factory/xml/example.xml +++ /dev/null @@ -1,87 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - asdfa - 123 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - INDIA - Pakistan - USA - USA - - - - - - - - - diff --git a/packages/context/src/factory/xml/interface.ts b/packages/context/src/factory/xml/interface.ts deleted file mode 100644 index 9164472bdb62..000000000000 --- a/packages/context/src/factory/xml/interface.ts +++ /dev/null @@ -1,28 +0,0 @@ -/** - * xml 解析节点使用的接口定义 - */ - -import { IObjectDefinition, IResource, IManagedInstance } from '../../interfaces'; - -export interface IXmlParser { - baseDir: string; - parse(root: Element, context: IParserContext): void; - parseElementNodes(definition: IObjectDefinition, ele: Element, context: IParserContext): void; - registerDefinition(definition: IObjectDefinition); -} - -export interface IParserContext { - defaults: IObjectDefinition; - currentResource: IResource; - parser: IXmlParser; -} - -export interface IObjectDefinitionParser { - readonly name: string; - parse(ele: Element, context: IParserContext): IObjectDefinition; -} - -export interface IManagedParser { - readonly name: string; - parse(ele: Element, context: IParserContext): IManagedInstance; -} diff --git a/packages/context/src/factory/xml/utils.ts b/packages/context/src/factory/xml/utils.ts deleted file mode 100644 index ad6b1e9749eb..000000000000 --- a/packages/context/src/factory/xml/utils.ts +++ /dev/null @@ -1,102 +0,0 @@ -/** - * xml解析工具函数集合 - */ - -import { NODE_TYPE } from '../common/constants'; - -export function nodeAttr(ele: Element, name: string) { - return ele.getAttribute(name).trim(); -} - -export function nodeText(ele: Element) { - return ele.textContent.trim(); -} - -export function nodeHasAttr(ele: Element, name: string) { - return ele.hasAttribute(name); -} - -export function nodeNameEq(ele: Element, desiredName: string) { - return ele.nodeName === desiredName || ele.localName === desiredName; -} - -export function nodeName(ele: Element) { - if (ele.nodeName && ele.nodeName.indexOf('#') === -1) { - return ele.nodeName.trim(); - } - - if (ele.localName && ele.localName.indexOf('#') === -1) { - return ele.localName.trim(); - } - - return ''; -} - -export type callback = (node: Element) => Promise; -export type callbackSync = (node: Element) => void; -/** - * 异步遍历element子节点 - * @param ele xml element节点 - * @param callback async function - */ -export async function eachSubElement(ele: Element, callback): Promise { - const childNodes = ele.childNodes; - const len = childNodes.length; - for (let i = 0; i < len; i++) { - const node = childNodes.item(i); - // element - if (node.nodeType === NODE_TYPE.ELEMENT) { - await callback(node); - } - } -} -/** - * 同步遍历element子节点 - * @param ele xml element节点 - * @param callbackSync function - */ -export function eachSubElementSync(ele: Element, callbackSync): void { - const childNodes = ele.childNodes; - const len = childNodes.length; - for (let i = 0; i < len; i++) { - const node = childNodes.item(i); - // element - if (node.nodeType === NODE_TYPE.ELEMENT) { - callbackSync(node); - } - } -} -/** - * 获取第一个element类型子节点 - * @param ele xml element节点 - */ -export function firstSubElement(ele: Element): Element { - const childNodes = ele.childNodes; - const len = childNodes.length; - for (let i = 0; i < len; i++) { - const node = childNodes.item(i); - // element - if (node.nodeType === NODE_TYPE.ELEMENT) { - return node; - } - } - - return null; -} -/** - * 获取第一个cdata类型子节点 - * @param ele xml element节点 - */ -export function firstCDATAText(ele: Element): string { - const childNodes = ele.childNodes; - const len = childNodes.length; - for (let i = 0; i < len; i++) { - const node = childNodes.item(i); - // element - if (node.nodeType === NODE_TYPE.CDATA) { - return node.textContent.trim(); - } - } - - return ''; -} diff --git a/packages/context/src/index.ts b/packages/context/src/index.ts deleted file mode 100644 index 5a9888a5cf12..000000000000 --- a/packages/context/src/index.ts +++ /dev/null @@ -1,19 +0,0 @@ -export * from './interfaces'; -export { ScopeEnum } from './base/Scope'; -export { MessageSource } from './base/MessageSource'; -export { BaseApplicationContext as ApplicationContext } from './factory/applicationContext'; -export { ObjectDefinition } from './base/ObjectDefinition'; -export { BaseConfiguration, ObjectConfiguration } from './base/Configuration'; -export { ObjectCreator } from './base/ObjectCreator'; -export * from './factory/common/managed'; -export { Container } from './factory/container'; -export * from './annotation/index'; -export * from './utils/metaKeys'; -export * from './factory/xml/interface'; -export { XmlApplicationContext } from './factory/xml/XmlApplicationContext'; -export { XmlObjectDefinition } from './factory/xml/XmlObjectDefinition'; -export { XmlObjectDefinitionParser } from './factory/xml/XmlObjectDefinitionParser'; -export { XmlObjectElementParser } from './factory/xml/XmlObjectElementParser'; -export { Autowire } from './factory/common/Autowire'; -export { RequestContainer } from './factory/requestContainer'; -export { NODE_TYPE, KEYS, VALUE_TYPE } from './factory/common/constants'; diff --git a/packages/context/src/interfaces.ts b/packages/context/src/interfaces.ts deleted file mode 100644 index dc9dcf4f7f05..000000000000 --- a/packages/context/src/interfaces.ts +++ /dev/null @@ -1,205 +0,0 @@ -export type ObjectIdentifier = string; -export type Scope = 'Singleton' | 'Request' | 'Prototype'; - -export interface IScopeEnum { - Singleton: Scope; - Request: Scope; - Prototype: Scope; -} -/** - * 生命周期定义 - */ -export interface ILifeCycle { - key: string; - onStart(): void; - onReady(): void; - onRefresh(): void; - onStop(): void; -} - -export type Locale = string; - -/** - * 多语言支持接口 - */ -export interface IMessageSource { - get(code: string, - args?: any[], - defaultMessage?: string, - locale?: Locale): string; -} -/** - * 对象容器抽象 - * 默认用Xml容器实现一个 - */ -export interface IObjectFactory { - registry: IObjectDefinitionRegistry; - isAsync(identifier: ObjectIdentifier): boolean; - get(identifier: ObjectIdentifier, args?: any): T; - getAsync(identifier: ObjectIdentifier, args?: any): Promise; -} -/** - * 对象描述定义 - */ -export interface IObjectDefinition { - creator: IObjectCreator; - id: string; - name: string; - initMethod: string; - destroyMethod: string; - constructMethod: string; - path: any; - export: string; - dependsOn: ObjectIdentifier[]; - constructorArgs: IManagedInstance[]; - properties: IConfiguration; - isAutowire(): boolean; - isAsync(): boolean; - isSingletonScope(): boolean; - isRequestScope(): boolean; - isExternal(): boolean; - isDirect(): boolean; - hasDependsOn(): boolean; - hasConstructorArgs(): boolean; - getAttr(key: ObjectIdentifier): any; - hasAttr(key: ObjectIdentifier): boolean; - setAttr(key: ObjectIdentifier, value: any): void; -} -export interface IObjectCreator { - load(): any; - doConstruct(Clzz: any, args?: any): any; - doConstructAsync(Clzz: any, args?: any): Promise; - doInit(obj: any): void; - doInitAsync(obj: any): Promise; - doDestroy(obj: any): void; - doDestroyAsync(obj: any): Promise; -} -/** - * 对象定义存储容器 - */ -export interface IObjectDefinitionRegistry { - readonly identifiers: ObjectIdentifier[]; - readonly count: number; - registerDefinition(identifier: ObjectIdentifier, definition: IObjectDefinition); - getDefinition(identifier: ObjectIdentifier): IObjectDefinition; - getDefinitionByPath(path: string): IObjectDefinition; - getDefinitionByName(name: string): IObjectDefinition[]; - removeDefinition(identifier: ObjectIdentifier): void; - hasDefinition(identifier: ObjectIdentifier): boolean; - clearAll(): void; - hasObject(identifier: ObjectIdentifier): boolean; - registerObject(identifier: ObjectIdentifier, target: any); - getObject(identifier: ObjectIdentifier): any; -} -/** - * 属性配置抽象 - */ -export interface IConfiguration { - readonly size: number; - keys(): ObjectIdentifier[]; - get(key: ObjectIdentifier, ...args: any[]): any; - dup(key: ObjectIdentifier): any; - has(key: ObjectIdentifier): boolean; - set(key: ObjectIdentifier, value: any): any; - putAll(props: IConfiguration): void; - toJSON(): Object; - stringPropertyNames(): ObjectIdentifier[]; - getProperty(key: ObjectIdentifier, defaultValue?: any): any; - addProperty(key: ObjectIdentifier, value: any): void; - setProperty(key: ObjectIdentifier, value: any): any; - clear(): void; - clone(): IConfiguration; -} -/** - * 资源配置抽象 - */ -export interface IResource { - readonly name: string; - readonly contentLength: number; - readonly lastModified: number; - encoding: string; - exists(): boolean; - isDir(): boolean; - isFile(): boolean; - isURL(): boolean; - getURL(): any; - getPath(): string; - getContent(): Buffer; - getContentAsJSON(): Object; - getSubResources(): IResource[]; - createRelative(path: string): IResource; -} -/** - * IoC上下文抽象 - */ -export interface IApplicationContext extends IObjectFactory { - baseDir: string; - parent: IApplicationContext; - props: IConfiguration; - configLocations: string[]; - messageSource: IMessageSource; - dependencyMap: Map; - refreshAsync(): Promise; - ready(): Promise; - addLifeCycle(lifeCycle: ILifeCycle): void; - removeLifeCycle(lifeCycle: ILifeCycle): void; - stop(): Promise; - dumpDependency(): void; -} -/** - * 内部管理的属性、json、ref等解析实例存储 - */ -export interface IManagedInstance { - type: string; -} -/** - * 解析内部管理的属性、json、ref等实例的解析器 - * 同时创建这些对象的实际使用的对象 - */ -export interface IManagedResolver { - type: string; - resolve(managed: IManagedInstance): any; - resolveAsync(managed: IManagedInstance): Promise; -} - -export interface ObjectDefinitionOptions { - isAsync?: boolean; - initMethod?: string; - destroyMethod?: string; - scope?: Scope; - constructorArgs?: Array; - // 是否自动装配 - isAutowire?: boolean; -} - -/** - * 提供简化的容器绑定能力 - */ -export interface IContainer extends IApplicationContext { - bind(target: T, options?: ObjectDefinitionOptions): void ; - bind(identifier: ObjectIdentifier, target: T, options?: ObjectDefinitionOptions): void; - createChild(): IContainer; - resolve(target: T): T; - registerCustomBinding(objectDefinition: IObjectDefinition, target): void; -} - -export interface TagPropsMetadata { - key: string | number | symbol; - value: any; -} - -export interface TagClsMetadata { - id: string; - originName: string; -} - -export interface ReflectResult { - [key: string]: TagPropsMetadata[]; -} - -export interface ObjectDependencyTree { - scope: IScopeEnum; - name: string; - constructorArgs: string[]; - properties: string[]; -} diff --git a/packages/context/src/jsx.ts b/packages/context/src/jsx.ts deleted file mode 100644 index 2c3f64ba5e8a..000000000000 --- a/packages/context/src/jsx.ts +++ /dev/null @@ -1,65 +0,0 @@ -declare namespace JSX { - interface IntrinsicElements { - objects: { - external?: boolean, - path?: string, - autowire?: boolean, - direct?: boolean - }; - object: { - external?: boolean, // 是否node module - path?: string, // 路径 - autowire?: boolean, // 是否自动装配 - direct?: boolean, // 是否直接require - async?: boolean, // 是否异步 - initMethod?: string, // 初始化方法 - destroyMethod?: string, // 销毁方法 - constructMethod?: string, // 创建实例方法 - id?: string // 唯一id - }; - json: {}; - constructorArg: {}; - ref: { - object: string - }; - property: { - name: string, - ref?: string, - value?: string, - type?: string - }; - props: {}; - prop: { - key: string, - value?: string, - type?: string - }; - set: {}; - list: {}; - value: { - type?: string - }; - map: {}; - entry: { - key: string, - value?: string, - type?: string - }; - import: { - resource?: string, - external?: boolean - }; - configuration: { - path: string, - external?: boolean - }; - aspect: { - path: string, - external?: boolean - }; - around: { - expression: string, - execute: string - }; - } -} diff --git a/packages/context/src/utils/Metadata.ts b/packages/context/src/utils/Metadata.ts deleted file mode 100644 index 8863112c5f5f..000000000000 --- a/packages/context/src/utils/Metadata.ts +++ /dev/null @@ -1,23 +0,0 @@ -import {NAMED_TAG} from './metaKeys'; -import {TagPropsMetadata as DecoratorMeta} from '../interfaces'; - -class Metadata implements DecoratorMeta { - - public key: string | number | symbol; - public value: any; - - public constructor(key: string | number | symbol, value: any) { - this.key = key; - this.value = value; - } - - public toString() { - if (this.key === NAMED_TAG) { - return `named: ${this.value.toString()} `; - } else { - return `tagged: { key:${this.key.toString()}, value: ${this.value} }`; - } - } -} - -export { Metadata }; diff --git a/packages/context/src/utils/decorator.ts b/packages/context/src/utils/decorator.ts deleted file mode 100644 index b7cb67f0c834..000000000000 --- a/packages/context/src/utils/decorator.ts +++ /dev/null @@ -1,64 +0,0 @@ -import 'reflect-metadata'; -import {DUPLICATED_METADATA, INVALID_DECORATOR_OPERATION} from './errMsg'; -import {TAGGED, TAGGED_PROP} from './metaKeys'; -import {TagPropsMetadata, ReflectResult} from '../interfaces'; - -function tagParameter( - annotationTarget: any, - propertyName: string, - parameterIndex: number, - metadata: TagPropsMetadata -) { - _tagParameterOrProperty(TAGGED, annotationTarget, propertyName, metadata, parameterIndex); -} - -function tagProperty( - annotationTarget: any, - propertyName: string, - metadata: TagPropsMetadata -) { - _tagParameterOrProperty(TAGGED_PROP, annotationTarget.constructor, propertyName, metadata); -} - -function _tagParameterOrProperty( - metadataKey: string, - annotationTarget: any, - propertyName: string, - metadata: TagPropsMetadata, - parameterIndex?: number -) { - - let paramsOrPropertiesMetadata: ReflectResult = {}; - const isParameterDecorator = (typeof parameterIndex === 'number'); - const key: string = (parameterIndex !== undefined && isParameterDecorator) ? parameterIndex.toString() : propertyName; - - // if the decorator is used as a parameter decorator, the property name must be provided - if (isParameterDecorator && propertyName !== undefined) { - throw new Error(INVALID_DECORATOR_OPERATION); - } - - // read metadata if available - if (Reflect.hasOwnMetadata(metadataKey, annotationTarget)) { - paramsOrPropertiesMetadata = Reflect.getMetadata(metadataKey, annotationTarget); - } - - // get metadata for the decorated parameter by its index - let paramOrPropertyMetadata: TagPropsMetadata[] = paramsOrPropertiesMetadata[key]; - - if (!Array.isArray(paramOrPropertyMetadata)) { - paramOrPropertyMetadata = []; - } else { - for (const m of paramOrPropertyMetadata) { - if (m.key === metadata.key) { - throw new Error(`${DUPLICATED_METADATA} ${m.key.toString()}`); - } - } - } - - // set metadata - paramOrPropertyMetadata.push(metadata); - paramsOrPropertiesMetadata[key] = paramOrPropertyMetadata; - Reflect.defineMetadata(metadataKey, paramsOrPropertiesMetadata, annotationTarget); -} - -export { tagParameter, tagProperty }; diff --git a/packages/context/src/utils/errMsg.ts b/packages/context/src/utils/errMsg.ts deleted file mode 100644 index 9eb9c3d0e248..000000000000 --- a/packages/context/src/utils/errMsg.ts +++ /dev/null @@ -1,42 +0,0 @@ -export const DUPLICATED_INJECTABLE_DECORATOR = 'Cannot apply @injectable decorator multiple times.'; -export const DUPLICATED_METADATA = 'Metadata key was used more than once in a parameter:'; -export const NULL_ARGUMENT = 'NULL argument'; -export const KEY_NOT_FOUND = 'Key Not Found'; -export const AMBIGUOUS_MATCH = 'Ambiguous match found for serviceIdentifier:'; -export const CANNOT_UNBIND = 'Could not unbind serviceIdentifier:'; -export const NOT_REGISTERED = 'No matching bindings found for serviceIdentifier:'; -export const MISSING_INJECTABLE_ANNOTATION = 'Missing required @injectable annotation in:'; -export const MISSING_INJECT_ANNOTATION = 'Missing required @inject or @multiInject annotation in:'; -export const CIRCULAR_DEPENDENCY = 'Circular dependency found:'; -export const NOT_IMPLEMENTED = 'Sorry, this feature is not fully implemented yet.'; -export const INVALID_BINDING_TYPE = 'Invalid binding type:'; -export const NO_MORE_SNAPSHOTS_AVAILABLE = 'No snapshot available to restore.'; -export const INVALID_MIDDLEWARE_RETURN = 'Invalid return type in middleware. Middleware must return!'; -export const INVALID_FUNCTION_BINDING = 'Value provided to function binding must be a function!'; - -export const INVALID_TO_SELF_VALUE = 'The toSelf function can only be applied when a constructor is ' + - 'used as service identifier'; - -export const INVALID_DECORATOR_OPERATION = 'The @inject @multiInject @tagged and @named decorators ' + - 'must be applied to the parameters of a class constructor or a class property.'; - -export const ARGUMENTS_LENGTH_MISMATCH_1 = 'The number of constructor arguments in the derived class '; -export const ARGUMENTS_LENGTH_MISMATCH_2 = ' must be >= than the number of constructor arguments of its base class.'; - -export const CONTAINER_OPTIONS_MUST_BE_AN_OBJECT = 'Invalid Container constructor argument. Container options ' + - 'must be an object.'; - -export const CONTAINER_OPTIONS_INVALID_DEFAULT_SCOPE = 'Invalid Container option. Default scope must ' + - 'be a string (\'singleton\' or \'transient\').'; - -export const CONTAINER_OPTIONS_INVALID_AUTO_BIND_INJECTABLE = 'Invalid Container option. Auto bind injectable must ' + - 'be a boolean'; - -export const MULTIPLE_POST_CONSTRUCT_METHODS = 'Cannot apply @postConstruct decorator multiple times in the same class'; -export const POST_CONSTRUCT_ERROR = (...values: any[]) => `@postConstruct error in class ${values[0]}: ${values[1]}`; - -export const CIRCULAR_DEPENDENCY_IN_FACTORY = (...values: any[]) => 'It looks like there is a circular dependency ' + - `in one of the '${values[0]}' bindings. Please investigate bindings with` + - `service identifier '${values[1]}'.`; - -export const STACK_OVERFLOW = 'Maximum call stack size exceeded'; diff --git a/packages/context/src/utils/errorFactory.ts b/packages/context/src/utils/errorFactory.ts deleted file mode 100644 index 48d5c786ca6a..000000000000 --- a/packages/context/src/utils/errorFactory.ts +++ /dev/null @@ -1,17 +0,0 @@ -import { ObjectIdentifier } from '../interfaces'; - -export class NotFoundError extends Error { - static readonly type = Symbol.for('#NotFoundError'); - static isClosePrototypeOf(ins: NotFoundError): boolean { - return ins ? ins[NotFoundError.type] === NotFoundError.type : false; - } - constructor(identifier: ObjectIdentifier) { - super(`${identifier} is not valid in current context`); - this[NotFoundError.type] = NotFoundError.type; - } - updateErrorMsg(className: string): void { - const identifier = this.message.split(' is not valid in current context')[0]; - const msg = `${identifier} in class ${className} is not valid in context`; - this.message = msg; - } -} diff --git a/packages/context/src/utils/metaKeys.ts b/packages/context/src/utils/metaKeys.ts deleted file mode 100644 index 33feeafa02be..000000000000 --- a/packages/context/src/utils/metaKeys.ts +++ /dev/null @@ -1,19 +0,0 @@ -// Used for named bindings -export const NAMED_TAG = 'named'; - -// The name of the target at design time -export const INJECT_TAG = 'inject'; - -// used to store constructor arguments tags -export const TAGGED = 'midway:tagged'; - -// used to store class properties tags -export const TAGGED_PROP = 'midway:tagged_props'; - -// used to store class to be injected -export const TAGGED_CLS = 'midway:tagged_class'; - -// used to store function to be injected -export const TAGGED_FUN = 'midway:tagged_function'; - -export const OBJ_DEF_CLS = 'object_definition_class'; diff --git a/packages/context/src/utils/reflectTool.ts b/packages/context/src/utils/reflectTool.ts deleted file mode 100644 index 1414edcc9ceb..000000000000 --- a/packages/context/src/utils/reflectTool.ts +++ /dev/null @@ -1,72 +0,0 @@ -import {ReflectResult} from '../interfaces'; -import 'reflect-metadata'; - -const functionPrototype = Object.getPrototypeOf(Function); - -// get property of an object -// https://tc39.github.io/ecma262/#sec-ordinarygetprototypeof -function ordinaryGetPrototypeOf(O: any): any { - const proto = Object.getPrototypeOf(O); - if (typeof O !== 'function' || O === functionPrototype) return proto; - - // TypeScript doesn't set __proto__ in ES5, as it's non-standard. - // Try to determine the superclass constructor. Compatible implementations - // must either set __proto__ on a subclass constructor to the superclass constructor, - // or ensure each class has a valid `constructor` property on its prototype that - // points back to the constructor. - - // If this is not the same as Function.[[Prototype]], then this is definately inherited. - // This is the case when in ES6 or when using __proto__ in a compatible browser. - if (proto !== functionPrototype) return proto; - - // If the super prototype is Object.prototype, null, or undefined, then we cannot determine the heritage. - const prototype = O.prototype; - const prototypeProto = prototype && Object.getPrototypeOf(prototype); - if (prototypeProto == null || prototypeProto === Object.prototype) return proto; - - // If the constructor was not a function, then we cannot determine the heritage. - const constructor = prototypeProto.constructor; - if (typeof constructor !== 'function') return proto; - - // If we have some kind of self-reference, then we cannot determine the heritage. - if (constructor === O) return proto; - - // we have a pretty good guess at the heritage. - return constructor; -} - -/** - * 以数组形式返回对象所有 property, 数组第一个元素是距离 o 最近的原型 - * @param target 对象,class 或者 function - */ -export function recursiveGetPrototypeOf(target: any): any[] { - const properties = []; - let parent = ordinaryGetPrototypeOf(target); - while (parent !== null) { - properties.push(parent); - parent = ordinaryGetPrototypeOf(parent); - } - return properties; -} - -/** - * get metadata value of a metadata key on the prototype chain of an object and property - * @param metadataKey metadata's key - * @param target the target of metadataKey - */ -export function recursiveGetMetadata(metadataKey: any, target: any, propertyKey?: string | symbol): ReflectResult[] { - const metadatas: ReflectResult[] = []; - - // get metadata value of a metadata key on the prototype - let metadata = Reflect.getOwnMetadata(metadataKey, target, propertyKey); - metadata !== undefined && metadatas.push(metadata); - - // get metadata value of a metadata key on the prototype chain - let parent = ordinaryGetPrototypeOf(target); - while (parent !== null) { - metadata = Reflect.getOwnMetadata(metadataKey, parent, propertyKey); - metadata !== undefined && metadatas.push(metadata); - parent = ordinaryGetPrototypeOf(parent); - } - return metadatas; -} diff --git a/packages/context/test/fixtures/UserClass.ts b/packages/context/test/fixtures/UserClass.ts deleted file mode 100644 index 4ae18a8bd4a1..000000000000 --- a/packages/context/test/fixtures/UserClass.ts +++ /dev/null @@ -1,7 +0,0 @@ -export class UserClass { - userService; - - getUser() { - return this.userService.getUser(); - } -} diff --git a/packages/context/test/fixtures/app/config/config.js b/packages/context/test/fixtures/app/config/config.js deleted file mode 100644 index 4e806ab310e1..000000000000 --- a/packages/context/test/fixtures/app/config/config.js +++ /dev/null @@ -1,5 +0,0 @@ -module.exports = { - foo: { - bar: '123' - } -}; diff --git a/packages/context/test/fixtures/app/hello.js b/packages/context/test/fixtures/app/hello.js deleted file mode 100644 index b372121603b5..000000000000 --- a/packages/context/test/fixtures/app/hello.js +++ /dev/null @@ -1,46 +0,0 @@ -'use strict'; - -class Base { - ss() {} - async hhh2() { - // - } -} - -class Base1 extends Base { - ss1() {} - ss() {} - async hhh2() { - // - } -} - -class HelloA extends Base1 { - constructor(a, b, c) { - super(); - this.a = a; - this.b = b; - this.c = c; - } - static hhhll() {} - say(args, next) { - const rt = `${this.a}+${this.b}+${this.c}`; - console.log('asdfad sya', rt); - return next(); - } - hhh() { console.log('this is hhh'); } - bb(args, next) { - return next(); - } - async ccc() { - // - console.log('kajsdfa'); - return new Promise(resolve => { - setTimeout(() => { - resolve(11); - }, 1000); - }); - } -} - -module.exports = HelloA; diff --git a/packages/context/test/fixtures/app/lib/ctor/aspect.js b/packages/context/test/fixtures/app/lib/ctor/aspect.js deleted file mode 100644 index 2dcbbb802c1b..000000000000 --- a/packages/context/test/fixtures/app/lib/ctor/aspect.js +++ /dev/null @@ -1,18 +0,0 @@ -'use strict'; - -const _ = require('lodash'); - -exports.beforeSay = (args, next) => { - return 'before say' + args.length + next(); -}; - -exports.asyncAroundSay = async (args, next) => { - return _.join(args, '-') + 'asyncAroundSay say' + (await next()); -}; - -exports.aroundSay = (args, next) => { - const b = _.join(args, '-') + 'before exec'; - const rt = next(); - const c = 'after exec'; - return `${b}+${rt}+${c}`; -}; diff --git a/packages/context/test/fixtures/app/lib/ctor/async.js b/packages/context/test/fixtures/app/lib/ctor/async.js deleted file mode 100644 index 50d7238da59c..000000000000 --- a/packages/context/test/fixtures/app/lib/ctor/async.js +++ /dev/null @@ -1,48 +0,0 @@ -'use strict'; - -const Base = require('sdk-base'); - -class AsyncTest { - async hello(name) { - return new Promise(resolve => { - setTimeout(() => { - resolve(`hello ${name}`); - }, 1000); - }); - } -} - -const aa1 = new AsyncTest(); - -class ReadyTest extends Base { - async say(name) { - return new Promise(resolve => { - setTimeout(() => { - resolve(`hello ${name}`); - }, 1000); - }); - } - - saySync(name) { - return `hello ${name} sync.`; - } -} - -const rr = new ReadyTest(); - -module.exports = { - getInstance() { - return new Promise(resolve => { - setTimeout(() => { - resolve(aa1); - }, 500); - }); - }, - - getReady() { - setTimeout(() => { - rr.ready(true); - }, 1500); - return rr; - } -}; diff --git a/packages/context/test/fixtures/app/lib/ctor/obj1.js b/packages/context/test/fixtures/app/lib/ctor/obj1.js deleted file mode 100644 index b63d044c8035..000000000000 --- a/packages/context/test/fixtures/app/lib/ctor/obj1.js +++ /dev/null @@ -1,13 +0,0 @@ -'use strict'; - -module.exports = class Obj1 { - constructor(a, b, c) { - this.a = a; - this.b = b; - this.c = c; - } - - say() { - return 'say hello'; - } -}; diff --git a/packages/context/test/fixtures/app/lib/ctor/obj2.js b/packages/context/test/fixtures/app/lib/ctor/obj2.js deleted file mode 100644 index d7c8ac067fce..000000000000 --- a/packages/context/test/fixtures/app/lib/ctor/obj2.js +++ /dev/null @@ -1,19 +0,0 @@ -'use strict'; - -module.exports = class Obj2 { - static getInstance() { - return new Obj2(); - } - - say1() { - return 'say1 hello'; - } - - async say2() { - return new Promise(resolve => { - setTimeout(() => { - resolve('say2 hello'); - }, 500); - }); - } -}; diff --git a/packages/context/test/fixtures/app/lib/ctor/obj3.js b/packages/context/test/fixtures/app/lib/ctor/obj3.js deleted file mode 100644 index 842130ebd58f..000000000000 --- a/packages/context/test/fixtures/app/lib/ctor/obj3.js +++ /dev/null @@ -1,12 +0,0 @@ -'use strict'; - -class Obj3 { - constructor() { - this.cowboy = null; - } - say() { - return 'hello'; - } -} - -module.exports = new Obj3(); diff --git a/packages/context/test/fixtures/app/lib/ctor/obj4.js b/packages/context/test/fixtures/app/lib/ctor/obj4.js deleted file mode 100644 index a118d70045e3..000000000000 --- a/packages/context/test/fixtures/app/lib/ctor/obj4.js +++ /dev/null @@ -1,5 +0,0 @@ -'use strict'; - -module.exports = class Obj4 { - -}; diff --git a/packages/context/test/fixtures/app/lib/ctor/obj5.js b/packages/context/test/fixtures/app/lib/ctor/obj5.js deleted file mode 100644 index 5cfa541854b3..000000000000 --- a/packages/context/test/fixtures/app/lib/ctor/obj5.js +++ /dev/null @@ -1,7 +0,0 @@ -'use strict'; - -module.exports = class Obj5 { - constructor() { - this.name = 'obj5'; - } -}; diff --git a/packages/context/test/fixtures/app/lib/ctor/obj6.js b/packages/context/test/fixtures/app/lib/ctor/obj6.js deleted file mode 100644 index 3f6dd8c18bb6..000000000000 --- a/packages/context/test/fixtures/app/lib/ctor/obj6.js +++ /dev/null @@ -1,11 +0,0 @@ -let i = 0; -module.exports = { - getData() { - const now = Date.now(); - const index = i++; - return { - now, - index - } - } -} \ No newline at end of file diff --git a/packages/context/test/fixtures/app/lib/ctor/obj7.js b/packages/context/test/fixtures/app/lib/ctor/obj7.js deleted file mode 100644 index f79d210d0fb1..000000000000 --- a/packages/context/test/fixtures/app/lib/ctor/obj7.js +++ /dev/null @@ -1,13 +0,0 @@ -const assert = require('assert'); - -module.exports = class Obj7 { - constructor(options) { - assert(options.hello, 'hello is null') - console.log(options); - this.options = options; - } - - getHello() { - return this.options.hello; - } -} \ No newline at end of file diff --git a/packages/context/test/fixtures/app/lib/list/obj1.js b/packages/context/test/fixtures/app/lib/list/obj1.js deleted file mode 100644 index 331ee7d392e3..000000000000 --- a/packages/context/test/fixtures/app/lib/list/obj1.js +++ /dev/null @@ -1,5 +0,0 @@ -'use strict'; - -module.exports = class Obj1 { - -}; diff --git a/packages/context/test/fixtures/app/lib/list/obj2.js b/packages/context/test/fixtures/app/lib/list/obj2.js deleted file mode 100644 index fbbcd3a2bc08..000000000000 --- a/packages/context/test/fixtures/app/lib/list/obj2.js +++ /dev/null @@ -1,5 +0,0 @@ -'use strict'; - -module.exports = class Obj2 { - -}; diff --git a/packages/context/test/fixtures/app/lib/list/obj3.js b/packages/context/test/fixtures/app/lib/list/obj3.js deleted file mode 100644 index 10d3e6c56482..000000000000 --- a/packages/context/test/fixtures/app/lib/list/obj3.js +++ /dev/null @@ -1,5 +0,0 @@ -'use strict'; - -module.exports = class Obj3 { - -}; diff --git a/packages/context/test/fixtures/app/lib/object/bar.js b/packages/context/test/fixtures/app/lib/object/bar.js deleted file mode 100644 index 4e4821ce8232..000000000000 --- a/packages/context/test/fixtures/app/lib/object/bar.js +++ /dev/null @@ -1,8 +0,0 @@ -'use strict'; -const {Autowire} = require('../../../../../src/factory/common/Autowire'); -module.exports = class Bar { - constructor() { - this.cowboy = null; - this.inject = Autowire.createInject('obj:bcd'); - } -}; diff --git a/packages/context/test/fixtures/app/lib/object/bcd.js b/packages/context/test/fixtures/app/lib/object/bcd.js deleted file mode 100644 index 4ec3bc0f0fd7..000000000000 --- a/packages/context/test/fixtures/app/lib/object/bcd.js +++ /dev/null @@ -1,9 +0,0 @@ -'use strict'; - -module.exports = class BCD { - - constructor() { - this.cowboy = null; - } - -}; diff --git a/packages/context/test/fixtures/app/locales/en.json b/packages/context/test/fixtures/app/locales/en.json deleted file mode 100644 index b8aaa2b85bf3..000000000000 --- a/packages/context/test/fixtures/app/locales/en.json +++ /dev/null @@ -1,3 +0,0 @@ -{ - "hello": "this is hello en" -} diff --git a/packages/context/test/fixtures/app/locales/zh-cn.json b/packages/context/test/fixtures/app/locales/zh-cn.json deleted file mode 100644 index ac75980f7de4..000000000000 --- a/packages/context/test/fixtures/app/locales/zh-cn.json +++ /dev/null @@ -1,4 +0,0 @@ -{ - "hello": "这是一个测试", - "this is": "a test %s" -} diff --git a/packages/context/test/fixtures/app/node_modules/hello/index.js b/packages/context/test/fixtures/app/node_modules/hello/index.js deleted file mode 100644 index f50bd9a36ddf..000000000000 --- a/packages/context/test/fixtures/app/node_modules/hello/index.js +++ /dev/null @@ -1,49 +0,0 @@ -'use strict'; - -class Base { - ss() {} - async hhh2() { - // - } -} - -class Base1 extends Base { - ss1() {} - ss() {} - async hhh2() { - // - } -} - -class HelloA extends Base1 { - constructor(a, b, c) { - super(); - this.a = a; - this.b = b; - this.c = c; - - this.autowireFalse = null; - } - - static hhhll() {} - say(args, next) { - const rt = `${this.a}+${this.b}+${this.c}`; - console.log('asdfad sya', rt); - return next(); - } - hhh() { console.log('this is hhh'); } - bb(args, next) { - return next(); - } - async ccc() { - // - console.log('kajsdfa'); - return new Promise(resolve => { - setTimeout(() => { - resolve(11); - }, 1000); - }); - } -} - -module.exports = HelloA; diff --git a/packages/context/test/fixtures/app/node_modules/hello/package.json b/packages/context/test/fixtures/app/node_modules/hello/package.json deleted file mode 100644 index 8b68e8250725..000000000000 --- a/packages/context/test/fixtures/app/node_modules/hello/package.json +++ /dev/null @@ -1,14 +0,0 @@ -{ - "name": "hello", - "version": "1.0.0", - "description": "test hello", - "main": "index.js", - "scripts": { - "test": "echo \"Error: no test specified\" && exit 1" - }, - "keywords": [ - "hello" - ], - "author": "mf", - "license": "ISC" -} diff --git a/packages/context/test/fixtures/app/resources/construction.xml b/packages/context/test/fixtures/app/resources/construction.xml deleted file mode 100644 index cbe0b028304e..000000000000 --- a/packages/context/test/fixtures/app/resources/construction.xml +++ /dev/null @@ -1,107 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - asdfa - 123 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - INDIA - Pakistan - USA - USA - - - - - diff --git a/packages/context/test/fixtures/app/resources/context.xml b/packages/context/test/fixtures/app/resources/context.xml deleted file mode 100644 index 57322c7894f7..000000000000 --- a/packages/context/test/fixtures/app/resources/context.xml +++ /dev/null @@ -1,9 +0,0 @@ - - - - - - - - - diff --git a/packages/context/test/fixtures/app/resources/list.xml b/packages/context/test/fixtures/app/resources/list.xml deleted file mode 100644 index a4a5bf7eec37..000000000000 --- a/packages/context/test/fixtures/app/resources/list.xml +++ /dev/null @@ -1,45 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/packages/context/test/fixtures/app/resources/mixin.xml b/packages/context/test/fixtures/app/resources/mixin.xml deleted file mode 100644 index 96efdbf702cd..000000000000 --- a/packages/context/test/fixtures/app/resources/mixin.xml +++ /dev/null @@ -1,16 +0,0 @@ - - - - - - - - - - - - - - - - diff --git a/packages/context/test/fixtures/app/resources/object.xml b/packages/context/test/fixtures/app/resources/object.xml deleted file mode 100644 index d1c7347fa192..000000000000 --- a/packages/context/test/fixtures/app/resources/object.xml +++ /dev/null @@ -1,20 +0,0 @@ - - - - - - - - - - - - - - - - - - - - diff --git a/packages/context/test/fixtures/app/simple.js b/packages/context/test/fixtures/app/simple.js deleted file mode 100644 index 5d027b8bab82..000000000000 --- a/packages/context/test/fixtures/app/simple.js +++ /dev/null @@ -1,6 +0,0 @@ -'use strict'; - -module.exports = { - get() {}, - hhh() {} -}; diff --git a/packages/context/test/fixtures/class_sample.ts b/packages/context/test/fixtures/class_sample.ts deleted file mode 100644 index 096a90521dca..000000000000 --- a/packages/context/test/fixtures/class_sample.ts +++ /dev/null @@ -1,79 +0,0 @@ -import {async, destroy, init, inject, provide} from '../../src'; - -export interface Warrior { - katana1; - katana2; -} - -export class Katana { -} - -export class Ninja implements Warrior { - katana1; - katana2; -} - -export class Samurai implements Warrior { - @inject('katana1') - katana1: Katana; - @inject('katana2') - katana2: Katana; -} - -export class BaseService { - foodNumber = 10; - - @init() - async open() { - this.foodNumber = 20; - } -} - -@async() -@provide('serviceAsync') -export class BaseServiceAsync { - - foodNumber = 10; - - @init() - async open() { - this.foodNumber = 20; - } - - @destroy() - async destroy() { - } -} - -@async() -@provide('serviceGenerator') -export class BaseServiceGenerator { - - foodNumber = 10; - - @init() - *open() { - this.foodNumber = 20; - } - - @destroy() - async destroy() { - } -} - - -export class Parent { - @inject('katana1') - katana1: Katana; -} - -export class Child extends Parent { - @inject('katana2') - katana2: Katana; -} - -export class Grandson extends Child { - @inject('katana3') - katana3: Katana; -} - diff --git a/packages/context/test/fixtures/class_sample_car.ts b/packages/context/test/fixtures/class_sample_car.ts deleted file mode 100644 index 0876ef811cd0..000000000000 --- a/packages/context/test/fixtures/class_sample_car.ts +++ /dev/null @@ -1,97 +0,0 @@ -import {inject} from '../../src'; - -export interface Engine { - start(fuel: Fuel); -} - -export class Turbo implements Engine { - start(fuel: Fuel) { - fuel.burn(); - } -} - -export interface Fuel { - capacity: number; - burn(); - add(capacity: number); -} - -export class Gas implements Fuel { - - capacity = 0; - - burn() { - this.capacity -= 5; - } - - add(capacity) { - this.capacity += capacity; - } -} - -export class Electricity implements Fuel { - - capacity = 60; - - burn() { - this.capacity -= 10; - } - - add(capacity) { - this.capacity += capacity; - } -} - -export class Car { - - private engine: Engine; - protected fuel: Fuel; - - constructor( - @inject('engine') engine: Engine, - @inject() fuel: Fuel - ) { - this.engine = engine; - this.fuel = fuel; - this.fuel.add(40); - } - - public run() { - return this.engine.start(this.fuel); - } - - getFuelCapacity() { - return this.fuel.capacity; - } - - getBrand() { - } -} - -export class Tesla extends Car { - private computer; - - constructor( - @inject('engine') engine: Engine, - computer, - @inject() fuel: Fuel - ) { - super(engine, fuel); - this.computer = computer; - this.fuel.add(40); - } - - getComputer() { - return this.computer; - } - - getBrand() { - return 'tesla'; - } -} - -export class BMWX1 extends Car { - getBrand() { - return 'bmw'; - } -} diff --git a/packages/context/test/fixtures/complex_injection/dbAPI.ts b/packages/context/test/fixtures/complex_injection/dbAPI.ts deleted file mode 100644 index 7db8365a9390..000000000000 --- a/packages/context/test/fixtures/complex_injection/dbAPI.ts +++ /dev/null @@ -1,34 +0,0 @@ -import { inject, provide, scope, ScopeEnum } from '../../../src'; - -@provide() -export class A { - config = { - c: 1 - }; -} - -@provide() -export class B { - config = { - c: 2 - }; -} - -@scope(ScopeEnum.Singleton) -@provide('newKey') -export class DbAPI { - - private config; - - constructor( - @inject() a, - hello, - @inject() b, - ) { - this.config = a.config.c + b.config.c; - } - - output() { - console.log(this.config); - } -} diff --git a/packages/context/test/fixtures/complex_injection/userController.ts b/packages/context/test/fixtures/complex_injection/userController.ts deleted file mode 100644 index fa689031f1c7..000000000000 --- a/packages/context/test/fixtures/complex_injection/userController.ts +++ /dev/null @@ -1,22 +0,0 @@ -import { UserService } from './userService'; -import { inject, scope, ScopeEnum } from '../../../src/'; - -@scope(ScopeEnum.Request) -export class UserController { - - @inject('ctx') - ctx; - - @inject('newKey') - dbApi; - - @inject() - userService: UserService; - - async index() { - const {ctx} = this; - ctx.body = await this.userService.getUsers(); - ctx.status = 200; - } - -} diff --git a/packages/context/test/fixtures/complex_injection/userService.ts b/packages/context/test/fixtures/complex_injection/userService.ts deleted file mode 100644 index d9832afef313..000000000000 --- a/packages/context/test/fixtures/complex_injection/userService.ts +++ /dev/null @@ -1,13 +0,0 @@ -import { scope, ScopeEnum } from '../../../src/'; - -@scope(ScopeEnum.Request) -export class UserService { - - async getUsers() { - return new Promise(resolve => { - setTimeout(() => { - resolve(['harry', 'jiakun.du']); - }, 100); - }); - } -} diff --git a/packages/context/test/fixtures/fun_sample.ts b/packages/context/test/fixtures/fun_sample.ts deleted file mode 100644 index b6d75b650dc2..000000000000 --- a/packages/context/test/fixtures/fun_sample.ts +++ /dev/null @@ -1,60 +0,0 @@ -import {IApplicationContext} from '../../src'; - -export function testInjectFunction(context: IApplicationContext) { - const child: any = context.get('child'); - return child.a + child.b; -} - -export function childFunction() { - return { - a: 1, - b: 2 - }; -} - -// providerWrapper([ -// { -// id: 'parentAsync', -// provider: testInjectAsyncFunction -// }, -// { -// id: 'childAsync', -// provider: childAsyncFunction -// } -// ]); - -export async function testInjectAsyncFunction(context: IApplicationContext) { - const child: any = await context.getAsync('childAsync'); - return child.c + child.d; -} - -export async function childAsyncFunction(context: IApplicationContext) { - return new Promise((resolve) => { - setTimeout(() => { - resolve({ - c: 3, - d: 4 - }); - }, 10); - }); -} - -// class AdapterFactory { -// -// @inject() -// factory: (context) => adapter; -// -// async get(name) { -// if(name === 'aone') { -// return context.get('aoneAdapter'); -// } else if(name === 'labs') { -// return context.get('labsAdapter'); -// } -// } -// } -// -// export function(seq) { -// return seq.define({ -// -// }); -// } diff --git a/packages/context/test/fixtures/js-app-inject/app.js b/packages/context/test/fixtures/js-app-inject/app.js deleted file mode 100644 index f69e81593ec0..000000000000 --- a/packages/context/test/fixtures/js-app-inject/app.js +++ /dev/null @@ -1,12 +0,0 @@ -class App { - - constructor() { - this.loader = null; - } - - getConfig() { - return this.loader.getConfig(); - } -} - -module.exports = App; diff --git a/packages/context/test/fixtures/js-app-inject/loader.js b/packages/context/test/fixtures/js-app-inject/loader.js deleted file mode 100644 index 45d5522d8f80..000000000000 --- a/packages/context/test/fixtures/js-app-inject/loader.js +++ /dev/null @@ -1,14 +0,0 @@ -class Loader { - getConfig() { - return {a: 1, b: 2}; - } -} - -class EasyLoader extends Loader { - getConfig() { - return {a: 3, b: 4}; - } -} - -exports.Loader = Loader; -exports.EasyLoader = EasyLoader; diff --git a/packages/context/test/fixtures/mix_sample.ts b/packages/context/test/fixtures/mix_sample.ts deleted file mode 100644 index 9fc37d1a972b..000000000000 --- a/packages/context/test/fixtures/mix_sample.ts +++ /dev/null @@ -1,46 +0,0 @@ -import {inject, provide, scope} from '../../src/annotation'; -import {ScopeEnum} from '../../src'; - -interface Engine { - capacity; -} - -@scope(ScopeEnum.Prototype) -@provide('petrol') -export class PetrolEngine implements Engine { - capacity = 10; -} - -@scope(ScopeEnum.Prototype) -@provide('diesel') -export class DieselEngine implements Engine { - capacity = 20; -} - -export function engineFactory(context) { - return (named: string) => { - return context.get(named); - }; -} - -interface CarFactory { - -} - -@provide() -export class DieselCar implements CarFactory { - dieselEngine: Engine; - backUpDieselEngine: Engine; - - constructor( - @inject('engineFactory') factory: (category: string) => Engine - ) { - this.dieselEngine = factory('diesel'); - this.backUpDieselEngine = factory('diesel'); - } - - run() { - this.dieselEngine.capacity -= 5; - } - -} diff --git a/packages/context/test/unit/base/Configuration.test.ts b/packages/context/test/unit/base/Configuration.test.ts deleted file mode 100644 index db0304861243..000000000000 --- a/packages/context/test/unit/base/Configuration.test.ts +++ /dev/null @@ -1,125 +0,0 @@ -import {BasicConfiguration, ObjectConfiguration} from '../../../src/base/Configuration'; -import {expect} from 'chai'; - -describe('/test/unit/base/Configuration', () => { - describe('#BasicConfiguration', () => { - it('test basic config ok', () => { - const config = new BasicConfiguration(); - expect(config.dup('this is a emtpy dup')).null; - - config.set('aa', 1); - config.set('bb', 2); - config.set('cc', 'hello world'); - config.set('ee', {dd: 'test dd', aa: 'hello'}); - - const json = config.toJSON(); - expect(json).deep.eq({ - aa: 1, - bb: 2, - cc: 'hello world', - ee: {dd: 'test dd', aa: 'hello'} - }); - expect(config.keys()).deep.eq([ - 'aa', 'bb', 'cc', 'ee' - ]); - - expect(config.has('aa')).true; - expect(config.has('dd')).false; - expect(config.get('cc')).eq('hello world'); - expect(config.dup('ee')).deep.eq({dd: 'test dd', aa: 'hello'}); - - const config1 = new ObjectConfiguration(); - config1.set('aa', 22); - config1.set('bb', '1243'); - config1.set('ee', {dd: '222', ff: 123}); - - config.putAll(config1); - - expect(config.get('aa')).eq(22); - expect(config.get('bb')).eq('1243'); - expect(config.set('bb', '111')).eq('1243'); - expect(config.get('ee')).deep.eq({dd: '222', ff: 123, aa: 'hello'}); - - expect(config.size).greaterThan(1); - config.clear(); - expect(config.size).eq(0); - - config.set('ccc', 'this is %s-%s test'); - expect(config.get('ccc', 'mf', 'hhh')).eq('this is mf-hhh test'); - }); - }); - - describe('#ObjectConfiguration', () => { - it('test object config ok', () => { - const config = new ObjectConfiguration(); - expect(config.dup('this is a empty dup')).null; - - config.set('aa', 1); - config.set('bb', 2); - config.set('cc', 'hello world'); - config.set('ee', {dd: 'test dd', aa: 'hello'}); - - expect(config.has('aa')).true; - expect(config.has('dd')).false; - expect(config.get('cc')).eq('hello world'); - const dupee = config.dup('ee'); - expect(dupee).deep.eq({dd: 'test dd', aa: 'hello'}); - - const ee = config.get('ee'); - config.get('ee').dd = '123'; - expect(ee.dd).eq('123'); - expect(dupee).not.deep.eq(ee); - - const config1 = new ObjectConfiguration(); - config1.set('aa', 22); - config1.set('bb', '1243'); - config1.set('ee', {dd: '222', ff: 123}); - - config.putAll(config1); - - expect(config.get('aa')).eq(22); - expect(config.get('bb')).eq('1243'); - expect(config.set('bb', '111')).eq('1243'); - expect(config.get('ee')).deep.eq({dd: '222', ff: 123, aa: 'hello'}); - - expect(config.size).greaterThan(1); - config.clear(); - expect(config.size).eq(0); - - config1.set('ccc', 'this is %s-%s test'); - expect(config1.get('ccc', 'mf', 'hhh')).eq('this is mf-hhh test'); - }); - it('test clone should be ok', () => { - const config1 = new ObjectConfiguration(); - config1.set('aa', 22); - config1.set('bb', '1243'); - config1.set('ee', {dd: '222', ff: 123}); - - const config2 = config1.clone(); - expect(config2.get('aa')).eq(22); - expect(config2.get('bb')).eq('1243'); - expect(config2.set('bb', '111')).eq('1243'); - expect(config2.get('ee')).deep.eq({dd: '222', ff: 123}); - }); - it('test putObject needClone should be ok', () => { - const config1 = new ObjectConfiguration(); - config1.set('aa', 22); - config1.set('bb', '1243'); - const aa = { - b: 1, - c: {a: '232'} - }; - config1.putObject(aa, true); - aa.c.a = '123'; - expect(config1.get('c.a')).eq('232'); - - const bb = { - bb: 1, - cc: {aaa: '232'} - }; - config1.putObject(bb); - bb.cc.aaa = '123'; - expect(config1.get('cc.aaa')).eq('123'); - }); - }); -}); diff --git a/packages/context/test/unit/base/MessageSource.test.ts b/packages/context/test/unit/base/MessageSource.test.ts deleted file mode 100644 index 86ebb091aa43..000000000000 --- a/packages/context/test/unit/base/MessageSource.test.ts +++ /dev/null @@ -1,42 +0,0 @@ - -import * as path from 'path'; -import { MessageSource } from '../../../src/base/MessageSource'; -import { Resource } from '../../../src/base/Resource'; - -import { expect } from 'chai'; - -const dir = path.resolve(__dirname, '../../fixtures/app/locales'); - -describe('/test/unit/base/MessageSource', () => { - it('message source test ok', async () => { - const source = new MessageSource('zh-cn'); - const res = new Resource(dir, 'zh-cn.json'); - await source.load('zh-cn', res); - await source.load('en', res.createRelative('en.json')); - - expect(source.getMessage('hello')).eq('这是一个测试'); - expect(source.getMessage('new', [], 'by name')).eq('by name'); - expect(source.getMessage('hello', [], '', 'en')).eq('this is hello en'); - expect(source.getMessage('this is', ['basic'])).eq('a test basic'); - }); - it('message source load dir should ok', async () => { - const source = new MessageSource('zh-cn'); - const res = new Resource(dir, '.'); - await source.load('zh-cn', res); - - expect(source.getMessage('hello')).eq('这是一个测试'); - expect(source.getMessage('new', [], 'by name')).eq('by name'); - expect(source.getMessage('this is', ['basic'])).eq('a test basic'); - expect(source.getMessage('hello', [], '', 'en')).is.null; - }); - it('message source load use file name should ok', async () => { - const source = new MessageSource('zh-cn'); - const res = new Resource(dir, '.'); - await source.loadUseFileName(res); - - expect(source.getMessage('hello')).eq('这是一个测试'); - expect(source.getMessage('new', [], 'by name')).eq('by name'); - expect(source.getMessage('this is', ['basic'])).eq('a test basic'); - expect(source.getMessage('hello', [], '', 'en')).eq('this is hello en'); - }); -}); diff --git a/packages/context/test/unit/base/ObjectCreator.test.ts b/packages/context/test/unit/base/ObjectCreator.test.ts deleted file mode 100644 index 289f8468939b..000000000000 --- a/packages/context/test/unit/base/ObjectCreator.test.ts +++ /dev/null @@ -1,3 +0,0 @@ -describe('', () => { - -}); diff --git a/packages/context/test/unit/base/ObjectDefinition.test.ts b/packages/context/test/unit/base/ObjectDefinition.test.ts deleted file mode 100644 index 27f02f77c122..000000000000 --- a/packages/context/test/unit/base/ObjectDefinition.test.ts +++ /dev/null @@ -1,31 +0,0 @@ -import {expect} from 'chai'; -import {ObjectDefinition} from '../../../src/base/ObjectDefinition'; -import { ScopeEnum } from '../../../src/base/Scope'; - -describe('/test/unit/base/ObjectDefinition', () => { - it('definition should be ok', () => { - const definition = new ObjectDefinition(); - expect(definition.isAsync()).false; - definition.asynchronous = true; - expect(definition.isAsync()).true; - expect(definition.isAutowire()).true; - definition.autowire = true; - expect(definition.isAutowire()).true; - - definition.scope = ScopeEnum.Prototype; - expect(definition.isRequestScope()).false; - expect(definition.isSingletonScope()).false; - - expect(definition.isExternal()).false; - definition.external = true; - expect(definition.isExternal()).true; - - expect(definition.isDirect()).false; - definition.direct = true; - expect(definition.isDirect()).true; - - definition.setAttr('hello', 1); - expect(definition.getAttr('hello')).eq(1); - expect(definition.hasAttr('hello')).true; - }); -}); diff --git a/packages/context/test/unit/base/Resource.test.ts b/packages/context/test/unit/base/Resource.test.ts deleted file mode 100644 index 558976ccddea..000000000000 --- a/packages/context/test/unit/base/Resource.test.ts +++ /dev/null @@ -1,72 +0,0 @@ - -import { Resource } from '../../../src/base/Resource'; -import { expect } from 'chai'; -import * as sinon from 'sinon'; - -describe('/test/unit/base/Resource', () => { - it('resource test ok', async () => { - const res = new Resource(__dirname, 'Configuration.test.ts'); - expect(res.isFile()).true; - expect(res.name).eq('Configuration.test'); - - const c = await res.getContent(); - expect(c).not.null; - const relres = res.createRelative('Resource.test.ts'); - expect(relres.isFile()).true; - expect(relres.name).eq('Resource.test'); - - - const res1 = new Resource(__dirname, '../base'); - expect(res1.isDir()).true; - const reses = await res1.getSubResources(); - expect(reses.length).greaterThan(1); - expect(reses[0].isFile()).true; - const buf1 = await reses[0].getContent(); - expect(buf1).not.null; - }); - - it('dir resource test should ok', async () => { - const res = new Resource(process.cwd(), '.'); - expect(res.getPath()).eq(process.cwd()); - expect(res.isDir()).true; - const reses = await res.getSubResources(); - expect(reses.length).greaterThan(1); - - const callback = sinon.spy(); - try { - await res.getContent(); - } catch (e) { - callback(e.message); - } - try { - await res.getContentAsJSON(); - } catch (e) { - callback(e.message); - } - expect(callback.called).true; - expect(callback.callCount).eq(2); - expect(callback.lastCall.args[0]).eq(`${res.getPath()} is not a file!`); - - const rlres = res.createRelative('package.json'); - const c = await rlres.getContent(); - expect(c).not.null; - expect(rlres.isFile()); - expect(rlres.getURL()).null; - expect(await rlres.getContentAsJSON()).not.null; - expect(await rlres.getSubResources()).deep.eq([]); - expect(rlres.contentLength).greaterThan(0); - expect(rlres.lastModified).greaterThan(0); - }); - it('file resource not exist', async () => { - const res = new Resource(null, 'http://www.hello.com/hhh/111'); - expect(res.getPath()).eq('http://www.hello.com/hhh/111'); - expect(res.isURL()).true; - expect(res.getURL()).not.null; - expect(res.contentLength).eq(0); - expect(res.lastModified).eq(0); - expect(res.name).null; - // expect(await res.getContent()).null; - // expect(await res.getContentAsJSON()).deep.eq({}); - // expect(await res.getSubResources()).deep.eq([]); - }); -}); diff --git a/packages/context/test/unit/container.test.ts b/packages/context/test/unit/container.test.ts deleted file mode 100644 index 9a356b1d447f..000000000000 --- a/packages/context/test/unit/container.test.ts +++ /dev/null @@ -1,285 +0,0 @@ -import { Container } from '../../src/index'; -import { expect } from 'chai'; -import { - Grandson, - Child, - Parent, - BaseService, - BaseServiceAsync, - BaseServiceGenerator, - Katana, - Ninja, - Samurai, - Warrior -} from '../fixtures/class_sample'; -import { recursiveGetMetadata } from '../../src/utils/reflectTool'; -import { TAGGED_PROP } from '../../src/index'; -import 'reflect-metadata'; - -import { BMWX1, Car, Electricity, Gas, Tesla, Turbo } from '../fixtures/class_sample_car'; -import { childAsyncFunction, childFunction, testInjectAsyncFunction, testInjectFunction } from '../fixtures/fun_sample'; -import { DieselCar, DieselEngine, engineFactory, PetrolEngine } from '../fixtures/mix_sample'; -import { UserService } from '../fixtures/complex_injection/userService'; -import { UserController } from '../fixtures/complex_injection/userController'; -import { A, B, DbAPI } from '../fixtures/complex_injection/dbAPI'; - -const path = require('path'); - -describe('/test/unit/container.test.ts', () => { - - it('Should be able to store bindings', () => { - const ninjaId = 'Ninja'; - const container = new Container(); - container.bind(ninjaId, Ninja); - const ninja = container.get(ninjaId); - expect(ninja instanceof Ninja).to.be.true; - }); - - it('Should have an unique identifier', () => { - const container1 = new Container(); - const container2 = new Container(); - expect(container1.id.length).eql(36); - expect(container2.id.length).eql(36); - expect(container1.id).not.eql(container2.id); - }); - - it('should inject property', () => { - const container = new Container(); - container.bind('warrior', Samurai); - container.bind('katana1', Katana); - container.bind('katana2', Katana); - const warrior = container.get('warrior'); - expect(warrior instanceof Samurai).to.be.true; - expect(warrior.katana1).not.to.be.undefined; - expect(warrior.katana2).not.to.be.undefined; - }); - - it('should inject attributes that on the prototype chain and property', () => { - const container = new Container(); - container.bind('grandson', Grandson); - container.bind('katana1', Katana); - container.bind('katana2', Katana); - container.bind('katana3', Katana); - const grandson = container.get('grandson'); - expect(grandson instanceof Child).to.be.true; - expect(grandson instanceof Parent).to.be.true; - expect(grandson.katana1).not.to.be.undefined; - expect(grandson.katana2).not.to.be.undefined; - expect(grandson.katana3).not.to.be.undefined; - }); - - it('should get all metaDatas that on the prototype chain and property', () => { - const container = new Container(); - container.bind('grandson', Grandson); - container.bind('child', Child); - container.bind('parent', Parent); - container.bind('katana1', Katana); - container.bind('katana2', Katana); - container.bind('katana3', Katana); - const metadatas = ['grandson', 'child', 'parent'].map(function (identifier) { - const defition = container.registry.getDefinition(identifier); - const tareget = defition.path; - return { - recursiveMetadata: recursiveGetMetadata(TAGGED_PROP, tareget), - ownMetadata: Reflect.getOwnMetadata(TAGGED_PROP, tareget), - }; - }); - const grandsonMetadata = metadatas[0]; - const childMetadata = metadatas[1]; - const parentMetadata = metadatas[2]; - - expect(grandsonMetadata.recursiveMetadata) - .to.have.lengthOf(3) - .include(grandsonMetadata.ownMetadata); - expect(childMetadata.recursiveMetadata) - .to.have.lengthOf(2) - .include(childMetadata.ownMetadata); - expect(parentMetadata.recursiveMetadata) - .to.have.lengthOf(1) - .include(parentMetadata.ownMetadata); - - expect(grandsonMetadata.recursiveMetadata).to.deep.equal([ - grandsonMetadata.ownMetadata, - childMetadata.ownMetadata, - parentMetadata.ownMetadata - ]); - expect(grandsonMetadata.recursiveMetadata).to.deep.equal([ - grandsonMetadata.ownMetadata, - ...childMetadata.recursiveMetadata, - ]); - expect(grandsonMetadata.recursiveMetadata).to.deep.equal([ - grandsonMetadata.ownMetadata, - childMetadata.ownMetadata, - ...parentMetadata.recursiveMetadata - ]); - }); - - it('should throw error with class name when injected property error', async () => { - const container = new Container(); - container.bind('grandson', Grandson); - - expect(function () { container.get('grandson'); }).to.throw(Error, /Grandson/); - expect(function () { container.get('nograndson'); }).to.throw(Error, /nograndson/); - - try { - await container.getAsync('grandson'); - } catch (error) { - expect(function () { throw error; }).to.throw(Error, /Grandson/); - } - try { - await container.getAsync('nograndson'); - } catch (error) { - expect(function () { throw error; }).to.throw(Error, /nograndson/); - } - }); - - - it('should load js dir and inject with $', () => { - const container = new Container(); - container.bind('app', require(path.join(__dirname, '../fixtures/js-app-inject', 'app.js'))); - container.bind('loader', require(path.join(__dirname, '../fixtures/js-app-inject', 'loader.js')).Loader); - const app: any = container.get('app'); - expect(app.getConfig().a).to.equal(1); - }); - - it('should bind class directly', () => { - const container = new Container(); - container.bind(Katana); - const ins1 = container.get(Katana); - const ins2 = container.get('katana'); - expect(ins1).to.equal(ins2); - }); - - it('should resolve instance', async() => { - const container = new Container(); - const ins1 = container.resolve(Katana); - expect(ins1 instanceof Katana).to.be.true; - expect(() => { - container.get(Katana); - }).to.throw(/is not valid in current context/); - - try { - await container.getAsync(Katana); - } catch (error) { - expect(function () { throw error; }).to.throw(/is not valid in current context/); - } - }); - - it('should use get async method replace get', async () => { - const container = new Container(); - container.bind(BaseService); - const ins = await container.getAsync(BaseService); - expect(ins instanceof BaseService).to.be.true; - }); - - it('should execute async init method when object created', async () => { - const container = new Container(); - container.bind(BaseServiceAsync); - const ins = await container.getAsync(BaseServiceAsync); - expect(ins.foodNumber).to.equal(20); - }); - - it('should execute generator init method when object created', async () => { - const container = new Container(); - container.bind(BaseServiceGenerator); - const ins = await container.getAsync(BaseServiceGenerator); - expect(ins.foodNumber).to.equal(20); - }); - - it('should support constructor inject', async () => { - const container = new Container(); - container.bind('engine', Turbo); - container.bind('fuel', Gas); - container.bind(Car); - - const car = await container.getAsync(Car); - car.run(); - expect(car.getFuelCapacity()).to.equal(35); - }); - - it('should support constructor inject from parent', async () => { - const container = new Container(); - container.bind('engine', Turbo); - container.bind('fuel', Gas); - container.bind(BMWX1); - - const car = await container.getAsync(BMWX1); - car.run(); - expect(car.getFuelCapacity()).to.equal(35); - expect(car.getBrand()).to.equal('bmw'); - }); - - it('should inject constructor parameter in order', async () => { - const container = new Container(); - container.bind(Tesla); - container.bind('engine', Turbo); - container.bind('fuel', Electricity); - - const car = await container.getAsync(Tesla); - car.run(); - expect(car.getFuelCapacity()).to.equal(130); - }); - - describe('inject function', () => { - - it('should get function module', () => { - const container = new Container(); - container.bind('parent', testInjectFunction); - container.bind('child', childFunction); - const result = container.get('parent'); - expect(result).to.equal(3); - }); - - it('should get async function module', async () => { - const container = new Container(); - container.bind('parentAsync', testInjectAsyncFunction); - container.bind('childAsync', childAsyncFunction); - const result = await container.get('parentAsync'); - expect(result).to.equal(7); - }); - }); - - describe('mix suit', () => { - - const container = new Container(); - - it('should use factory dynamic create object', () => { - container.bind('engineFactory', engineFactory); - container.bind(DieselCar); - container.bind(PetrolEngine); - container.bind(DieselEngine); - const result = container.get(DieselCar); - result.run(); - expect(result.dieselEngine.capacity).to.equal(15); - expect(result.backUpDieselEngine.capacity).to.equal(20); - }); - - }); - - describe('dependency tree', () => { - - it('should generate dependency dot in requestContainer', async () => { - const applicationContext = new Container(); - applicationContext.bind(UserService); - applicationContext.bind(UserController); - applicationContext.bind(DbAPI); - const newTree = await applicationContext.dumpDependency(); - expect(/userController/.test(newTree)).to.be.true; - expect(/newKey\(DbAPI\)/.test(newTree)).to.be.true; - }); - - it('should skip empty properties', async () => { - const applicationContext = new Container(); - applicationContext.bind(UserService); - applicationContext.bind(UserController); - applicationContext.bind(DbAPI); - applicationContext.bind(A); - applicationContext.bind(B); - const newTree = await applicationContext.dumpDependency(); - expect(/userController/.test(newTree)).to.be.true; - expect(/newKey\(DbAPI\)/.test(newTree)).to.be.true; - expect(/"newKey" -> "b"/.test(newTree)).to.be.true; - }); - - }); -}); diff --git a/packages/context/test/unit/factory/ApplicationContext.test.ts b/packages/context/test/unit/factory/ApplicationContext.test.ts deleted file mode 100644 index 9f4431fe2199..000000000000 --- a/packages/context/test/unit/factory/ApplicationContext.test.ts +++ /dev/null @@ -1,89 +0,0 @@ -import { ObjectDefinition } from '../../../src/base/ObjectDefinition'; -import { ObjectDefinitionRegistry, BaseApplicationContext, ContextEvent } from '../../../src/factory/applicationContext'; -import * as sinon from 'sinon'; -import { expect } from 'chai'; - -describe('/test/unit/factory/ApplicationContext', () => { - describe('ObjectDefinitionRegistry', () => { - it('should be ok', () => { - const definition = new ObjectDefinition(); - definition.id = 'hello1'; - - const registry = new ObjectDefinitionRegistry(); - registry.registerDefinition(definition.id, definition); - - const definition1 = new ObjectDefinition(); - definition1.id = 'hello1'; - definition1.path = '/test/hello1'; - registry.registerDefinition(definition1.id, definition1); - - expect(registry.hasDefinition(definition.id)).true; - expect(registry.getDefinition(definition.id)).not.null; - expect(registry.identifiers).deep.eq([definition.id]); - expect(registry.count).eq(1); - expect(registry.getDefinitionByPath(definition1.path)).not.null; - expect(registry.getDefinitionByPath('/test')).is.null; - - registry.clearAll(); - expect(registry.count).eq(0); - expect(registry.getDefinition(definition.id)).is.undefined; - - registry.registerDefinition(definition1.id, definition1); - expect(registry.hasDefinition(definition1.id)).true; - registry.removeDefinition(definition1.id); - expect(registry.hasDefinition(definition1.id)).false; - - const obj = { - aa: 1, - bb: [22, 'asdfa'] - }; - registry.registerObject('he1', obj); - expect(registry.hasObject('he1')).true; - expect(registry.getObject('he1')).deep.eq({ - aa: 1, - bb: [22, 'asdfa'] - }); - - expect(registry.identifiers).deep.eq([]); - }); - }); - describe('BaseApplicationContext', () => { - it('context event should be ok', () => { - const callback = sinon.spy(); - const app = new BaseApplicationContext(__dirname); - - const listen = { - key: 'hello world', - onStart() { - callback('onStart'); - }, - onReady() { - callback('onReady'); - }, - onRefresh() { - callback('onRefresh'); - }, - onStop() { - callback('onStop'); - } - }; - app.addLifeCycle(listen); - app.emit(ContextEvent.START); - app.emit(ContextEvent.READY); - app.emit(ContextEvent.ONREFRESH); - app.emit(ContextEvent.STOP); - - app.removeLifeCycle(listen); - app.emit(ContextEvent.START); - app.emit(ContextEvent.READY); - app.emit(ContextEvent.ONREFRESH); - app.emit(ContextEvent.STOP); - - expect(callback.callCount).eq(4); - expect(callback.withArgs('onStart').calledOnce).true; - expect(callback.withArgs('onReady').calledOnce).true; - expect(callback.withArgs('onRefresh').calledOnce).true; - expect(callback.withArgs('onStop').calledOnce).true; - }); - }); -}); diff --git a/packages/context/test/unit/factory/common/Autowire.test.ts b/packages/context/test/unit/factory/common/Autowire.test.ts deleted file mode 100644 index 62b33b8b089d..000000000000 --- a/packages/context/test/unit/factory/common/Autowire.test.ts +++ /dev/null @@ -1,32 +0,0 @@ -import { Autowire, InjectionPoint } from '../../../../src/factory/common/Autowire'; -import { expect } from 'chai'; - -describe('/test/unit/factory/common/Autowire', () => { - it('inject point should be ok', () => { - const point = InjectionPoint.create('hello', 1234); - expect(point).not.null; - expect(point).not.undefined; - - expect(point.defaultValue).eq(1234); - expect(point.id).eq('hello'); - }); - - it('patchDollar should be ok', () => { - const aa = {'$hh': null}; - const context = { - get() { - return 'ddd'; - } - }; - Autowire.patchDollar(aa, context as any); - - Autowire.patchDollar(aa, context as any); - - expect(aa.$hh).eq('ddd'); - expect((aa as any).__patched_dollar__).true; - - const bb = {'$cc': null}; - Autowire.patchDollar(bb, context as any, function (key) { return 'ccc'; }); - expect(bb.$cc).eq('ccc'); - }); -}); diff --git a/packages/context/test/unit/factory/common/ManagedResolverFactory.test.ts b/packages/context/test/unit/factory/common/ManagedResolverFactory.test.ts deleted file mode 100644 index 4b85379a10b9..000000000000 --- a/packages/context/test/unit/factory/common/ManagedResolverFactory.test.ts +++ /dev/null @@ -1,92 +0,0 @@ -import { BaseManagedResolver, ManagedResolverFactory } from '../../../../src/factory/common/ManagedResolverFactory'; -import { BaseApplicationContext } from '../../../../src/factory/applicationContext'; -import {expect} from 'chai'; -import { ManagedProperties, ManagedValue, ManagedJSON } from '../../../../src/factory/common/managed'; -import { VALUE_TYPE } from '../../../../src/factory/common/constants'; -import { ObjectConfiguration } from '../../../../src/base/Configuration'; - -describe('/test/unit/factory/common/ManagedResolverFactory', () => { - it('base resolver should be ok', async () => { - const r = new BaseManagedResolver(null); - let a = false; - try { - expect(r.type).true; - } catch (e) { - a = true; - } - expect(a).true; - - try { - r.resolve(null); - } catch (e) { - a = true; - } - expect(a).true; - - try { - await r.resolveAsync(null); - } catch (e) { - a = true; - } - expect(a).true; - }); - - it('resolver should be ok', async () => { - const context = new BaseApplicationContext(); - context.props.addProperty('hello', {a: {b: 1}}); - context.props.addProperty('hello1', 123); - - const resolver = new ManagedResolverFactory(context); - - let b = false; - resolver.beforeEachCreated((clzz, args, context) => { - b = true; - }); - const props = new ManagedProperties(); - const val = new ManagedValue('bbb', VALUE_TYPE.STRING); - props.addProperty('a', val); - const cfg: ObjectConfiguration = resolver.resolveManaged(props); - expect(cfg.get('a')).eq('bbb'); - const cfg1: ObjectConfiguration = await resolver.resolveManagedAsync(props); - expect(cfg1.get('a')).eq('bbb'); - - let a = false; - try { - resolver.resolveManaged({ - type: 'aaa' - }); - } catch(e) { - a = true; - } - expect(a).true; - a = false; - try { - await resolver.resolveManagedAsync({ - type: 'aaa' - }); - } catch(e) { - a = true; - } - expect(a).true; - - const jsn = new ManagedJSON(); - jsn.value = '{"test": 1, "test1": "{{hello.a.b}}"}'; - - const jsna = await resolver.resolveManagedAsync(jsn); - expect(jsna).deep.eq({test: 1, test1: '1'}); - - - const vmv = new ManagedValue(); - const svmv = new ManagedValue(); - vmv.value = svmv; - vmv.valueType = VALUE_TYPE.MANAGED; - svmv.value = '1234'; - svmv.valueType = VALUE_TYPE.INTEGER; - const v1 = resolver.resolveManaged(vmv); - expect(v1).eq(1234); - const v2 = await resolver.resolveManagedAsync(vmv); - expect(v2).eq(1234); - - expect(b).false; - }); -}); diff --git a/packages/context/test/unit/factory/utils/errorFactory.test.ts b/packages/context/test/unit/factory/utils/errorFactory.test.ts deleted file mode 100644 index 6bce83519674..000000000000 --- a/packages/context/test/unit/factory/utils/errorFactory.test.ts +++ /dev/null @@ -1,41 +0,0 @@ -import { NotFoundError } from '../../../../src/utils/errorFactory'; -import { expect } from 'chai'; - -describe('/test/unit/utils/errorFactory.test.ts', () => { - const creatNormalError = function(msg) { - throw new Error(msg); - }; - const creatNotFoundError = function(msg) { - throw new NotFoundError(msg); - }; - - try { - creatNormalError(''); - } catch (error) { - expect(error).to.instanceOf(Error); - expect(NotFoundError.isClosePrototypeOf(error)).to.false; - } - - try { - creatNotFoundError(''); - } catch (error) { - expect(error).to.instanceOf(Error); - expect(error).to.instanceOf(NotFoundError); - expect(NotFoundError.isClosePrototypeOf(error)).to.true; - expect(() => { - throw error; - }).to.throw(/is not valid in current context/); - } - - try { - creatNotFoundError('testKey'); - } catch (error) { - expect(error).to.instanceOf(Error); - expect(error).to.instanceOf(NotFoundError); - expect(NotFoundError.isClosePrototypeOf(error)).to.true; - error.updateErrorMsg('TestClass'); - expect(() => { - throw error; - }).to.throw('testKey in class TestClass is not valid in context'); - } -}); diff --git a/packages/context/test/unit/factory/utils/reflectTool.test.ts b/packages/context/test/unit/factory/utils/reflectTool.test.ts deleted file mode 100644 index 42734d7fae77..000000000000 --- a/packages/context/test/unit/factory/utils/reflectTool.test.ts +++ /dev/null @@ -1,17 +0,0 @@ -import { recursiveGetPrototypeOf } from '../../../../src/utils/reflectTool'; -import { expect } from 'chai'; -import { Grandson, Child, Parent } from '../../../fixtures/class_sample'; - -describe('/test/unit/utils/reflectTools.test.ts', () => { - const grandsonPrototyp = recursiveGetPrototypeOf(Grandson); - const childPrototyp = recursiveGetPrototypeOf(Child); - const parentPrototyp = recursiveGetPrototypeOf(Parent); - expect(grandsonPrototyp).deep.eq([ - Child, - Parent, - Object.getPrototypeOf(Function), - Object.prototype - ]); - expect(parentPrototyp).deep.eq([Function.prototype, Object.prototype]); - expect(grandsonPrototyp.slice(1)).deep.eq(childPrototyp); -}); diff --git a/packages/context/test/unit/factory/xml/MixinDefinitionParser.ts b/packages/context/test/unit/factory/xml/MixinDefinitionParser.ts deleted file mode 100644 index ba06bb351675..000000000000 --- a/packages/context/test/unit/factory/xml/MixinDefinitionParser.ts +++ /dev/null @@ -1,26 +0,0 @@ - -import { IObjectDefinitionParser, IParserContext } from '../../../../src/factory/xml/interface'; -import { IObjectDefinition } from '../../../../src/interfaces'; -import { XmlObjectDefinition } from '../../../../src/factory/xml/XmlObjectDefinition'; -import * as utils from '../../../../src/factory/xml/utils'; -import { XmlObjectElementParser } from '../../../../src/factory/xml/XmlObjectElementParser'; -import { KEYS } from '../../../../src/factory/common/constants'; - -export class MixinDefinitionParser implements IObjectDefinitionParser { - readonly name: string = 'mixin'; - private eleParser = new XmlObjectElementParser(); - - parse(ele: Element, context: IParserContext): IObjectDefinition { - const definition = new XmlObjectDefinition(ele); - - utils.eachSubElementSync(ele, (node: Element) => { - if (utils.nodeNameEq(node, KEYS.PROPERTY_ELEMENT)) { - const name = utils.nodeAttr(node, KEYS.NAME_ATTRIBUTE); - const managed = this.eleParser.parseElement(node, context); - definition.properties.addProperty(name, managed); - } - }); - - return definition; - } -} diff --git a/packages/context/test/unit/factory/xml/XmlApplicationContext.test.ts b/packages/context/test/unit/factory/xml/XmlApplicationContext.test.ts deleted file mode 100644 index a90800697389..000000000000 --- a/packages/context/test/unit/factory/xml/XmlApplicationContext.test.ts +++ /dev/null @@ -1,109 +0,0 @@ -import { expect } from 'chai'; -import * as path from 'path'; -import * as sinon from 'sinon'; -import { XmlApplicationContext } from '../../../../src/factory/xml/XmlApplicationContext'; - -let baseDir = path.resolve(__dirname, '../../../fixtures/app'); -let context: XmlApplicationContext; -let ctx1: XmlApplicationContext; - -describe('/test/unit/factory/xml/XmlApplicationContext', () => { - before(async () => { - context = new XmlApplicationContext(baseDir); - context.configLocations = ['resources/context.xml']; - await context.ready(); - - ctx1 = new XmlApplicationContext(baseDir); - ctx1.configLocations = ['resources/list.xml', 'resources/object.xml']; - await ctx1.ready(); - }); - it('context load dir should be ok', async () => { - const ctx2 = new XmlApplicationContext(baseDir); - ctx2.configLocations = ['resources']; - await ctx2.ready(); - expect(context.isReady).true; - expect(context.parser).not.null; - }); - it('context init should be ok', () => { - expect(context.isReady).true; - expect(context.parser).not.null; - }); - it('context get identifier should be ok', async () => { - const obj1: any = context.get('ctor:obj1'); - expect(obj1).not.null; - expect(obj1.say()).eq('say hello'); - - const casync: any = await context.getAsync('ctor:async'); - const rt = await casync.hello('mf'); // tslint:disable-line - expect(rt).eq('hello mf'); - - const hhh = context.get('ctor:hello'); - expect(hhh).not.null; - - expect(context.props.size).greaterThan(0); - expect(context.props.get('foo')).deep.eq({bar: '123'}); - - const cowboy = context.get('cowboy'); - console.log('---- cowboy', cowboy); - - const obj3: any = context.get('ctor:obj3'); - console.log('---- obj3 111', obj3, obj3.say(), obj3.cowboy); - expect(obj3).not.null; - expect(obj3.cowboy).not.null; - expect(obj3.cowboy.name).eq('Spike'); - }); - it('ctx1 should be ok', async () => { - expect(ctx1).not.null; - - const foo: any = ctx1.get('obj:foo'); - expect(foo).not.null; - expect(foo.abc).eq('bcd'); - expect(foo.num).eq(1); - expect(foo.int === 12).true; - expect(foo.date.getTime()).eq(1527069046019); - expect(foo.unknow).eq('aaa'); - expect(foo.boolean).eq(true); - }); - it('injectionpoint should be ok', () => { - const bar: any = ctx1.get('obj:bar'); - expect(bar.inject).not.null; - expect(bar.inject.cowboy).is.null; - expect(bar.inject.cowboy).not.undefined; - }); - it('context should be exception ok', async () => { - const callback = sinon.spy(); - try { - const ctx = new XmlApplicationContext(baseDir); - ctx.configLocations = 'hello'; - await ctx.ready(); - } catch(e) { - callback(e.message); - } - expect(callback.called).true; - expect(callback.withArgs('loadDefinitions fail configLocations is not array!').calledOnce).true; - }); - it('context registry getDefinitionByName should be ok', () => { - const arr = context.registry.getDefinitionByName('object'); - expect(arr).is.not.null; - expect(arr.length).greaterThan(0); - }); - it('context construct-method should be only once', () => { - const obj6 = context.get('ctor:obj6'); - - const obj62 = context.get('ctor:obj6'); - - expect(obj6).deep.eq(obj62); - - const obj63 = context.get('ctor:obj6'); - - expect(obj62).deep.eq(obj63); - expect(obj6).deep.eq(obj63); - }); - it('context constructor-arg object should be ok', () => { - const aa: any = context.get('ctor:obj7'); - expect(aa.getHello()).eq('hello'); - - const aa1: any = context.get('ctor:obj8'); - expect(aa1.getHello()).eq('hello8'); - }); -}); diff --git a/packages/context/test/unit/factory/xml/XmlObjectDefinition.test.ts b/packages/context/test/unit/factory/xml/XmlObjectDefinition.test.ts deleted file mode 100644 index 2f53f7779174..000000000000 --- a/packages/context/test/unit/factory/xml/XmlObjectDefinition.test.ts +++ /dev/null @@ -1,80 +0,0 @@ -import { XmlObjectDefinition } from '../../../../src'; -import * as utils from '../../../../src/factory/xml/utils'; -import { DOMParser } from 'xmldom'; -import { expect } from 'chai'; - -function parseStr(str: string): Element { - const doc = new DOMParser().parseFromString(str); - const ele = utils.firstSubElement(doc); - return ele; -} - -describe('/test/unit/factory/xml/XmlObjectDefinition.test.ts', () => { - it('xml object should ok', () => { - const s = ` - - - `; - - const ele = parseStr(s); - const oo = new XmlObjectDefinition(ele); - - expect(oo.id).eq('ctor:obj2'); - expect(oo.path).eq('obj2'); - expect(oo.initMethod).eq('getInstance'); - expect(oo.destroyMethod).eq('close'); - expect(oo.isDirect()).false; - expect(oo.isAsync()).false; - expect(oo.isAutowire()).true; - expect(oo.isExternal()).false; - expect(oo.isSingletonScope()).true; - - - const s1 = ` - - - `; - - const ele1 = parseStr(s1); - const oo1 = new XmlObjectDefinition(ele1); - - expect(oo1.id).eq('ctor:obj1'); - expect(oo1.path).eq('obj1'); - expect(oo1.constructMethod).eq('getInstance'); - expect(oo1.initMethod).is.null; - expect(oo1.destroyMethod).eq('close'); - expect(oo1.hasDependsOn()).false; - expect(oo1.hasConstructorArgs()).false; - expect(oo1.isDirect()).false; - expect(oo1.isAsync()).false; - expect(oo1.isAutowire()).false; - expect(oo1.isExternal()).true; - expect(oo1.isSingletonScope()).false; - expect(oo1.isRequestScope()).true; - - const s2 = ` - - - `; - - const ele2 = parseStr(s2); - const oo2 = new XmlObjectDefinition(ele2); - - expect(oo2.id).eq('ctor:obj2'); - expect(oo2.path).eq('obj1'); - expect(oo2.constructMethod).eq('getInstance'); - expect(oo2.initMethod).is.null; - expect(oo2.destroyMethod).eq('close'); - expect(oo2.hasDependsOn()).false; - expect(oo2.hasConstructorArgs()).false; - expect(oo2.export).eq('hello'); - expect(oo2.isDirect()).false; - expect(oo2.isAsync()).false; - expect(oo2.isAutowire()).true; - expect(oo2.isExternal()).false; - expect(oo2.isSingletonScope()).false; - expect(oo2.isRequestScope()).false; - oo2.setAttr('nihaoma', 'this is a test'); - expect(oo2.getAttr('nihaoma')).eq('this is a test'); - }); -}); diff --git a/packages/context/test/unit/factory/xml/XmlObjectDefinitionParser.test.ts b/packages/context/test/unit/factory/xml/XmlObjectDefinitionParser.test.ts deleted file mode 100644 index 5ecc6eacb2ea..000000000000 --- a/packages/context/test/unit/factory/xml/XmlObjectDefinitionParser.test.ts +++ /dev/null @@ -1,47 +0,0 @@ -import * as path from 'path'; -import { expect } from 'chai'; -import { XmlObjectDefinitionParser } from '../../../../src/factory/xml/XmlObjectDefinitionParser'; -import { ObjectDefinitionRegistry } from '../../../../src/factory/applicationContext'; -import { Resource } from '../../../../src/base/Resource'; -import { MixinDefinitionParser } from './MixinDefinitionParser'; - -const baseDir = path.resolve(__dirname, '../../../fixtures/app'); -let parser: XmlObjectDefinitionParser; -let registry: ObjectDefinitionRegistry; - -describe('/test/unit/factory/xml/XmlObjectDefinitionParser', () => { - before(() => { - registry = new ObjectDefinitionRegistry(); - parser = new XmlObjectDefinitionParser(baseDir, registry); - }); - - it('load fixture app should ok', async () => { - const res = new Resource(baseDir, 'resources/context.xml'); - parser.load(res); - expect(parser.registry.hasDefinition('ctor:obj1')).true; - const definition = parser.registry.getDefinition('ctor:obj1'); - expect(definition).not.null; - expect(definition.constructorArgs.length).eq(3); - expect(definition.constructorArgs[0].type).eq('json'); - expect(parser.registry.hasDefinition('list:obj1')).true; - expect(parser.registry.hasDefinition('obj:foo')).true; - }); - - it('should register mixin parser ok', async () => { - const res = new Resource(baseDir, 'resources/mixin.xml'); - const mixin = new MixinDefinitionParser(); - parser.registerParser(mixin); - parser.load(res); - - const definition = registry.getDefinition('mixin1'); - expect(definition).not.null; - expect(definition.properties.size).greaterThan(0); - expect(definition.properties.getProperty('def')).not.null; - const obj = registry.getDefinition('obj:foo2'); - expect(obj).not.null; - expect(obj.getAttr('mixin')).eq('mixin1,mixin2'); - - parser.removeParser(mixin); - expect(parser.hasParser(mixin.name)).false; - }); -}); diff --git a/packages/context/test/unit/factory/xml/XmlObjectElementParser.test.ts b/packages/context/test/unit/factory/xml/XmlObjectElementParser.test.ts deleted file mode 100644 index 24ca91775dfb..000000000000 --- a/packages/context/test/unit/factory/xml/XmlObjectElementParser.test.ts +++ /dev/null @@ -1,337 +0,0 @@ -import { KEYS, VALUE_TYPE } from '../../../../src/factory/common/constants'; -import { XmlObjectElementParser } from '../../../../src/factory/xml/XmlObjectElementParser'; -import { ParserContext, XmlObjectDefinitionParser } from '../../../../src/factory/xml/XmlObjectDefinitionParser'; -import * as utils from '../../../../src/factory/xml/utils'; -import { DOMParser } from 'xmldom'; -import { expect } from 'chai'; -import * as sinon from 'sinon'; -import { - ManagedJSON, - ManagedReference, - ManagedSet, - ManagedValue, - ManagedList, - ManagedMap, - ManagedObject, - ManagedProperty, - ManagedProperties -} from '../../../../src/factory/common/managed'; -import { IManagedInstance } from '../../../../src/interfaces'; - -let parser: XmlObjectElementParser; - -function parseStr(str: string): IManagedInstance { - const doc = new DOMParser().parseFromString(str); - const ele = utils.firstSubElement(doc); - return parser.parseElement(ele, new ParserContext(null, - new XmlObjectDefinitionParser(process.cwd(), null))); -} - -describe('/test/unit/factory/xml/XmlObjectElementParser', () => { - before(() => { - parser = new XmlObjectElementParser(); - }); - it('json parser should be ok', () => { - const json = ` - - - - `; - const managed = parseStr(json); - expect(managed.type).eq(KEYS.JSON_ELEMENT); - const mj = managed; - expect(mj.value).not.null; - expect(mj.value).eq('{"foo": "{{foo.bar}}"}'); - }); - it('ref parser should be ok', () => { - const ref = ` - - `; - const managed = parseStr(ref); - expect(managed.type).eq(KEYS.REF_ELEMENT); - const mj = managed; - expect(mj.name).not.null; - expect(mj.name).eq('ctor:obj4'); - }); - it('set parser should be ok', () => { - const set = ` - - 10 - 10i - 1523678271683 - - - - `; - const managed = parseStr(set); - expect(managed.type).eq(KEYS.SET_ELEMENT); - const ms = managed; - expect(ms.size).greaterThan(1); - const arr = Array.from(ms); - - const one = arr[0]; - expect(one.type).eq(KEYS.VALUE_ELEMENT); - expect(one.valueType).eq(VALUE_TYPE.INTEGER); - expect(one.value).eq('10'); - - const three = arr[2]; - expect(three.type).eq(KEYS.VALUE_ELEMENT); - expect(three.valueType).eq(VALUE_TYPE.DATE); - - const four = arr[3]; - expect(four.type).eq(KEYS.REF_ELEMENT); - expect(four.name).eq('obj:foo'); - }); - it('list parser should be ok', () => { - const list = ` - - 10 - 10i - 1523678271683 - - - - `; - const managed = parseStr(list); - expect(managed.type).eq(KEYS.LIST_ELEMENT); - const ms = managed; - expect(ms.length).greaterThan(1); - const arr = ms; - - const one = arr[0]; - expect(one.type).eq(KEYS.VALUE_ELEMENT); - expect(one.valueType).eq(VALUE_TYPE.INTEGER); - expect(one.value).eq('10'); - - const three = arr[2]; - expect(three.type).eq(KEYS.VALUE_ELEMENT); - expect(three.valueType).eq(VALUE_TYPE.DATE); - - const four = arr[3]; - expect(four.type).eq(KEYS.REF_ELEMENT); - expect(four.name).eq('obj:foo'); - }); - it('map parser should ok', () => { - const map = ` - - - - - - - - - - `; - const managed = parseStr(map); - expect(managed.type).eq(KEYS.MAP_ELEMENT); - const mp = managed; - expect(mp.get('foo').type).eq(KEYS.VALUE_ELEMENT); - expect(mp.get('foo2').type).eq(KEYS.OBJECT_ELEMENT); - - const mo = mp.get('foo2'); - expect(mo.name).eq(''); - expect(mo.definition.id).eq(''); - expect(mo.definition.properties.size).greaterThan(0); - expect(mo.definition.properties.getProperty('a').type).eq(KEYS.PROPERTY_ELEMENT); - const mpt = mo.definition.properties.getProperty('a'); - expect(mpt.value.type).eq(KEYS.VALUE_ELEMENT); - expect(mpt.valueType).eq(VALUE_TYPE.MANAGED); - - const mpv = mpt.value; - expect(mpv.valueType).eq(VALUE_TYPE.STRING); - }); - it('value parser should ok', () => { - const v1 = ` - 123 - `; - - const managed1 = parseStr(v1); - expect(managed1.valueType).eq(VALUE_TYPE.INTEGER); - - const v2 = ` - - - - `; - const managed2 = parseStr(v2); - expect(managed2.valueType).eq(VALUE_TYPE.MANAGED); - expect(managed2.value.type).eq(KEYS.JSON_ELEMENT); - }); - it('property parser should ok', () => { - const s1 = ` - - `; - const mp1 = parseStr(s1); - expect(mp1.value.type).eq(KEYS.VALUE_ELEMENT); - expect(mp1.value.value).eq('b'); - - const s2 = ` - - `; - const mp2 = parseStr(s2); - expect(mp2.value.type).eq(KEYS.REF_ELEMENT); - expect(mp2.value.name).eq('foo'); - - const s3 = ` - - 10 - - `; - const mp3 = parseStr(s3); - expect(mp3.value.type).eq(KEYS.VALUE_ELEMENT); - expect(mp3.value.value).eq('10'); - expect(mp3.value.valueType).eq('int'); - - const s4 = ` - - true - - `; - const mp4 = parseStr(s4); - expect(mp4.value.type).eq(KEYS.VALUE_ELEMENT); - expect(mp4.value.value).eq('true'); - expect(mp4.value.valueType).eq('boolean'); - }); - it('props parser should ok', () => { - const s = ` - - - INDIA - Pakistan - USA - USA - - - `; - - const prop = parseStr(s); - expect(prop.value.type).eq(KEYS.PROPS_ELEMENT); - - const props = prop.value; - const p1 = props.getProperty('one'); - expect(p1.value).eq('INDIA'); - - const p2 = props.getProperty('two'); - expect(p2.value).eq('Pakistan'); - - const p3 = props.getProperty('three'); - expect(p3.value).eq('USA'); - }); - it('object parser should ok', () => { - const s = ` - - - - - - - - - - - - - - - asdfa - 123 - - - - `; - - const managed = parseStr(s); - expect(managed.name).eq('ctor:obj1'); - expect(managed.definition.id).eq('ctor:obj1'); - expect(managed.definition.constructorArgs.length).eq(3); - expect(managed.definition.properties.size).eq(3); - const json = managed.definition.constructorArgs[0]; - expect(json.value).eq('{"foo": "{{foo.bar}}"}'); - - const ref = managed.definition.constructorArgs[1]; - expect(ref.name).eq('ctor:obj4'); - const p = managed.definition.properties.getProperty('k1'); - expect(p.value.type).eq(KEYS.VALUE_ELEMENT); - expect(p.value.value).eq('v1'); - - const pl = managed.definition.properties.getProperty('things'); - const plv = pl.value; - expect(plv.type).eq(KEYS.LIST_ELEMENT); - expect(plv[0].value).eq('asdfa'); - expect(plv[1].value).eq('123'); - - - const se1 = ` - - - - - - - - - - - - `; - const call1 = sinon.spy(); - try { - parseStr(se1); - } catch(e) { - call1(e.message); - } - expect(call1.calledOnce).true; - expect(call1.calledWith('ctor:obj1: direct object has no constructor-args element')).true; - - const se2 = ` - - - `; - - const call2 = sinon.spy(); - try { - parseStr(se2); - } catch(e) { - call2(e.message); - } - expect(call2.calledOnce).true; - expect(call2.calledWith('ctor:obj1: direct object has no construct-method or init-method attribute')).true; - - const se3 = ` - - - `; - - const call3 = sinon.spy(); - try { - parseStr(se3); - } catch(e) { - call3(e.message); - } - expect(call3.calledOnce).true; - expect(call3.calledWith('ctor:obj1: async object has no construct-method attribute')).true; - - const se4 = ` - - - `; - - const call4 = sinon.spy(); - try { - parseStr(se4); - } catch(e) { - call4(e.message); - } - expect(call4.calledOnce).true; - expect(call4.calledWith('ctor:obj1: object construct-method conflict with init-method attribute')).true; - }); -}); diff --git a/packages/context/test/unit/factory/xml/utils.test.ts b/packages/context/test/unit/factory/xml/utils.test.ts deleted file mode 100644 index cba44954c198..000000000000 --- a/packages/context/test/unit/factory/xml/utils.test.ts +++ /dev/null @@ -1,54 +0,0 @@ -import * as utils from '../../../../src/factory/xml/utils'; -import { KEYS } from '../../../../src/factory/common/constants'; -import { DOMParser } from 'xmldom'; -import { expect } from 'chai'; - -const dom = ` - - - - - - - - - - - -`; - -let doc = null; - -describe('/test/unit/factory/xml/utils', () => { - before(() => { - doc = new DOMParser().parseFromString(dom); - }); - it('utils test should ok', async () => { - const ele = utils.firstSubElement(doc); - expect(utils.nodeName(doc)).eq(''); - expect(ele).not.null; - - expect(utils.nodeAttr(ele, KEYS.PATH_ATTRIBUTE)).eq('obj1'); - expect(utils.nodeName(ele)).eq(KEYS.OBJECT_ELEMENT); - expect(utils.nodeNameEq(ele, KEYS.OBJECT_ELEMENT)).true; - expect(utils.nodeHasAttr(ele, KEYS.PATH_ATTRIBUTE)).true; - expect(utils.nodeHasAttr(ele, KEYS.TYPE_ATTRIBUTE)).false; - - utils.eachSubElementSync(ele, (node: Element) => { - expect(utils.nodeNameEq(node, KEYS.CONSTRUCTORARG_ELEMENT)); - }); - - const cele = utils.firstSubElement(ele); - - await utils.eachSubElement(cele, async (node: Element) => { - expect(utils.nodeText(node)).not.null; - }); - expect(utils.firstCDATAText(cele)).eq(''); - - const jsonele = utils.firstSubElement(cele); - expect(utils.nodeNameEq(jsonele, KEYS.JSON_ELEMENT)).true; - expect(utils.firstCDATAText(jsonele)).eq('{"foo": "{{foo.bar}}"}'); - }); -}); diff --git a/packages/context/test/unit/factory/xml/xmltest.ts b/packages/context/test/unit/factory/xml/xmltest.ts deleted file mode 100644 index 428bb66d3d8d..000000000000 --- a/packages/context/test/unit/factory/xml/xmltest.ts +++ /dev/null @@ -1,34 +0,0 @@ -import * as path from 'path'; -import * as fs from 'fs'; -import { DOMParser } from 'xmldom'; - -let doc = null; - -describe('xmltest', () => { - before(() => { - const buf = fs.readFileSync(path.resolve(__dirname, '../../../fixtures/resources/construction.xml')); - doc = new DOMParser().parseFromString(buf.toString()); - }); - - it('#xml test should ok', () => { - console.log(doc.localName, doc.nodeName, doc.documentElement.childNodes.item(5).nodeName, doc.documentElement.childNodes.item(5).localName, doc.documentElement.childNodes.item(5).textContent); - - - const tt = ` - - llll - - `; - - const dd = new DOMParser().parseFromString(tt); - for (let i = 0; i < dd.childNodes.length; i++) { - const ele = dd.childNodes.item(i); - if (ele.nodeType === 1) { - console.log(ele.textContent); - for (let j = 0; j < ele.childNodes.length; j++) { - console.log(ele.childNodes.item(j).nodeName, ele.childNodes.item(j).nodeType, ele.childNodes.item(j).textContent); - } - } - } - }); -}); diff --git a/packages/context/test/unit/index.test.ts b/packages/context/test/unit/index.test.ts deleted file mode 100644 index 5459f640bc7f..000000000000 --- a/packages/context/test/unit/index.test.ts +++ /dev/null @@ -1,14 +0,0 @@ -import {expect} from 'chai'; -import {UserClass} from '../fixtures/UserClass'; -const is = require('is-type-of'); - -class Textclass { - -} - -describe('/test/unit/index.test.ts', () => { - it('should test is-type-of is.class method', () => { - expect(is.class(Textclass)).to.be.true; - expect(is.class(UserClass)).to.be.true; - }); -}); diff --git a/packages/context/test/unit/requestContainer.test.ts b/packages/context/test/unit/requestContainer.test.ts deleted file mode 100644 index 6ab57c2da4a6..000000000000 --- a/packages/context/test/unit/requestContainer.test.ts +++ /dev/null @@ -1,101 +0,0 @@ -import {expect} from 'chai'; -import {Container, inject, provide, RequestContainer, scope, ScopeEnum} from '../../src'; -// const path = require('path'); - -// function sleep(t) { -// return new Promise((resolve) => { -// setTimeout(() => { -// resolve(); -// }, t); -// }); -// } - -class Tracer { - - get parentId() { - return '321'; - } - -} - -class DataCollector { - - id = Math.random(); - - getData() { - return this.id + 'hello'; - } -} - -@provide('tracer') -@scope(ScopeEnum.Request) -class ChildTracer extends Tracer { - - id = Math.random(); - - @inject('dataCollector') - collector: DataCollector; - - get parentId() { - return '123'; - } - - get traceId() { - return this.id; - } - - getData() { - return this.collector.getData(); - } - -} - -describe('/test/unit/requestContainer.test.ts', () => { - - it('should create request container more then once and get same value from parent', async () => { - const appCtx = new Container(); - appCtx.bind(Tracer); - - const reqCtx1 = new RequestContainer({}, appCtx); - const reqCtx2 = new RequestContainer({}, appCtx); - expect(reqCtx1.get(Tracer).parentId).to.equal(reqCtx2.get(Tracer).parentId); - expect((await reqCtx1.getAsync(Tracer)).parentId).to.equal((await reqCtx2.getAsync(Tracer)).parentId); - }); - - it('should get different property value in different request context', async () => { - const appCtx = new Container(); - appCtx.bind('tracer', Tracer); - - const reqCtx1 = new RequestContainer({}, appCtx); - reqCtx1.registerObject('tracer', new ChildTracer()); - const reqCtx2 = new RequestContainer({}, appCtx); - reqCtx2.registerObject('tracer', new ChildTracer()); - - const tracer1 = await reqCtx1.getAsync('tracer'); - const tracer2 = await reqCtx2.getAsync('tracer'); - - expect(tracer1.parentId).to.equal('123'); - expect(tracer2.parentId).to.equal('123'); - - expect(tracer1.traceId).to.not.equal(tracer2.traceId); - }); - - it('should get singleton object in different request scope object', async () => { - const appCtx = new Container(); - appCtx.bind(DataCollector); - appCtx.bind(ChildTracer); - - const reqCtx1 = new RequestContainer({}, appCtx); - const reqCtx2 = new RequestContainer({}, appCtx); - - const tracer1 = await reqCtx1.getAsync('tracer'); - const tracer2 = await reqCtx2.getAsync('tracer'); - - expect(tracer1.parentId).to.equal('123'); - expect(tracer2.parentId).to.equal('123'); - - expect(tracer1.traceId).to.not.equal(tracer2.traceId); - expect(tracer1.getData()).to.equal(tracer2.getData()); - }); - -}); diff --git a/packages/context/tsconfig.json b/packages/context/tsconfig.json deleted file mode 100644 index ec3748a356b0..000000000000 --- a/packages/context/tsconfig.json +++ /dev/null @@ -1,25 +0,0 @@ -{ - "compilerOptions": { - "target": "ES2017", - "module": "commonjs", - "moduleResolution": "node", - "experimentalDecorators": true, - "emitDecoratorMetadata": true, - "noImplicitThis": true, - "noUnusedLocals": true, - "stripInternal": true, - "pretty": true, - "declaration": true, - "outDir": "dist", - "lib": ["es2017", "dom"], - "sourceMap": true - }, - "exclude": [ - "dist", - "node_modules", - "test" - ], - "files": [ - "src/index" - ] -} diff --git a/packages/midway/README.md b/packages/midway/README.md index 70d0cef533ac..f7bb17d3171d 100644 --- a/packages/midway/README.md +++ b/packages/midway/README.md @@ -64,7 +64,6 @@ midway is comprised of many specialized packages. This repository contains all t | [`midway-init`](https://github.com/midwayjs/midway/tree/master/packages/midway-init) | [![npm (scoped)](https://img.shields.io/npm/v/midway-init.svg?maxAge=86400)](https://github.com/midwayjs/midway/tree/master/midway-init/CHANGELOG.md) | [![Dependency Status](https://david-dm.org/midwayjs/midway.svg?path=packages/midway-init)](https://david-dm.org/midwayjs/midway.svg?path=packages/midway-init) | [![devDependency Status](https://david-dm.org/midwayjs/midway/dev-status.svg?path=packages/midway-init)](https://david-dm.org/midwayjs/midway?path=packages/midway-init#info=devDependencies) | | [`midway-bin`](https://github.com/midwayjs/midway/tree/master/packages/midway-bin) | [![npm (scoped)](https://img.shields.io/npm/v/midway-bin.svg?maxAge=86400)](https://github.com/midwayjs/midway/tree/master/midway-bin/CHANGELOG.md) | [![Dependency Status](https://david-dm.org/midwayjs/midway.svg?path=packages/midway-bin)](https://david-dm.org/midwayjs/midway.svg?path=packages/midway-bin) | [![devDependency Status](https://david-dm.org/midwayjs/midway/dev-status.svg?path=packages/midway-bin)](https://david-dm.org/midwayjs/midway?path=packages/midway-bin#info=devDependencies) | | [`midway-schedule`](https://github.com/midwayjs/midway/tree/master/packages/midway-schedule) | [![npm (scoped)](https://img.shields.io/npm/v/midway-schedule.svg?maxAge=86400)](https://github.com/midwayjs/midway/tree/master/midway-schedule/CHANGELOG.md) | [![Dependency Status](https://david-dm.org/midwayjs/midway.svg?path=packages/midway-schedule)](https://david-dm.org/midwayjs/midway.svg?path=packages/midway-schedule) | [![devDependency Status](https://david-dm.org/midwayjs/midway/dev-status.svg?path=packages/midway-schedule)](https://david-dm.org/midwayjs/midway?path=packages/midway-schedule#info=devDependencies) | -| [`injection`](https://github.com/midwayjs/midway/tree/master/packages/context) | [![npm (scoped)](https://img.shields.io/npm/v/injection.svg?maxAge=86400)](https://github.com/midwayjs/midway/tree/master/context/CHANGELOG.md) | [![Dependency Status](https://david-dm.org/midwayjs/midway.svg?path=packages/context)](https://david-dm.org/midwayjs/midway.svg?path=packages/context) | [![devDependency Status](https://david-dm.org/midwayjs/midway/dev-status.svg?path=packages/context)](https://david-dm.org/midwayjs/midway?path=packages/context#info=devDependencies) | Globally: [![Build Status](https://img.shields.io/travis/midwayjs/midway/master.svg?style=flat)](https://travis-ci.org/midwayjs/midway) [![devDependency Status](https://david-dm.org/midwayjs/midway/dev-status.svg)](https://david-dm.org/midwayjs/midway#info=devDependencies)