Skip to content

Commit

Permalink
inject transform & type
Browse files Browse the repository at this point in the history
  • Loading branch information
Helveg committed Dec 8, 2024
0 parents commit b17e806
Show file tree
Hide file tree
Showing 28 changed files with 7,391 additions and 0 deletions.
24 changes: 24 additions & 0 deletions .github/workflows/main.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
name: Test library
on: "push"
jobs:
ci:
runs-on: ubuntu-latest
strategy:
matrix:
node-version: [ 16.x ]
steps:
- name: Checkout
uses: actions/checkout@v2
- name: Use Node.js ${{ matrix.node-version }}
uses: actions/setup-node@v2
with:
node-version: ${{ matrix.node-version }}
cache: 'npm'
- name: Install dependencies
run: |
npm install
- name: Build lib
run: npm run build
- name: Test
run: |
npm run test
16 changes: 16 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
# dependencies
/node_modules

# IDE
/.vscode
/.idea

# misc
npm-debug.log
.DS_Store

# dist
/dist

# test
.testdbs/
8 changes: 8 additions & 0 deletions .npmignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
lib
sample
index.ts
package-lock.json
.eslintrc.js
tsconfig.json
.prettierrc
.commitlintrc.json
21 changes: 21 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2020 Edward Anthony

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
114 changes: 114 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,114 @@
<p align="center">
Amp up your NestJS and `class-transformer` stack with dependency injection!
</p>

## Installation and setup

### Install the dependency

```
npm install nestjs-inject-transformer --save
```

### Import the `InjectTransformModule`

```ts
import { InjectTransformModule } from 'nestjs-inject-transformer';

@Module({
imports: [InjectTransformModule]
})
export class ApplicationModule {}
```

## Usage

This package provides the `InjectTransform` and `InjectType` decorators
which support all options of their `class-transformer` respective counterparts `Transform` and `Type`.

### `InjectTransform`

Replace your `Transform` decorator with the dependency injection enabled `InjectTransform` decorator.

To inject a dependencies pass an array of injection tokens to the `inject` option. They will be passed
as additional arguments to your transform function, in the order they were given:

```ts
import { InjectTransform } from 'nestjs-inject-transformer';

export class MyDTO {
@InjectTransform(
(params, myService: MyService) => myService.parse(params.value),
{inject: [MyService]}
)
myAttr: number;
}
```

> [!WARN]
>
> `class-transformer` operates strictly synchronously. Promises can not be awaited!
Alternatively, you can pass an `InjectTransformer` to tidy up more extensive use cases:

```ts
import {InjectTransform, InjectTransformer} from 'nestjs-inject-transformer';
import {TransformFnParams} from "class-transformer";

export class MyTransformer implements InjectTransformer {
constructor(
private readonly dep1: Dependency1,
private readonly dep2: Dependency2,
private readonly dep3: Dependency3
) {}

transform(params: TransformFnParams): any {
return this.dep1.parse(this.dep2.format(this.dep3.trim(params.value)));
}
}

export class MyDTO {
@InjectTransform(MyTransformer)
myAttr: number;
}
```

### `InjectType`

This decorator allows you to provide a dependency injection enabled type injector. Like the
type transformer you can use the type injector's class body to scaffold your dependencies.

Its `inject` function is called with the same arguments as the `Type` function would have been.

The following example illustrates how you could return different DTO types (and thereby different
validation schemes when used in combination with `class-validator`) based on a supposed client's
configuration:

```ts
@Injectable()
class ClientDtoInjector implements TypeInjector {
constructor(
private readonly service: ClientConfigurationService
) {}

inject(type?: TypeHelpOptions) {
const client = type.object['client'] ?? 'default';
const clientConfig = this.service.getClientConfiguration(client);
const dto = clientConfig.getNestedDTO(type.newObject, type.property);
return dto
}
}

class OpenAccountDTO {
@IsString()
client: string;

@ValidateNested()
@InjectType(ClientDtoInjector)
accountInfo: AccountInfoDTO
}
```

## 📜 License

`nestjs-inject-transformer` is [MIT licensed](LICENSE).
19 changes: 19 additions & 0 deletions lib/app-state.service.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import { OnApplicationBootstrap, OnApplicationShutdown } from "@nestjs/common";

export class AppStateService
implements OnApplicationBootstrap, OnApplicationShutdown
{
private appRunning = false;

onApplicationBootstrap() {
this.appRunning = true;
}

onApplicationShutdown(signal?: string) {
this.appRunning = false;
}

get isRunning() {
return this.appRunning;
}
}
1 change: 1 addition & 0 deletions lib/decorators/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export * from "./inject-transform.decorator.js";
116 changes: 116 additions & 0 deletions lib/decorators/inject-transform.decorator.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,116 @@
import { plainToInstance, TransformFnParams } from "class-transformer";
import { Injectable, Module } from "@nestjs/common";
import { NestFactory } from "@nestjs/core";
import { InjectTransform } from "./index.js";
import { InjectTransformModule } from "../inject-transform.module.js";
import { InjectLifecycleError } from "../exceptions.js";
import { InjectTransformer } from "../interfaces/inject-transformer.interface.js";

const TEST_TOKEN = Symbol("TestToken");
const MISSING_TOKEN = Symbol("MissingToken");

@Injectable()
class TestService {
transform(a: number, b: number) {
return a * b;
}
}

@Injectable()
class TestTransformer implements InjectTransformer {
transform(params: TransformFnParams) {
return params.value * 4;
}
}

@Module({
imports: [InjectTransformModule],
providers: [
{ provide: TEST_TOKEN, useValue: 5 },
TestService,
TestTransformer,
],
})
class TestAppModule {}

class TestSubject {
@InjectTransform(
(params, tokenValue: number, service: TestService) =>
service.transform(params.value, tokenValue),
{
inject: [TEST_TOKEN, TestService],
}
)
x: number;

@InjectTransform(TestTransformer)
xx: number;

@InjectTransform(
(params, tokenValue: number, service: TestService) =>
service.transform(params.value, tokenValue),
{
inject: [TEST_TOKEN, TestService],
ignoreInjectLifecycle: true,
}
)
y: number;

@InjectTransform((params) => 0, { inject: [MISSING_TOKEN] })
z: number;
}

describe("InjectTransform", () => {
it("should inject transform functions", async () => {
const app = await NestFactory.createApplicationContext(TestAppModule);
await app.init();

// TestSubject.x injects the value 5 and a transform service that multiplies
// by that value => 3 * 5 = 15.
expect(plainToInstance(TestSubject, { x: 3 }).x).toEqual(15);

await app.close();
});

it("should inject transformers", async () => {
const app = await NestFactory.createApplicationContext(TestAppModule);
await app.init();

// TestSubject.xx injects a transformer that multiplies by 4
expect(plainToInstance(TestSubject, { xx: 3 }).xx).toEqual(12);

await app.close();
});

it("should error outside of injection lifecycle", async () => {
const app = await NestFactory.createApplicationContext(TestAppModule);
await app.init();
await app.close();

// Injecting while no app is open yet, or is closed already
// is defended from by default as it may lead to unexpected behaviour.
expect(() => plainToInstance(TestSubject, { x: 3 })).toThrow(
InjectLifecycleError
);
});

it("should optionally ignore lifecycle errors", async () => {
const app = await NestFactory.createApplicationContext(TestAppModule);
await app.init();
await app.close();

// TestSubject.y is marked with ignoreLifecycleErrors
expect(plainToInstance(TestSubject, { y: 3 }).y).toEqual(15);
});

it("should error on missing providers", async () => {
const app = await NestFactory.createApplicationContext(TestAppModule);
await app.init();

// TestSubject.z injects the missing MISSING_TOKEN provider.
expect(() => plainToInstance(TestSubject, { z: 3 }).z).toThrow(
"Nest could not find Symbol(MissingToken) element"
);
await app.close();
});
});
41 changes: 41 additions & 0 deletions lib/decorators/inject-transform.decorator.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
import { Transform } from "class-transformer";
import "reflect-metadata";
import { InjectTransformModule } from "../inject-transform.module.js";
import { InjectTransformOptions } from "../interfaces/index.js";
import { InjectTransformFn } from "../interfaces/inject-transform-fn.interface.js";
import { InjectTransformer } from "../interfaces/inject-transformer.interface.js";
import { Type } from "@nestjs/common";
import { isClass } from "../util/is-class.js";

export function InjectTransform(
transformer: InjectTransformFn,
options?: InjectTransformOptions
): PropertyDecorator;
export function InjectTransform(
transformer: Type<InjectTransformer>,
options?: Omit<InjectTransformOptions, "inject">
): PropertyDecorator;
export function InjectTransform(
transformer: InjectTransformFn | Type<InjectTransformer>,
options: InjectTransformOptions = {}
) {
return Transform((params) => {
const injector = InjectTransformModule.getInjectTransformContainer(options);
const providers = options.inject ?? [];

// Unify transformFn <-> transformer
// * If it's a transformer, inject it and bind its transform function as transformFn.
// * If it's a transformFn, use it directly.
const transformerInstance = isClass(transformer)
? injector.get(transformer)
: undefined;
const transformFn =
transformerInstance?.transform.bind(transformerInstance) ?? transformer;

// Call the transform function, injecting all the dependencies in order.
return transformFn(
params,
...providers.map((provider) => injector.get(provider))
);
}, options);
}
Loading

0 comments on commit b17e806

Please sign in to comment.