Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(di): make @tsed/di compatible with browser env #2361

Merged
merged 5 commits into from
Jul 6, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion lerna.json
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
"packages/third-parties/*",
"docs"
],
"version": "7.30.3",
"version": "7.31.0-rc.1",
"command": {
"bootstrap": {
"npmClientArgs": [
Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@tsed/root",
"version": "7.30.3",
"version": "7.31.0-rc.1",
"description": "A TypeScript Framework on top of Express",
"private": true,
"author": "Romain Lenzotti",
Expand Down
6 changes: 3 additions & 3 deletions packages/core/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@tsed/core",
"version": "7.30.3",
"version": "7.31.0-rc.1",
"description": "Core module for Ts.ED Framework",
"private": false,
"source": "./src/index.ts",
Expand Down Expand Up @@ -29,8 +29,8 @@
"tslib": "2.5.0"
},
"devDependencies": {
"@tsed/eslint": "7.30.3",
"@tsed/typescript": "7.30.3",
"@tsed/eslint": "7.31.0-rc.1",
"@tsed/typescript": "7.31.0-rc.1",
"eslint": "^8.12.0"
},
"peerDependencies": {}
Expand Down
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
}
}
};
29 changes: 16 additions & 13 deletions packages/di/package.json
Original file line number Diff line number Diff line change
@@ -1,41 +1,44 @@
{
"name": "@tsed/di",
"version": "7.30.3",
"version": "7.31.0-rc.1",
"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"
},
"devDependencies": {
"@tsed/core": "7.30.3",
"@tsed/eslint": "7.30.3",
"@tsed/core": "7.31.0-rc.1",
"@tsed/eslint": "7.31.0-rc.1",
"@tsed/logger": ">=6.2.2",
"@tsed/schema": "7.30.3",
"@tsed/typescript": "7.30.3",
"@tsed/schema": "7.31.0-rc.1",
"@tsed/typescript": "7.31.0-rc.1",
"eslint": "^8.12.0"
},
"peerDependencies": {
"@tsed/core": "^7.30.3",
"@tsed/core": "^7.31.0-rc.1",
"@tsed/logger": ">=6.2.2",
"@tsed/schema": "^7.30.3"
"@tsed/schema": "^7.31.0-rc.1"
},
"peerDependenciesMeta": {
"@tsed/core": {
Expand Down
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
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
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
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";
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
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
Loading
Loading