Merge pull request #1133 from Hexastack/1132-issue---api-make-sure-hookentityprepostcreate-is-used-across-the-board

fix(api): resolve predefined create hooks bug
This commit is contained in:
Med Marrouchi 2025-06-18 16:27:18 +01:00 committed by GitHub
commit c23a4cee08
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
7 changed files with 182 additions and 123 deletions

View File

@ -16,7 +16,6 @@ import { LabelDto } from '../dto/label.dto';
import { import {
Label, Label,
LABEL_POPULATE, LABEL_POPULATE,
LabelDocument,
LabelFull, LabelFull,
LabelPopulate, LabelPopulate,
} from '../schemas/label.schema'; } from '../schemas/label.schema';
@ -31,31 +30,4 @@ export class LabelRepository extends BaseRepository<
constructor(@InjectModel(Label.name) readonly model: Model<Label>) { constructor(@InjectModel(Label.name) readonly model: Model<Label>) {
super(model, Label, LABEL_POPULATE, LabelFull); super(model, Label, LABEL_POPULATE, LabelFull);
} }
/**
* After creating a `Label`, this method emits an event and updates the `label_id` field.
*
* @param created - The created label document instance.
*
* @returns A promise that resolves when the update operation is complete.
*/
async postCreate(created: LabelDocument): Promise<void> {
this.eventEmitter.emit(
'hook:label:create',
created,
async (result: Record<string, any>) => {
await this.model.updateOne(
{ _id: created._id },
{
$set: {
label_id: {
...(created.label_id || {}),
...result,
},
},
},
);
},
);
}
} }

View File

@ -18,6 +18,7 @@ import { SettingRepository } from '@/setting/repositories/setting.repository';
import { SettingModel } from '@/setting/schemas/setting.schema'; import { SettingModel } from '@/setting/schemas/setting.schema';
import { SettingSeeder } from '@/setting/seeds/setting.seed'; import { SettingSeeder } from '@/setting/seeds/setting.seed';
import { SettingService } from '@/setting/services/setting.service'; import { SettingService } from '@/setting/services/setting.service';
import { IGNORED_TEST_FIELDS } from '@/utils/test/constants';
import { nlpEntityFixtures } from '@/utils/test/fixtures/nlpentity'; import { nlpEntityFixtures } from '@/utils/test/fixtures/nlpentity';
import { installNlpValueFixtures } from '@/utils/test/fixtures/nlpvalue'; import { installNlpValueFixtures } from '@/utils/test/fixtures/nlpvalue';
import { getPageQuery } from '@/utils/test/pagination'; import { getPageQuery } from '@/utils/test/pagination';
@ -47,6 +48,8 @@ describe('NlpEntityRepository', () => {
let nlpValueRepository: NlpValueRepository; let nlpValueRepository: NlpValueRepository;
let firstNameNlpEntity: NlpEntity | null; let firstNameNlpEntity: NlpEntity | null;
let nlpService: NlpService; let nlpService: NlpService;
let llmNluHelper: LlmNluHelper;
let nlpEntityService: NlpEntityService;
beforeAll(async () => { beforeAll(async () => {
const { getMocks, module } = await buildTestingMocks({ const { getMocks, module } = await buildTestingMocks({
@ -98,15 +101,17 @@ describe('NlpEntityRepository', () => {
], ],
}); });
[nlpEntityRepository, nlpValueRepository, nlpService] = await getMocks([ [nlpEntityRepository, nlpValueRepository, nlpService, nlpEntityService] =
NlpEntityRepository, await getMocks([
NlpValueRepository, NlpEntityRepository,
NlpService, NlpValueRepository,
]); NlpService,
NlpEntityService,
]);
firstNameNlpEntity = await nlpEntityRepository.findOne({ firstNameNlpEntity = await nlpEntityRepository.findOne({
name: 'firstname', name: 'firstname',
}); });
const llmNluHelper = module.get(LlmNluHelper); llmNluHelper = module.get(LlmNluHelper);
module.get(HelperService).register(llmNluHelper); module.get(HelperService).register(llmNluHelper);
}); });
@ -173,4 +178,54 @@ describe('NlpEntityRepository', () => {
]); ]);
}); });
}); });
describe('postCreate', () => {
it('should create and attach a foreign_id to the newly created nlp entity', async () => {
nlpEntityRepository.eventEmitter.once(
'hook:nlpEntity:postCreate',
async (...[created]) => {
const helperSpy = jest.spyOn(llmNluHelper, 'addEntity');
jest.spyOn(nlpEntityService, 'updateOne');
await nlpService.handleEntityPostCreate(created);
expect(helperSpy).toHaveBeenCalledWith(created);
expect(nlpEntityService.updateOne).toHaveBeenCalledWith(
{
_id: created._id,
},
{ foreign_id: await helperSpy.mock.results[0].value },
);
},
);
const result = await nlpEntityRepository.create({
name: 'test1',
});
const intentNlpEntity = await nlpEntityRepository.findOne(result.id);
expect(intentNlpEntity?.foreign_id).toBeDefined();
expect(intentNlpEntity).toEqualPayload(result, [
...IGNORED_TEST_FIELDS,
'foreign_id',
]);
});
it('should not create and attach a foreign_id to the newly created nlp entity with builtin set to true', async () => {
nlpEntityRepository.eventEmitter.once(
'hook:nlpEntity:postCreate',
async (...[created]) => {
await nlpService.handleEntityPostCreate(created);
},
);
const result = await nlpEntityRepository.create({
name: 'test2',
builtin: true,
});
const nlpEntity = await nlpEntityRepository.findOne(result.id);
expect(nlpEntity?.foreign_id).toBeUndefined();
expect(nlpEntity).toEqualPayload(result);
});
});
}); });

View File

@ -16,7 +16,6 @@ import { NlpEntityDto } from '../dto/nlp-entity.dto';
import { import {
NLP_ENTITY_POPULATE, NLP_ENTITY_POPULATE,
NlpEntity, NlpEntity,
NlpEntityDocument,
NlpEntityFull, NlpEntityFull,
NlpEntityPopulate, NlpEntityPopulate,
} from '../schemas/nlp-entity.schema'; } from '../schemas/nlp-entity.schema';
@ -32,20 +31,6 @@ export class NlpEntityRepository extends BaseRepository<
super(model, NlpEntity, NLP_ENTITY_POPULATE, NlpEntityFull); super(model, NlpEntity, NLP_ENTITY_POPULATE, NlpEntityFull);
} }
/**
* Post-create hook that triggers after an NLP entity is created.
* Emits an event to notify other parts of the system about the creation.
* Bypasses built-in entities.
*
* @param created - The newly created NLP entity document.
*/
async postCreate(_created: NlpEntityDocument): Promise<void> {
if (!_created.builtin) {
// Bypass builtin entities (probably fixtures)
this.eventEmitter.emit('hook:nlpEntity:create', _created);
}
}
/** /**
* Post-update hook that triggers after an NLP entity is updated. * Post-update hook that triggers after an NLP entity is updated.
* Emits an event to notify other parts of the system about the update. * Emits an event to notify other parts of the system about the update.

View File

@ -18,6 +18,7 @@ import { SettingRepository } from '@/setting/repositories/setting.repository';
import { SettingModel } from '@/setting/schemas/setting.schema'; import { SettingModel } from '@/setting/schemas/setting.schema';
import { SettingSeeder } from '@/setting/seeds/setting.seed'; import { SettingSeeder } from '@/setting/seeds/setting.seed';
import { SettingService } from '@/setting/services/setting.service'; import { SettingService } from '@/setting/services/setting.service';
import { IGNORED_TEST_FIELDS } from '@/utils/test/constants';
import { nlpEntityFixtures } from '@/utils/test/fixtures/nlpentity'; import { nlpEntityFixtures } from '@/utils/test/fixtures/nlpentity';
import { installNlpSampleEntityFixtures } from '@/utils/test/fixtures/nlpsampleentity'; import { installNlpSampleEntityFixtures } from '@/utils/test/fixtures/nlpsampleentity';
import { nlpValueFixtures } from '@/utils/test/fixtures/nlpvalue'; import { nlpValueFixtures } from '@/utils/test/fixtures/nlpvalue';
@ -53,6 +54,9 @@ describe('NlpValueRepository', () => {
let nlpSampleEntityRepository: NlpSampleEntityRepository; let nlpSampleEntityRepository: NlpSampleEntityRepository;
let nlpValues: NlpValue[]; let nlpValues: NlpValue[];
let nlpService: NlpService; let nlpService: NlpService;
let nlpEntityRepository: NlpEntityRepository;
let llmNluHelper: LlmNluHelper;
let nlpValueService: NlpValueService;
beforeAll(async () => { beforeAll(async () => {
const { getMocks, module } = await buildTestingMocks({ const { getMocks, module } = await buildTestingMocks({
@ -102,14 +106,21 @@ describe('NlpValueRepository', () => {
], ],
}); });
[nlpValueRepository, nlpSampleEntityRepository, nlpService] = [
await getMocks([ nlpValueRepository,
NlpValueRepository, nlpSampleEntityRepository,
NlpSampleEntityRepository, nlpService,
NlpService, nlpEntityRepository,
]); nlpValueService,
] = await getMocks([
NlpValueRepository,
NlpSampleEntityRepository,
NlpService,
NlpEntityRepository,
NlpValueService,
]);
nlpValues = await nlpValueRepository.findAll(); nlpValues = await nlpValueRepository.findAll();
const llmNluHelper = module.get(LlmNluHelper); llmNluHelper = module.get(LlmNluHelper);
module.get(HelperService).register(llmNluHelper); module.get(HelperService).register(llmNluHelper);
}); });
@ -180,4 +191,63 @@ describe('NlpValueRepository', () => {
expect(sampleEntities.length).toEqual(0); expect(sampleEntities.length).toEqual(0);
}); });
}); });
describe('postCreate', () => {
it('should create and attach a foreign_id to the newly created nlp value', async () => {
nlpValueRepository.eventEmitter.once(
'hook:nlpValue:postCreate',
async (...[created]) => {
const helperSpy = jest.spyOn(llmNluHelper, 'addValue');
jest.spyOn(nlpValueService, 'updateOne');
await nlpService.handleValuePostCreate(created);
expect(helperSpy).toHaveBeenCalledWith(created);
expect(nlpValueService.updateOne).toHaveBeenCalledWith(
{
_id: created._id,
},
{ foreign_id: await helperSpy.mock.results[0].value },
);
},
);
const createdNlpEntity = await nlpEntityRepository.create({
name: 'test1',
});
const result = await nlpValueRepository.create({
entity: createdNlpEntity.id,
value: 'test',
});
const intentNlpEntity = await nlpValueRepository.findOne(result.id);
expect(intentNlpEntity?.foreign_id).toBeDefined();
expect(intentNlpEntity).toEqualPayload(result, [
...IGNORED_TEST_FIELDS,
'foreign_id',
]);
});
it('should not create and attach a foreign_id to the newly created nlp value with builtin set to true', async () => {
nlpValueRepository.eventEmitter.once(
'hook:nlpValue:postCreate',
async (...[created]) => {
await nlpService.handleValuePostCreate(created);
},
);
const createdNlpEntity = await nlpEntityRepository.create({
name: 'nlpEntityTest2',
});
const result = await nlpValueRepository.create({
entity: createdNlpEntity.id,
value: 'nlpValueTest2',
builtin: true,
});
const nlpValue = await nlpValueRepository.findOne(result.id);
expect(nlpValue?.foreign_id).toBeUndefined();
expect(nlpValue).toEqualPayload(result);
});
});
}); });

View File

@ -27,7 +27,6 @@ import { NlpValueDto } from '../dto/nlp-value.dto';
import { import {
NLP_VALUE_POPULATE, NLP_VALUE_POPULATE,
NlpValue, NlpValue,
NlpValueDocument,
NlpValueFull, NlpValueFull,
NlpValueFullWithCount, NlpValueFullWithCount,
NlpValuePopulate, NlpValuePopulate,
@ -46,18 +45,6 @@ export class NlpValueRepository extends BaseRepository<
super(model, NlpValue, NLP_VALUE_POPULATE, NlpValueFull); super(model, NlpValue, NLP_VALUE_POPULATE, NlpValueFull);
} }
/**
* Emits an event after a new NLP value is created, bypassing built-in values.
*
* @param created - The newly created NLP value document.
*/
async postCreate(created: NlpValueDocument): Promise<void> {
if (!created.builtin) {
// Bypass builtin entities (probably fixtures)
this.eventEmitter.emit('hook:nlpValue:create', created);
}
}
/** /**
* Emits an event after an NLP value is updated, bypassing built-in values. * Emits an event after an NLP value is updated, bypassing built-in values.
* *

View File

@ -69,21 +69,25 @@ export class NlpService {
* *
* @param entity - The NLP entity to be created. * @param entity - The NLP entity to be created.
*/ */
@OnEvent('hook:nlpEntity:create') @OnEvent('hook:nlpEntity:postCreate')
async handleEntityCreate(entity: NlpEntityDocument) { async handleEntityPostCreate(created: NlpEntityDocument) {
// Synchonize new entity with NLP if (!created.builtin) {
try { // Synchonize new entity with NLP
const helper = await this.helperService.getDefaultHelper(HelperType.NLU); try {
const foreignId = await helper.addEntity(entity); const helper = await this.helperService.getDefaultHelper(
this.logger.debug('New entity successfully synced!', foreignId); HelperType.NLU,
await this.nlpEntityService.updateOne( );
{ _id: entity._id }, const foreignId = await helper.addEntity(created);
{ this.logger.debug('New entity successfully synced!', foreignId);
foreign_id: foreignId, await this.nlpEntityService.updateOne(
}, { _id: created._id },
); {
} catch (err) { foreign_id: foreignId,
this.logger.error('Unable to sync a new entity', err); },
);
} catch (err) {
this.logger.error('Unable to sync a new entity', err);
}
} }
} }
@ -149,21 +153,25 @@ export class NlpService {
* *
* @param value - The NLP value to be created. * @param value - The NLP value to be created.
*/ */
@OnEvent('hook:nlpValue:create') @OnEvent('hook:nlpValue:postCreate')
async handleValueCreate(value: NlpValueDocument) { async handleValuePostCreate(created: NlpValueDocument) {
// Synchonize new value with NLP provider if (!created.builtin) {
try { // Synchonize new value with NLP provider
const helper = await this.helperService.getDefaultNluHelper(); try {
const foreignId = await helper.addValue(value); const helper = await this.helperService.getDefaultHelper(
this.logger.debug('New value successfully synced!', foreignId); HelperType.NLU,
await this.nlpValueService.updateOne( );
{ _id: value._id }, const foreignId = await helper.addValue(created);
{ this.logger.debug('New value successfully synced!', foreignId);
foreign_id: foreignId, await this.nlpValueService.updateOne(
}, { _id: created._id },
); {
} catch (err) { foreign_id: foreignId,
this.logger.error('Unable to sync a new value', err); },
);
} catch (err) {
this.logger.error('Unable to sync a new value', err);
}
} }
} }

View File

@ -19,7 +19,7 @@ import type { Block, BlockFull } from '@/chat/schemas/block.schema';
import { type Category } from '@/chat/schemas/category.schema'; import { type Category } from '@/chat/schemas/category.schema';
import { type ContextVar } from '@/chat/schemas/context-var.schema'; import { type ContextVar } from '@/chat/schemas/context-var.schema';
import { type Conversation } from '@/chat/schemas/conversation.schema'; import { type Conversation } from '@/chat/schemas/conversation.schema';
import type { Label, LabelDocument } from '@/chat/schemas/label.schema'; import type { Label } from '@/chat/schemas/label.schema';
import { type Message } from '@/chat/schemas/message.schema'; import { type Message } from '@/chat/schemas/message.schema';
import { type Subscriber } from '@/chat/schemas/subscriber.schema'; import { type Subscriber } from '@/chat/schemas/subscriber.schema';
import { type ContentType } from '@/cms/schemas/content-type.schema'; import { type ContentType } from '@/cms/schemas/content-type.schema';
@ -27,16 +27,10 @@ import { type Content } from '@/cms/schemas/content.schema';
import { type Menu } from '@/cms/schemas/menu.schema'; import { type Menu } from '@/cms/schemas/menu.schema';
import { type Language } from '@/i18n/schemas/language.schema'; import { type Language } from '@/i18n/schemas/language.schema';
import { type Translation } from '@/i18n/schemas/translation.schema'; import { type Translation } from '@/i18n/schemas/translation.schema';
import type { import type { NlpEntity } from '@/nlp/schemas/nlp-entity.schema';
NlpEntity,
NlpEntityDocument,
} from '@/nlp/schemas/nlp-entity.schema';
import { type NlpSampleEntity } from '@/nlp/schemas/nlp-sample-entity.schema'; import { type NlpSampleEntity } from '@/nlp/schemas/nlp-sample-entity.schema';
import { type NlpSample } from '@/nlp/schemas/nlp-sample.schema'; import { type NlpSample } from '@/nlp/schemas/nlp-sample.schema';
import type { import type { NlpValue } from '@/nlp/schemas/nlp-value.schema';
NlpValue,
NlpValueDocument,
} from '@/nlp/schemas/nlp-value.schema';
import { type Setting } from '@/setting/schemas/setting.schema'; import { type Setting } from '@/setting/schemas/setting.schema';
import { type Invitation } from '@/user/schemas/invitation.schema'; import { type Invitation } from '@/user/schemas/invitation.schema';
import { type Model } from '@/user/schemas/model.schema'; import { type Model } from '@/user/schemas/model.schema';
@ -130,7 +124,7 @@ declare module '@nestjs/event-emitter' {
category: TDefinition<Category>; category: TDefinition<Category>;
contextVar: TDefinition<ContextVar>; contextVar: TDefinition<ContextVar>;
conversation: TDefinition<Conversation, { end: unknown; close: unknown }>; conversation: TDefinition<Conversation, { end: unknown; close: unknown }>;
label: TDefinition<Label, { create: LabelDocument }>; label: TDefinition<Label>;
message: TDefinition<Message>; message: TDefinition<Message>;
subscriber: TDefinition<Subscriber, { assign: SubscriberUpdateDto }>; subscriber: TDefinition<Subscriber, { assign: SubscriberUpdateDto }>;
contentType: TDefinition<ContentType>; contentType: TDefinition<ContentType>;
@ -138,22 +132,10 @@ declare module '@nestjs/event-emitter' {
menu: TDefinition<Menu>; menu: TDefinition<Menu>;
language: TDefinition<Language>; language: TDefinition<Language>;
translation: TDefinition<Translation>; translation: TDefinition<Translation>;
nlpEntity: TDefinition< nlpEntity: TDefinition<NlpEntity, { update: NlpEntity }>;
NlpEntity,
{
create: NlpEntityDocument;
update: NlpEntity;
}
>;
nlpSampleEntity: TDefinition<NlpSampleEntity>; nlpSampleEntity: TDefinition<NlpSampleEntity>;
nlpSample: TDefinition<NlpSample>; nlpSample: TDefinition<NlpSample>;
nlpValue: TDefinition< nlpValue: TDefinition<NlpValue, { update: NlpValue }>;
NlpValue,
{
create: NlpValueDocument;
update: NlpValue;
}
>;
setting: TDefinition<Setting>; setting: TDefinition<Setting>;
invitation: TDefinition<Invitation>; invitation: TDefinition<Invitation>;
model: TDefinition<Model>; model: TDefinition<Model>;