Skip to content

Commit a307392

Browse files
author
Umed Khudoiberdiev
authored
Merge pull request #4 from 19majkel94/custom-repository-decorator
[WIP] Added decorator for injecting custom repository
2 parents 6e448e5 + 0539445 commit a307392

File tree

3 files changed

+31
-2
lines changed

3 files changed

+31
-2
lines changed

package.json

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
{
22
"name": "typeorm-typedi-extensions",
3-
"version": "0.0.8",
3+
"version": "0.0.9",
44
"description": "Dependancy injection and service container integration with TypeORM using typedi library.",
55
"license": "MIT",
66
"readmeFilename": "README.md",
@@ -42,7 +42,7 @@
4242
"@types/node": "^7.0.4"
4343
},
4444
"peerDependencies": {
45-
"typeorm": "^0.0.8",
45+
"typeorm": "^0.0.9",
4646
"typedi": "^0.4.2"
4747
}
4848
}

src/decorators/OrmCustomRepository.ts

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
import { ConnectionManager } from "typeorm";
2+
import { Container } from "typedi";
3+
4+
/**
5+
* Allows to inject a custom Repository using typedi's Container.
6+
* Use it to get the repository class decorated with @EntityRepository decorator.
7+
*/
8+
export function OrmCustomRepository(cls: Function, connectionName: string = "default"): Function {
9+
return function(target: Object|Function, propertyName: string, index?: number) {
10+
11+
const getValue = () => {
12+
const connectionManager = Container.get(ConnectionManager);
13+
if (!connectionManager.has(connectionName))
14+
throw new Error(`Cannot get connection "${connectionName}" from the connection manager. ` +
15+
`Make sure you have created such connection. Also make sure you have called useContainer(Container) ` +
16+
`in your application before you established a connection and importing any entity.`);
17+
18+
const connection = connectionManager.get(connectionName);
19+
return connection.getCustomRepository(cls as any);
20+
};
21+
22+
if (index !== undefined) {
23+
Container.registerParamHandler({ type: target as Function, index: index, getValue: getValue });
24+
} else {
25+
Container.registerPropertyHandler({ target: target as Function /* todo: looks like typedi wrong type here */, key: propertyName, getValue: getValue });
26+
}
27+
};
28+
}

src/decorators/OrmRepository.ts

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ import {Container} from "typedi";
33

44
/**
55
* Allows to inject a Repository using typedi's Container.
6+
* If you want to inject custom Repository class decorated with @EntityRepository decorator, use OrmCustomRepository instead.
67
*/
78
export function OrmRepository(cls: Function, connectionName: string = "default"): Function {
89
return function(target: Object|Function, propertyName: string, index?: number) {

0 commit comments

Comments
 (0)