Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

chore: improve readme #167

Merged
merged 7 commits into from
Jun 17, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
772 changes: 662 additions & 110 deletions packages/nestjs-cache/README.md

Large diffs are not rendered by default.

1 change: 1 addition & 0 deletions packages/nestjs-cache/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
"@concepta/ts-common": "^4.0.0-alpha.46",
"@concepta/ts-core": "^4.0.0-alpha.46",
"@concepta/typeorm-common": "^4.0.0-alpha.46",
"@nestjs/core": "^9.0.0",
"@nestjs/common": "^9.0.0",
"@nestjs/config": "^2.2.0",
"@nestjs/swagger": "^6.0.0",
Expand Down
9 changes: 8 additions & 1 deletion packages/nestjs-cache/src/__fixtures__/app.module.fixture.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
import { Module } from '@nestjs/common';
import { TypeOrmExtModule } from '@concepta/nestjs-typeorm-ext';
import { CrudModule } from '@concepta/nestjs-crud';

import { APP_FILTER } from '@nestjs/core';
import { CacheModule } from '../cache.module';
import { UserEntityFixture } from './entities/user-entity.fixture';
import { UserCacheEntityFixture } from './entities/user-cache-entity.fixture';
import { ExceptionsFilter } from '@concepta/nestjs-exception';

@Module({
imports: [
Expand All @@ -28,5 +29,11 @@ import { UserCacheEntityFixture } from './entities/user-cache-entity.fixture';
}),
CrudModule.forRoot({}),
],
providers: [
{
provide: APP_FILTER,
useClass: ExceptionsFilter,
},
],
})
export class AppModuleFixture {}
Original file line number Diff line number Diff line change
Expand Up @@ -151,7 +151,13 @@ describe('CacheAssignmentController (e2e)', () => {
await supertest(app.getHttpServer())
.post('/cache/user')
.send(payload)
.expect(500);
.then((res) => {
// check error message
expect(res.body.message).toBe(
'userCache already exists with the given key, type, and assignee ID.',
);
expect(res.status).toBe(400);
});
});

it('DELETE /cache/user/:id', async () => {
Expand Down
42 changes: 32 additions & 10 deletions packages/nestjs-cache/src/controllers/cache-crud.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,8 @@ import { CacheEntityNotFoundException } from '../exceptions/cache-entity-not-fou
import { CacheSettingsInterface } from '../interfaces/cache-settings.interface';
import { CacheCrudService } from '../services/cache-crud.service';
import getExpirationDate from '../utils/get-expiration-date.util';

import { CacheService } from '../services/cache.service';
import { CacheEntityAlreadyExistsException } from '../exceptions/cache-entity-already-exists.exception';
/**
* Cache assignment controller.
*/
Expand Down Expand Up @@ -76,6 +77,7 @@ export class CacheCrudController
private settings: CacheSettingsInterface,
@Inject(CACHE_MODULE_CRUD_SERVICES_TOKEN)
private allCrudServices: Record<string, CacheCrudService>,
private cacheService: CacheService,
) {}

/**
Expand Down Expand Up @@ -126,6 +128,17 @@ export class CacheCrudController
cacheCreateDto.expiresIn ?? this.settings.expiresIn,
);

const existingCache = await this.cacheService.get(
assignment,
cacheCreateDto,
);

if (existingCache) {
throw new CacheEntityAlreadyExistsException(
this.getEntityKey(assignment),
);
}

// call crud service to create
return this.getCrudService(assignment).createOne(crudRequest, {
...cacheCreateDto,
Expand Down Expand Up @@ -180,18 +193,27 @@ export class CacheCrudController
* @param assignment The cache assignment
*/
protected getCrudService(assignment: ReferenceAssignment): CacheCrudService {
const entityKey = this.getEntityKey(assignment);
// repo matching assignment was injected?
if (this.allCrudServices[entityKey]) {
// yes, return it
return this.allCrudServices[entityKey];
} else {
// bad entity key
throw new CacheEntityNotFoundException(entityKey);
}
}

/**
* Get the entity key for the given assignment.
*
* @param assignment The cache assignment
*/
protected getEntityKey(assignment: ReferenceAssignment): string {
// have entity key for given assignment?
if (this.settings.assignments[assignment]) {
// yes, set it
const entityKey = this.settings.assignments[assignment].entityKey;
// repo matching assignment was injected?
if (this.allCrudServices[entityKey]) {
// yes, return it
return this.allCrudServices[entityKey];
} else {
// bad entity key
throw new CacheEntityNotFoundException(entityKey);
}
return this.settings.assignments[assignment].entityKey;
} else {
// bad assignment
throw new CacheAssignmentNotFoundException(assignment);
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
import { CacheEntityAlreadyExistsException } from './cache-entity-already-exists.exception';

describe(CacheEntityAlreadyExistsException.name, () => {
it('should create an instance of CacheEntityAlreadyExistsException', () => {
const exception = new CacheEntityAlreadyExistsException('TestEntity');
expect(exception).toBeInstanceOf(CacheEntityAlreadyExistsException);
});

it('should have the correct error message', () => {
const exception = new CacheEntityAlreadyExistsException('TestEntity');
expect(exception.message).toBe(
'TestEntity already exists with the given key, type, and assignee ID.',
);
});

it('should have the correct context', () => {
const exception = new CacheEntityAlreadyExistsException('TestEntity');
expect(exception.context).toEqual({ entityName: 'TestEntity' });
});

it('should have the correct error code', () => {
const exception = new CacheEntityAlreadyExistsException('TestEntity');
expect(exception.errorCode).toBe('CACHE_ENTITY_ALREADY_EXISTS_ERROR');
});
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import { RuntimeException } from '@concepta/nestjs-exception';
import { HttpStatus } from '@nestjs/common';

export class CacheEntityAlreadyExistsException extends RuntimeException {
context: RuntimeException['context'] & {
entityName: string;
};

constructor(
entityName: string,
message = '%s already exists with the given key, type, and assignee ID.',
) {
super({
httpStatus: HttpStatus.BAD_REQUEST,
message,
messageParams: [entityName],
});

this.errorCode = 'CACHE_ENTITY_ALREADY_EXISTS_ERROR';

this.context = {
...super.context,
entityName,
};
}
}
13 changes: 12 additions & 1 deletion packages/nestjs-cache/src/services/cache.service.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,9 @@ describe('CacheService', () => {
beforeEach(() => {
repo = mock<Repository<CacheInterface>>();
settings = mock<CacheSettingsInterface>();
settings.assignments = {
testAssignment: { entityKey: 'testAssignment' },
};
settings.expiresIn = '1h';
service = new CacheService({ testAssignment: repo }, settings);
});
Expand Down Expand Up @@ -101,14 +104,22 @@ describe('CacheService', () => {
repoProxyMock.repository.mockReturnValue(repo);

service['validateDto'] = jest.fn().mockResolvedValueOnce(cacheDto);
service['findCache'] = jest.fn();
const result = {
key: cacheDto.key,
type: cacheDto.type,
data: cacheDto.data,
assignee: cacheDto.assignee,
expirationDate,
};
service['findCache'] = jest.fn().mockImplementationOnce(() => {
return {
...result,
dateCreated: new Date(),
dateUpdated: new Date(),
id: 'testId',
version: 1,
} as CacheInterface;
});
service['mergeEntity'] = jest.fn().mockResolvedValue(result);

jest.spyOn(RepositoryProxy.prototype, 'repository').mockReturnValue(repo);
Expand Down
29 changes: 21 additions & 8 deletions packages/nestjs-cache/src/services/cache.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ import { CacheEntityNotFoundException } from '../exceptions/cache-entity-not-fou
import { CacheServiceInterface } from '../interfaces/cache-service.interface';
import { CacheSettingsInterface } from '../interfaces/cache-settings.interface';
import getExpirationDate from '../utils/get-expiration-date.util';
import { CacheAssignmentNotFoundException } from '../exceptions/cache-assignment-not-found.exception';

@Injectable()
export class CacheService implements CacheServiceInterface {
Expand Down Expand Up @@ -99,6 +100,10 @@ export class CacheService implements CacheServiceInterface {
// try to update the item
try {
const assignedCache = await this.findCache(repoProxy, dto, queryOptions);
if (!assignedCache)
throw new CacheEntityNotFoundException(
assignmentRepo.metadata.targetName,
);

const mergedEntity = await this.mergeEntity(
repoProxy,
Expand Down Expand Up @@ -265,18 +270,18 @@ export class CacheService implements CacheServiceInterface {
repoProxy: RepositoryProxy<CacheInterface>,
cache: Pick<CacheInterface, 'key' | 'type' | 'assignee'>,
queryOptions?: QueryOptionsInterface,
): Promise<CacheInterface> {
): Promise<CacheInterface | null> {
const { key, type, assignee } = cache;
try {
const cache = await repoProxy.repository(queryOptions).findOne({
const repo = repoProxy.repository(queryOptions);
const cache = await repo.findOne({
where: {
key,
type,
assignee,
},
relations: ['assignee'],
});
if (!cache) throw new Error('Could not find repository');
return cache;
} catch (e) {
throw new ReferenceLookupException(
Expand All @@ -295,13 +300,21 @@ export class CacheService implements CacheServiceInterface {
protected getAssignmentRepo(
assignment: ReferenceAssignment,
): Repository<CacheInterface> {
// repo matching assignment was injected?
if (this.allCacheRepos[assignment]) {
// yes, return it
return this.allCacheRepos[assignment];
if (this.settings.assignments[assignment]) {
// get entity key based on assignment
const entityKey = this.settings.assignments[assignment].entityKey;

// repo matching assignment was injected?
if (this.allCacheRepos[entityKey]) {
// yes, return it
return this.allCacheRepos[entityKey];
} else {
// bad assignment
throw new CacheEntityNotFoundException(entityKey);
}
} else {
// bad assignment
throw new CacheEntityNotFoundException(assignment);
throw new CacheAssignmentNotFoundException(assignment);
}
}

Expand Down
Loading