Skip to content

Commit f1c0284

Browse files
committed
Added decorator for injecting custom repository
1 parent 6e448e5 commit f1c0284

File tree

2 files changed

+29
-2
lines changed

2 files changed

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

0 commit comments

Comments
 (0)