Skip to content

Commit

Permalink
fix(core): make model and resposiory customizable
Browse files Browse the repository at this point in the history
now user can use the default as well as their custom respository

GH-121
  • Loading branch information
yeshamavani committed Jun 13, 2024
1 parent 912105c commit 37ea818
Show file tree
Hide file tree
Showing 12 changed files with 167 additions and 106 deletions.
145 changes: 109 additions & 36 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ npm install @sourceloop/audit-log

In order to use this component into your LoopBack application, please follow below steps.

- Add audit model class as Entity.
- If you wish to modify the one provided by this extension create your own model class just the one shown below. You can use `lb4 model` command to create new model

```ts
import {Entity, model, property} from '@loopback/repository';
Expand Down Expand Up @@ -154,7 +154,8 @@ export class AuditDataSource
}
```

- Using `lb4 repository` command, create a repository file. After that, change the inject paramater as below so as to refer to correct data source name.
- If you have a custom model and you wish to use that in your repository class you can
Using `lb4 repository` command, create a repository file. After that, change the inject paramater as below so as to refer to correct data source name.
`@inject(`datasources.\${AuditDbSourceName}`) dataSource: AuditDataSource,`

One example below.
Expand Down Expand Up @@ -187,8 +188,7 @@ import {Group, GroupRelations} from '../models';
import {PgdbDataSource} from '../datasources';
import {inject, Getter, Constructor} from '@loopback/core';
import {AuthenticationBindings, IAuthUser} from 'loopback4-authentication';
import {AuditRepositoryMixin} from '@sourceloop/audit-log';
import {AuditLogRepository} from './audit-log.repository';
import {AuditRepositoryMixin, AuditLogRepository} from '@sourceloop/audit-log';

const groupAuditOpts: IAuditMixinOptions = {
actionKey: 'Group_Logs',
Expand All @@ -207,14 +207,64 @@ export class GroupRepository extends AuditRepositoryMixin<
@inject('datasources.pgdb') dataSource: PgdbDataSource,
@inject.getter(AuthenticationBindings.CURRENT_USER)
public getCurrentUser: Getter<IAuthUser>,
@repository.getter('AuditLogRepository')
@repository.getter(AuditLogRepository)
public getAuditLogRepository: Getter<AuditLogRepository>,
) {
super(Group, dataSource, getCurrentUser);
}
}
```

and also bind the component of this extension in your application.ts

```ts
import {AuditLogComponent} from '@sourceloop/audit-log';

this.component(AuditLogComponent);
```

- The above code uses the default repository provided by this extension
- If you wish to use your custom repository and model class do the following

```ts
import {repository} from '@loopback/repository';
import {Group, GroupRelations} from '../models';
import {PgdbDataSource} from '../datasources';
import {inject, Getter, Constructor} from '@loopback/core';
import {AuthenticationBindings, IAuthUser} from 'loopback4-authentication';
import {AuditRepositoryMixin} from '@sourceloop/audit-log';
import {CustomAuditLogRepository} from './audit-log.repository';
import {CustomAuditLogModel} from '../models';

const groupAuditOpts: IAuditMixinOptions = {
actionKey: 'Group_Logs',
};

export class GroupRepository extends AuditRepositoryMixin<
Group,
typeof Group.prototype.id,
GroupRelations,
string,
Constructor<
DefaultCrudRepository<Group, typeof Group.prototype.id, GroupRelations>
>,
// pass the below two parameters when you want your custom model to be used
// otheriwise the default model and repository will be used
CustomAuditLogModel,
CustomAuditLogRepository
>(DefaultCrudRepository, groupAuditOpts) {
constructor(
@inject('datasources.pgdb') dataSource: PgdbDataSource,
@inject.getter(AuthenticationBindings.CURRENT_USER)
public getCurrentUser: Getter<IAuthUser>,
@repository.getter(CustomAuditLogRepository)
public getAuditLogRepository: Getter<CustomAuditLogRepository>,
) {
super(Group, dataSource, getCurrentUser);
}
}
```

You can pass any extra attributes to save into audit table using the `IAuditMixinOptions` parameter of mixin function.

Make sure you provide `getCurrentUser` and `getAuditLogRepository` Getter functions in constructor.
Expand All @@ -227,7 +277,7 @@ This will create all insert, update, delete audits for this model.
create(data, {noAudit: true});
```

- The Actor field is now configurable and can save any string type value in the field.
- The Actor field is configurable and can save any string type value in the field.
Though the default value will be userId a developer can save any string field from the current User that is being passed.

```ts
Expand Down Expand Up @@ -265,6 +315,15 @@ this.bind(AuthServiceBindings.ActorIdKey).to('username');
public actorIdKey?: ActorId,
```

#### Making current user not mandatory

Incase you dont have current user binded in your application context and wish to log the activities within your application then in that case you can pass the actor id along with the
options just like

```ts
await productRepo.create(product, {noAudit: false, actorId: 'userId'});
```

- The package exposes a conditional mixin for your repository classes. Just extend your repository class with `ConditionalAuditRepositoryMixin`, for all those repositories where you need audit data based on condition whether `ADD_AUDIT_LOG_MIXIN` is set true. See an example below. For a model `Group`, here we are extending the `GroupRepository` with `AuditRepositoryMixin`.

```ts
Expand All @@ -273,8 +332,10 @@ import {Group, GroupRelations} from '../models';
import {PgdbDataSource} from '../datasources';
import {inject, Getter, Constructor} from '@loopback/core';
import {AuthenticationBindings, IAuthUser} from 'loopback4-authentication';
import {ConditionalAuditRepositoryMixin} from '@sourceloop/audit-log';
import {AuditLogRepository} from './audit-log.repository';
import {
ConditionalAuditRepositoryMixin,
AuditLogRepository,
} from '@sourceloop/audit-log';

const groupAuditOpts: IAuditMixinOptions = {
actionKey: 'Group_Logs',
Expand All @@ -300,15 +361,6 @@ export class GroupRepository extends ConditionalAuditRepositoryMixin(
}
```

### Making current user not mandatory

Incase you dont have current user binded in your application context and wish to log the activities within your application then in that case you can pass the actor id along with the
options just like

```ts
await productRepo.create(product, {noAudit: false, actorId: 'userId'});
```

## Using with Sequelize ORM

This extension provides support to both juggler (the default loopback ORM) and sequelize.
Expand All @@ -318,33 +370,50 @@ If your loopback project is already using `SequelizeCrudRepository` from [@loopb
1. The import statements should have the suffix `/sequelize`, like below:

```ts
import {
AuditRepositoryMixin,
AuditLogRepository,
} from '@sourceloop/audit-log/sequelize';
```

2. The Audit datasource's parent class should be `SequelizeDataSource`.

```ts
import {SequelizeDataSource} from '@loopback/sequelize';
import {repository} from '@loopback/repository';
import {Group, GroupRelations} from '../models';
import {PgdbDataSource} from '../datasources';
import {inject, Getter, Constructor} from '@loopback/core';
import {AuthenticationBindings, IAuthUser} from 'loopback4-authentication';
import {AuditRepositoryMixin} from '@sourceloop/audit-log';
import {AuditLogRepository as SequelizeAuditLogRepository} from '@sourceloop/auidt-log/sequelize';

export class AuditDataSource
extends SequelizeDataSource
implements LifeCycleObserver
{
static dataSourceName = AuditDbSourceName;
static readonly defaultConfig = config;
const groupAuditOpts: IAuditMixinOptions = {
actionKey: 'Group_Logs',
};

export class GroupRepository extends AuditRepositoryMixin<
Group,
typeof Group.prototype.id,
GroupRelations,
string,
Constructor<
DefaultCrudRepository<Group, typeof Group.prototype.id, GroupRelations>
>,
AuditLog,
SequelizeAuditLogRepository
>(DefaultCrudRepository, groupAuditOpts) {
constructor(
@inject('datasources.config.audit', {optional: true})
dsConfig: object = config,
@inject('datasources.pgdb') dataSource: PgdbDataSource,
@inject.getter(AuthenticationBindings.CURRENT_USER)
public getCurrentUser: Getter<IAuthUser>,
@repository.getter(AuditLogRepository)
public getAuditLogRepository: Getter<SequelizeAuditLogRepository>,
) {
super(dsConfig);
super(Group, dataSource, getCurrentUser);
}
}
```

Also add the following to your application.ts file to bind the Sequelize repository

```ts
import {AuditLog} from '@sourceloop/auidt-log/';
import {AuditLogRepository} from '@sourceloop/auidt-log/sequelize';

this.repositories = [AuditLogRepository<AuditLog>];
```

## Feedback

If you've noticed a bug or have a question or have a feature request, [search the issue tracker](https://github.com/sourcefuse/loopback4-audit-log/issues) to see if someone else in the community has already created a ticket.
Expand All @@ -363,3 +432,7 @@ Code of conduct guidelines [here](https://github.com/sourcefuse/loopback4-audit-
## License

[MIT](https://github.com/sourcefuse/loopback4-audit-log/blob/master/LICENSE)

```
```
4 changes: 2 additions & 2 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 2 additions & 2 deletions src/__tests__/acceptance/fixtures/dummy-application.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,10 +9,10 @@ import {RestApplication} from '@loopback/rest';
import {TenantUtilitiesBindings} from '@sourceloop/core';
import * as path from 'path';
import {TestRepository} from './repositories/test.repository';
import {AuditLogRepository} from '../../../repositories';
import {TestAuditLogErrorRepository} from './repositories/audit-error.repository';
import {TestErrorRepository} from './repositories/test-error.repository';
import {AuditLogComponent} from '../../../component';
import {TestAuditLogRepository} from './repositories/audit.repository';

export {ApplicationConfig};

Expand All @@ -29,7 +29,7 @@ export class DummyAuditServiceApplication extends BootMixin(

this.component(AuditLogComponent);

this.repository(AuditLogRepository);
this.repository(TestAuditLogRepository);
this.repository(TestRepository);
this.repository(TestAuditLogErrorRepository);
this.repository(TestErrorRepository);
Expand Down
7 changes: 0 additions & 7 deletions src/__tests__/acceptance/fixtures/models/audit.model.ts
Original file line number Diff line number Diff line change
Expand Up @@ -54,13 +54,6 @@ export class TestAuditLog extends Entity {
})
actor: string;

@property({
name: 'tenant_id',
type: 'string',
required: true,
})
tenantId: string;

@property({
type: 'object',
})
Expand Down
15 changes: 5 additions & 10 deletions src/__tests__/acceptance/fixtures/repositories/audit.repository.ts
Original file line number Diff line number Diff line change
@@ -1,18 +1,13 @@
import {DefaultCrudRepository, Entity, juggler} from '@loopback/repository';
import {DefaultCrudRepository, juggler} from '@loopback/repository';
import {TestAuditLog} from '../models/audit.model';
import {tenantGuard} from '@sourceloop/core';
import {inject} from '@loopback/core';

@tenantGuard()
export class TestAuditLogRepository extends DefaultCrudRepository<
TestAuditLog,
typeof TestAuditLog.prototype.id
typeof TestAuditLog.prototype.id,
{}
> {
constructor(
@inject('datasources.AuditDB') dataSource: juggler.DataSource,
@inject('models.AuditLog')
private readonly auditLog: typeof Entity & {prototype: TestAuditLog},
) {
super(auditLog, dataSource);
constructor(@inject('datasources.AuditDB') dataSource: juggler.DataSource) {
super(TestAuditLog, dataSource);
}
}
Original file line number Diff line number Diff line change
@@ -1,21 +1,17 @@
import {Constructor, Getter, inject} from '@loopback/core';
import {DefaultCrudRepository, repository} from '@loopback/repository';

import {
AuditLogRepository,
AuditRepositoryMixin,
IAuditMixinOptions,
} from '../../../..';
import {TestDataSource} from '../datasources/test.datasource';
import {TestModel, TestModelRelations} from '../models/test.model';

import {AuditLogRepository as SequelizeAuditLogRepository} from '../../../../repositories/sequelize';
import {IAuthUserWithPermissions} from '@sourceloop/core';

export const testAuditOpts: IAuditMixinOptions = {
actionKey: 'Item_Logs',
};

export class TestErrorRepository extends AuditRepositoryMixin<
TestModel,
typeof TestModel.prototype.id,
Expand All @@ -34,9 +30,7 @@ export class TestErrorRepository extends AuditRepositoryMixin<
@inject.getter('sf.userAuthentication.currentUser')
public getCurrentUser: Getter<IAuthUserWithPermissions>,
@repository.getter('TestAuditLogErrorRepository')
public getAuditLogRepository: Getter<
AuditLogRepository | SequelizeAuditLogRepository
>,
public getAuditLogRepository: Getter<AuditLogRepository>,
) {
super(TestModel, dataSource);
}
Expand Down
21 changes: 9 additions & 12 deletions src/__tests__/acceptance/fixtures/repositories/test.repository.ts
Original file line number Diff line number Diff line change
@@ -1,16 +1,13 @@
import {Constructor, Getter, inject} from '@loopback/core';
import {DefaultCrudRepository, repository} from '@loopback/repository';

import {
AuditLogRepository,
AuditRepositoryMixin,
IAuditMixinOptions,
} from '../../../..';
import {TestDataSource} from '../datasources/test.datasource';
import {TestModel, TestModelRelations} from '../models/test.model';

import {AuditLogRepository as SequelizeAuditLogRepository} from '../../../../repositories/sequelize';
import {IAuthUserWithPermissions} from '@sourceloop/core';
import {AuditRepositoryMixin} from '../../../../mixins';
import {IAuditMixinOptions} from '../../../../types';
import {AuditLogRepository} from '../../../../repositories';
import {TestAuditLog} from '../models/audit.model';
import {TestAuditLogRepository} from './audit.repository';

export const testAuditOpts: IAuditMixinOptions = {
actionKey: 'Item_Logs',
Expand All @@ -27,16 +24,16 @@ export class TestRepository extends AuditRepositoryMixin<
typeof TestModel.prototype.id,
TestModelRelations
>
>
>,
TestAuditLog,
TestAuditLogRepository
>(DefaultCrudRepository, testAuditOpts) {
constructor(
@inject('datasources.test') dataSource: TestDataSource,
@inject.getter('sf.userAuthentication.currentUser')
public getCurrentUser: Getter<IAuthUserWithPermissions>,
@repository.getter('TestAuditLogRepository')
public getAuditLogRepository: Getter<
AuditLogRepository | SequelizeAuditLogRepository
>,
public getAuditLogRepository: Getter<AuditLogRepository>,
) {
super(TestModel, dataSource);
}
Expand Down
Loading

0 comments on commit 37ea818

Please sign in to comment.