Skip to content

Commit

Permalink
feat(di): make @tsed/di compatible with browser env
Browse files Browse the repository at this point in the history
  • Loading branch information
Romakita committed Jul 6, 2023
1 parent e115ec1 commit 4605b5a
Show file tree
Hide file tree
Showing 195 changed files with 347 additions and 257 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ export class Server {
@Inject()
app: PlatformApplication;

$beforeRoutesInits() {
$beforeRoutesInit() {
this.app.use(GlobalAcceptMimeMiddleware);
}

Expand Down
4 changes: 1 addition & 3 deletions lerna.json
Original file line number Diff line number Diff line change
Expand Up @@ -14,9 +14,7 @@
"version": "7.30.3",
"command": {
"bootstrap": {
"npmClientArgs": [
"--no-package-lock"
]
"npmClientArgs": ["--no-package-lock"]
}
}
}
2 changes: 1 addition & 1 deletion packages/core/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -34,4 +34,4 @@
"eslint": "^8.12.0"
},
"peerDependencies": {}
}
}
2 changes: 2 additions & 0 deletions packages/core/src/utils/proxyDelegation.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import {uniq} from "./uniq";

/**
* @ignore
*/
Expand All @@ -15,6 +16,7 @@ export type ProxyDelegationSetter<T = any> = (target: T, property: PropertyKey,
* @ignore
*/
export type ProxyDelegationOwnKeys<T = any> = (target: T) => (string | symbol)[];

/**
* @ignore
*/
Expand Down
5 changes: 5 additions & 0 deletions packages/di/.barrelsby.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
{
"directory": ["./src/common", "./src/node"],
"exclude": ["__mock__", "__mocks__", ".spec.ts"],
"delete": true
}
8 changes: 4 additions & 4 deletions packages/di/jest.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,10 @@ module.exports = {
...require("@tsed/jest-config"),
coverageThreshold: {
global: {
statements: 98.62,
branches: 96.51,
lines: 98.62,
functions: 98.72
statements: 98.81,
branches: 96.71,
lines: 98.81,
functions: 98.32
}
}
};
17 changes: 10 additions & 7 deletions packages/di/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,22 +4,25 @@
"description": "DI module for Ts.ED Framework",
"private": false,
"source": "./src/index.ts",
"main": "./lib/cjs/index.js",
"module": "./lib/esm/index.js",
"main": "lib/cjs/index.js",
"module": "lib/esm/index.js",
"typings": "./lib/types/index.d.ts",
"browser": "./lib/browser/di.umd.min.js",
"exports": {
"types": "./lib/types/index.d.ts",
"browser": "./lib/browser/di.umd.min.js",
"import": "./lib/esm/index.js",
"require": "./lib/cjs/index.js",
"default": "./lib/esm/index.js"
},
"scripts": {
"build": "yarn barrels && yarn build:ts",
"barrels": "yarn barrelsby --delete -d ./src -e \"\\.spec\\.ts\" -e \"__mock__\"",
"build": "yarn barrels && yarn build:ts && yarn run build:browser",
"build:browser": "webpack",
"barrels": "yarn barrelsby --config .barrelsby.json",
"test": "cross-env NODE_ENV=test yarn jest --max-workers=2 && jest-coverage-thresholds-bumper",
"build:ts": "tsc --build tsconfig.json && tsc --build tsconfig.esm.json",
"lint": "eslint '**/*.{ts,js}'",
"lint:fix": "eslint '**/*.{ts,js}' --fix"
"lint": "node_modules/.bin/eslint '**/*.{ts,js}'",
"lint:fix": "node_modules/.bin/eslint '**/*.{ts,js}' --fix"
},
"dependencies": {
"tslib": "2.5.0"
Expand Down Expand Up @@ -48,4 +51,4 @@
"optional": false
}
}
}
}
File renamed without changes.
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import {DecoratorParameters, decoratorTypeOf, DecoratorTypes, StoreSet} from "@tsed/core";
import {Inject} from "../decorators/inject";
import {Inject} from "./inject";
import {DIConfiguration} from "../services/DIConfiguration";

/**
Expand Down
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ import {DI_PARAM_OPTIONS, INJECTABLE_PROP} from "../constants/constants";
import {InvalidPropertyTokenError} from "../errors/InvalidPropertyTokenError";
import type {InjectablePropertyOptions} from "../interfaces/InjectableProperties";
import {TokenProvider} from "../interfaces/TokenProvider";
import {getContext} from "../utils/asyncHookContext";

export function injectProperty(target: any, propertyKey: string, options: Partial<InjectablePropertyOptions>) {
Store.from(target).merge(INJECTABLE_PROP, {
Expand Down Expand Up @@ -104,27 +103,3 @@ export function Inject(token?: TokenProvider | (() => TokenProvider), onGet = (b
}
};
}

/**
* Inject a context like PlatformContext or any BaseContext.
*
* ```typescript
* @Injectable()
* export class MyService {
* @InjectContext()
* ctx?: Context;
* }
* ```
*
* @returns {Function}
* @decorator
*/
export function InjectContext(): PropertyDecorator {
return (target: any, propertyKey: string): any | void => {
injectProperty(target, propertyKey, {
resolver() {
return () => getContext();
}
});
};
}
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import {Injectable} from "../decorators/injectable";
import {Injectable} from "./injectable";
import {GlobalProviders} from "../registries/GlobalProviders";
import * as ProviderRegistry from "../registries/ProviderRegistry";

Expand Down
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import {descriptorOf} from "@tsed/core";
import {DITest} from "../../node/index";
import {ProviderScope} from "../domain/ProviderScope";
import {DITest} from "../services/DITest";
import {Inject} from "./inject";
import {Injectable} from "./injectable";
import {Opts} from "./opts";
Expand Down
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
54 changes: 54 additions & 0 deletions packages/di/src/common/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
/**
* @file Automatically generated by barrelsby.
*/

export * from "./constants/constants";
export * from "./decorators/configuration";
export * from "./decorators/constant";
export * from "./decorators/controller";
export * from "./decorators/inject";
export * from "./decorators/injectable";
export * from "./decorators/intercept";
export * from "./decorators/interceptor";
export * from "./decorators/lazyInject";
export * from "./decorators/module";
export * from "./decorators/opts";
export * from "./decorators/overrideProvider";
export * from "./decorators/scope";
export * from "./decorators/service";
export * from "./decorators/useOpts";
export * from "./decorators/value";
export * from "./domain/Container";
export * from "./domain/ControllerProvider";
export * from "./domain/InjectablePropertyType";
export * from "./domain/LocalsContainer";
export * from "./domain/Provider";
export * from "./domain/ProviderScope";
export * from "./domain/ProviderType";
export * from "./errors/InjectionError";
export * from "./errors/InvalidPropertyTokenError";
export * from "./errors/UndefinedTokenError";
export * from "./interfaces/DIConfigurationOptions";
export * from "./interfaces/DILogger";
export * from "./interfaces/DILoggerOptions";
export * from "./interfaces/DIResolver";
export * from "./interfaces/InjectableProperties";
export * from "./interfaces/InterceptorContext";
export * from "./interfaces/InterceptorMethods";
export * from "./interfaces/InvokeOptions";
export * from "./interfaces/OnDestroy";
export * from "./interfaces/OnInit";
export * from "./interfaces/ProviderOpts";
export * from "./interfaces/RegistrySettings";
export * from "./interfaces/ResolvedInvokeOptions";
export * from "./interfaces/TokenProvider";
export * from "./interfaces/TokenRoute";
export * from "./registries/GlobalProviders";
export * from "./registries/ProviderRegistry";
export * from "./services/DIConfiguration";
export * from "./services/DILogger";
export * from "./services/InjectorService";
export * from "./utils/colors";
export * from "./utils/createContainer";
export * from "./utils/getConfiguration";
export * from "./utils/resolveControllers";
File renamed without changes.
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import {DITest} from "../../node/index";
import {Inject} from "../decorators/inject";
import {Injectable} from "../decorators/injectable";
import {Module} from "../decorators/module";
import {DITest} from "../services/DITest";

@Injectable()
class MyService {
Expand Down
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
Original file line number Diff line number Diff line change
Expand Up @@ -108,13 +108,6 @@ export class GlobalProviderRegistry extends Map<TokenProvider, Provider> {

createRegisterFn(type: string) {
return (provider: any | ProviderOpts, instance?: any): void => {
// istanbul ignore next
if (!provider.provide) {
provider = {
provide: provider
};
}

provider = Object.assign({instance}, provider, {type});
this.merge(provider.provide, provider);
};
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -79,35 +79,11 @@ describe("DIConfiguration", () => {
});
});

describe("proxy", () => {
it("should set and get data", () => {
describe("rootDir()", () => {
it("should replace rootDir", () => {
const configuration = new DIConfiguration();

configuration.set("test", "test");
expect(configuration.get("test")).toEqual("test");
expect("test" in configuration).toEqual(true);
expect(configuration.get("test")).toEqual("test");
});

it("ownKeys", () => {
const configuration = new DIConfiguration();
configuration.set("test", "test");
expect(Reflect.ownKeys(configuration)).toEqual(["default", "map", "scopes", "resolvers", "imports", "routes", "logger", "test"]);
});

it("defineProperty", () => {
const configuration = new (class extends DIConfiguration {})();

expect(Reflect.defineProperty(configuration, "test", {})).toEqual(true);
expect(Reflect.deleteProperty(configuration, "test")).toEqual(false);
});

describe("resolve()", () => {
it("should replace rootDir", () => {
const configuration = new DIConfiguration();
configuration.set("rootDir", "/root");
expect(configuration.resolve("${rootDir}")).toEqual("/root");
});
configuration.set("rootDir", "/root");
expect(configuration.resolve("${rootDir}")).toEqual("/root");
});
});
});
Original file line number Diff line number Diff line change
@@ -1,9 +1,8 @@
import {classOf, Env, getValue, proxyDelegation, setValue} from "@tsed/core";
import {Env, getValue, proxyDelegation, setValue} from "@tsed/core";
import type {ProviderScope} from "../domain/ProviderScope";
import type {DILoggerOptions} from "../interfaces/DILoggerOptions";
import type {DIResolver} from "../interfaces/DIResolver";
import {TokenProviderOpts} from "../interfaces/TokenProvider";
import type {TokenProvider} from "../interfaces/TokenProvider";
import type {TokenProvider, TokenProviderOpts} from "../interfaces/TokenProvider";
import type {TokenRoute} from "../interfaces/TokenRoute";

export class DIConfiguration {
Expand Down Expand Up @@ -120,7 +119,7 @@ export class DIConfiguration {
*/
set(propertyKey: string | Partial<TsED.Configuration>, value?: any): this {
if (typeof propertyKey === "string") {
if (propertyKey in this) {
if (Reflect.has(this, propertyKey)) {
// @ts-ignore
this[propertyKey] = value;
} else {
Expand Down Expand Up @@ -151,6 +150,15 @@ export class DIConfiguration {
return this.getRaw(propertyKey, defaultValue);
}

/**
*
* @param value
* @returns {any}
*/
resolve(value: any) {
return value.replace("${rootDir}", this.rootDir);
}

protected getRaw(propertyKey: string, defaultValue?: any): any {
const value = getValue(this.map, propertyKey);

Expand All @@ -160,13 +168,4 @@ export class DIConfiguration {

return getValue(this.default, propertyKey, defaultValue);
}

/**
*
* @param value
* @returns {any}
*/
resolve(value: any) {
return value.replace("${rootDir}", this.rootDir);
}
}
22 changes: 22 additions & 0 deletions packages/di/src/common/services/DILogger.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import {Container, Inject, Injectable, InjectorService, LOGGER} from "../../common/index";

describe("DILogger", () => {
it("should inject logger in another service", async () => {
@Injectable()
class MyService {
@Inject(LOGGER)
logger: LOGGER;
}

const injector = new InjectorService();
injector.logger = console;

const container = new Container();
container.add(MyService);

await injector.load(container);
const logger = injector.get(MyService).logger;

expect(logger).toEqual(injector.logger);
});
});
Original file line number Diff line number Diff line change
@@ -1,9 +1,12 @@
import {Logger} from "@tsed/logger";
import {DILogger} from "../interfaces/DILogger";
import {registerProvider} from "../registries/ProviderRegistry";
import {InjectorService} from "./InjectorService";

export const LOGGER = Symbol.for("LOGGER");
export type LOGGER = DILogger;

registerProvider({
provide: Logger,
provide: LOGGER,
deps: [InjectorService],
useFactory(injector: InjectorService) {
return injector.logger;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import {ProviderScope} from "../domain/ProviderScope";
import {ProviderType} from "../domain/ProviderType";
import {GlobalProviders} from "../registries/GlobalProviders";
import {registerProvider} from "../registries/ProviderRegistry";
import {InjectorService} from "../services/InjectorService";
import {InjectorService} from "./InjectorService";

class Test {
@Inject()
Expand Down
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
Loading

0 comments on commit 4605b5a

Please sign in to comment.