-
Notifications
You must be signed in to change notification settings - Fork 568
/
adapter.ts
94 lines (85 loc) 路 2.75 KB
/
adapter.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
import { DataSource, Repository } from 'typeorm';
import { CasbinRule } from './casbinRule';
import { CasbinMongoRule } from './casbinMongoRule';
import {
CasbinRuleConstructor,
GenericCasbinRule,
TypeORMAdapterConfig,
} from './interface';
import { BaseAdapter } from '@midwayjs/casbin';
/**
* TypeORMAdapter represents the TypeORM filtered adapter for policy storage.
*/
export class TypeORMAdapter extends BaseAdapter<GenericCasbinRule> {
private adapterConfig: TypeORMAdapterConfig;
private typeorm: DataSource;
constructor(dataSource: DataSource, options: TypeORMAdapterConfig) {
super();
this.typeorm = dataSource;
this.adapterConfig = options;
}
private async clearTable() {
await this.getRepository().clear();
}
/**
* Returns either a {@link CasbinRule} or a {@link CasbinMongoRule}, depending on the type. If passed a custom entity through the adapter config it will use that entity type.
* This switch is required as the normal {@link CasbinRule} does not work when using MongoDB as a backend (due to a missing ObjectID field).
* @param type
* @param adapterConfig
*/
private static getCasbinRuleType(
type: string,
adapterConfig?: TypeORMAdapterConfig
): CasbinRuleConstructor {
if (adapterConfig?.customCasbinRuleEntity) {
return adapterConfig.customCasbinRuleEntity;
}
if (type === 'mongodb') {
return CasbinMongoRule;
}
return CasbinRule;
}
private getRepository(): Repository<GenericCasbinRule> {
return this.typeorm.getRepository(this.getAdapterLine());
}
protected getAdapterLine(): new () => GenericCasbinRule {
return TypeORMAdapter.getCasbinRuleType(
this.adapterConfig.type,
this.adapterConfig
);
}
protected async loadPolicyByAdapter(): Promise<GenericCasbinRule[]> {
return this.getRepository().find();
}
protected async loadPolicyWithFilterByAdapter(
filter: any
): Promise<GenericCasbinRule[]> {
return this.getRepository().find({ where: filter });
}
protected async savePolicyByAdapter(
policies: GenericCasbinRule[]
): Promise<void> {
await this.clearTable();
const queryRunner = this.typeorm.createQueryRunner();
await queryRunner.connect();
await queryRunner.startTransaction();
try {
await queryRunner.manager.save(policies);
await queryRunner.commitTransaction();
} catch (err) {
await queryRunner.rollbackTransaction();
throw err;
} finally {
await queryRunner.release();
}
await this.getRepository().save(policies);
}
protected async removePolicyByAdapter(
removePolicy: GenericCasbinRule,
newestPolicies?: GenericCasbinRule[]
): Promise<void> {
await this.getRepository().delete({
...(removePolicy as any),
});
}
}