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: add logic to create/update on service instead of crudservice #189

Merged
merged 5 commits into from
Jul 24, 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
Original file line number Diff line number Diff line change
Expand Up @@ -111,7 +111,7 @@ describe('CacheAssignmentController (e2e)', () => {
});
});

it('POST /cache/user', async () => {
it('POST /cache/user creating user with success', async () => {
const payload: CacheCreatableInterface = {
key: 'dashboard-1',
type: 'filter',
Expand Down Expand Up @@ -265,6 +265,71 @@ describe('CacheAssignmentController (e2e)', () => {
expect(res.body.data).toBe(payload.data);
expect(res.body.assignee.id).toBe(user.id);
});

const url =
`/cache/user/` +
`?filter[0]=key||$eq||${payload.key}` +
`&filter[1]=type||$eq||${payload.type}` +
`&filter[2]=assignee.id||$eq||${payload.assignee.id}`;
// Assuming your endpoint can filter by key and type
await supertest(app.getHttpServer())
.get(url)
.expect(200)
.then((res) => {
const response = res.body[0];
assert.strictEqual(response.assignee.id, user.id);
assert.strictEqual(response.key, payload.key);
assert.strictEqual(response.type, payload.type);
assert.strictEqual(response.data, payload.data);
});
});

it.only('PUT /cache/user replace', async () => {
const payload: CacheCreatableInterface = {
key: 'dashboard-1',
type: 'filter',
data: '{}',
expiresIn: '1d',
assignee: { id: user.id },
};
let cacheId = '';
await supertest(app.getHttpServer())
.put('/cache/user')
.send(payload)
.expect(200)
.then((res) => {
cacheId = res.body.id;
expect(res.body.key).toBe(payload.key);
expect(res.body.assignee.id).toBe(user.id);
});
payload.data = '{ "name": "John Doe" }';
payload.expiresIn = null;
await supertest(app.getHttpServer())
.put(`/cache/user/${cacheId}`)
.send(payload)
.expect(200)
.then((res) => {
expect(res.body.key).toBe(payload.key);
expect(res.body.data).toBe(payload.data);
expect(res.body.assignee.id).toBe(user.id);
});

const url =
`/cache/user/` +
`?filter[0]=key||$eq||${payload.key}` +
`&filter[1]=type||$eq||${payload.type}` +
`&filter[2]=assignee.id||$eq||${payload.assignee.id}`;
// Assuming your endpoint can filter by key and type
await supertest(app.getHttpServer())
.get(url)
.expect(200)
.then((res) => {
const response = res.body[0];
assert.strictEqual(response.assignee.id, user.id);
assert.strictEqual(response.key, payload.key);
assert.strictEqual(response.type, payload.type);
assert.strictEqual(response.data, payload.data);
});
});

it('DELETE /cache/user/:id', async () => {
Expand Down
83 changes: 50 additions & 33 deletions packages/nestjs-cache/src/controllers/cache-crud.controller.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { Inject, Param } from '@nestjs/common';
import { ApiTags } from '@nestjs/swagger';
import { Inject, Param, Put } from '@nestjs/common';
import { ApiOkResponse, ApiTags } from '@nestjs/swagger';
import {
AccessControlCreateOne,
AccessControlDeleteOne,
Expand All @@ -14,6 +14,7 @@ import {
CrudDeleteOne,
CrudReadMany,
CrudReadOne,
CrudReplaceOne,
CrudRequest,
CrudRequestInterface,
CrudUpdateOne,
Expand Down Expand Up @@ -64,7 +65,7 @@ export class CacheCrudController
CacheInterface,
CacheCreatableInterface,
CacheUpdatableInterface,
never
CacheCreatableInterface
>
{
/**
Expand Down Expand Up @@ -130,42 +131,18 @@ export class CacheCrudController
cacheCreateDto.expiresIn ?? this.settings.expiresIn,
);

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

// update or create
if (existingCache) {
crudRequest.parsed.search.$and?.push({
id: {
$eq: existingCache.id,
},
});
// call crud service to create
const response = await this.getCrudService(assignment).updateOne(
crudRequest,
{
id: existingCache.id,
...cacheCreateDto,
expirationDate,
},
);
return response;
} else {
// call crud service to create
return this.getCrudService(assignment).createOne(crudRequest, {
...cacheCreateDto,
expirationDate,
});
}
// call crud service to create
return this.getCrudService(assignment).createOne(crudRequest, {
...cacheCreateDto,
expirationDate,
});
}

/**
* Create one
*
* @param crudRequest - the CRUD request object
* @param cacheUpdateDto - cache create dto
* @param cacheUpdateDto - cache update dto
* @param assignment - The cache assignment
*/
@CrudUpdateOne()
Expand Down Expand Up @@ -219,6 +196,46 @@ export class CacheCrudController
}
}

/**
* Do a Upsert operation for cache
*
* @param crudRequest - the CRUD request object
* @param cacheUpdateDto - cache update dto
* @param assignment - The cache assignment
*/
@Put(':id?')
@ApiOkResponse({
type: CacheDto,
})
@CrudReplaceOne()
@AccessControlCreateOne(CacheResource.One)
async replaceOne(
@CrudRequest() crudRequest: CrudRequestInterface,
@CrudBody() cacheUpdateDto: CacheUpdateDto,
@Param('assignment') assignment: ReferenceAssignment,
) {
let cache;
try {
cache = await this.getOne(crudRequest, assignment);
} catch (error) {
// TODO: find a better aproach
// getOne throws and error if id does not match
}
if (cache && cache?.id) {
const expirationDate = getExpirationDate(
cacheUpdateDto.expiresIn ?? this.settings.expiresIn,
);

// call crud service to create
return this.getCrudService(assignment).replaceOne(crudRequest, {
...cacheUpdateDto,
expirationDate,
});
} else {
return this.createOne(crudRequest, cacheUpdateDto, assignment);
}
}

/**
* Get the entity key for the given assignment.
*
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { ReferenceAssignment } from '@concepta/ts-core';
import { QueryOptionsInterface } from '@concepta/typeorm-common';
import {
CacheClearInterface,
CacheCreatableInterface,
CacheCreateInterface,
CacheDeleteInterface,
CacheGetOneInterface,
Expand All @@ -15,6 +16,12 @@ export interface CacheServiceInterface
CacheUpdateInterface<QueryOptionsInterface>,
CacheGetOneInterface<QueryOptionsInterface>,
CacheClearInterface<QueryOptionsInterface> {
updateOrCreate(
assignment: ReferenceAssignment,
cache: CacheCreatableInterface,
options?: QueryOptionsInterface,
): Promise<CacheInterface>;

getAssignedCaches(
assignment: ReferenceAssignment,
cache: Pick<CacheInterface, 'assignee'>,
Expand Down
13 changes: 13 additions & 0 deletions packages/nestjs-cache/src/services/cache.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -239,6 +239,19 @@ export class CacheService implements CacheServiceInterface {
}
}

async updateOrCreate(
assignment: ReferenceAssignment,
cache: CacheCreateDto,
queryOptions?: QueryOptionsInterface,
): Promise<CacheInterface> {
const existingCache = await this.get(assignment, cache, queryOptions);
if (existingCache) {
return await this.update(assignment, cache, queryOptions);
} else {
return await this.create(assignment, cache, queryOptions);
}
}

// Should this be on nestjs-common?
protected async validateDto<T extends DeepPartial<CacheInterface>>(
type: Type<T>,
Expand Down
Loading