Skip to content

Commit

Permalink
Merge pull request #832 from Sanofi-IADC/feature/WEB-2070-tags
Browse files Browse the repository at this point in the history
feat(WEB-2070): WEB-2070 Wait for db write on whisp create
  • Loading branch information
sairam459 authored Apr 10, 2024
2 parents de5eb4f + 24df059 commit 4c1412a
Show file tree
Hide file tree
Showing 3 changed files with 90 additions and 54 deletions.
5 changes: 1 addition & 4 deletions src/whisp/whisp.resolver.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,9 +33,7 @@ export class WhispResolver {
@Inject('PUB_SUB') private pubSub: PubSubEngine,
) {
this.distributionService.whispSubject.subscribe((whisp) => {
setTimeout(() => {
pubSub.publish('whispAdded', { whispAdded: whisp });
}, 1000);
pubSub.publish('whispAdded', { whispAdded: whisp });
});
}

Expand Down Expand Up @@ -128,7 +126,6 @@ export class WhispResolver {
@ResolveField(() => [Tag])
async tags(@Root() whisp: Whisp): Promise<TagInputType[]> {
// eslint-disable-next-line no-underscore-dangle
this.logger.log(`Test logging whisp ${JSON.stringify(whisp)}`);
return this.whispService.findTagsByWhispId(whisp._id);
}
}
5 changes: 3 additions & 2 deletions src/whisp/whisp.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,9 @@ export class WhispService {
const { timeToLiveSec, expirationDate } = WhispService.fillTTL(whispIn, now);
whisp.timeToLiveSec = timeToLiveSec;
whisp.expirationDate = expirationDate;
const createdWhisp = await this.whispModel.create(whisp);
const WhispDocModel = this.whispModel;
const whispInstance = new WhispDocModel(whisp);
const createdWhisp = await whispInstance.save();
await this.eventService.triggerEvent(new Event(EventNames.WHISP_CREATED, createdWhisp));
this.distributionService.distributeWhisp(createdWhisp);

Expand Down Expand Up @@ -127,7 +129,6 @@ export class WhispService {
}

async findTagsByWhispId(whispId: string): Promise<TagInputType[]> {
this.logger.log(`Test logging whispId ${whispId}`);
const whisps = await this.whispModel.findById(whispId).populate('tags').exec();
return whisps.tags;
}
Expand Down
134 changes: 86 additions & 48 deletions tests/unit/whisp/whisp.service.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,68 +14,89 @@ jest.mock('../../../src/event/event.service');
jest.mock('../../../src/file/file.service');
jest.mock('../../../src/sequence/sequence.service');

// function to retrieve input of the called function
const passThrough = (data) =>
new Promise((resolve) => {
resolve(data);
});
const commonProviders = [
{
provide: getModelToken('Whisp'),
useFactory: () => ({
findOneAndUpdate: jest.fn().mockReturnThis(),
create: jest.fn().mockImplementation(passThrough),
save: jest.fn().mockImplementation(passThrough),
update: jest.fn(),
aggregate: jest.fn().mockReturnThis(),
allowDiskUse: jest.fn().mockReturnThis(),
exec: jest.fn(),
constructor: jest.fn(),
}),
},
WhispService,
Logger,
{
provide: DistributionService,
useFactory: () => ({
distributeWhisp: jest.fn(() => true),
}),
},
FileService,
SequenceService,
EventService,
];
describe('WhispService', () => {
let whispService: WhispService;
let whispModel: Model<IWhisp>;
let whispModel;
const OBJECT_ID = '56cb91bdc3464f14678934ca';
describe('create Whisp', () => {
let constructorData: any;
beforeEach(async () => {
constructorData = {};
class mockModel {
constructor(public data?: any) {
constructorData = data;
this.data = data;
}

beforeEach(async () => {
// function to retrieve input of the called function
const passThrough = (data) =>
new Promise((resolve) => {
resolve(data);
});

const moduleRef = await Test.createTestingModule({
providers: [
{
provide: getModelToken('Whisp'),
useFactory: () => ({
findOneAndUpdate: jest.fn().mockReturnThis(),
create: jest.fn().mockImplementation(passThrough),
update: jest.fn(),
aggregate: jest.fn().mockReturnThis(),
allowDiskUse: jest.fn().mockReturnThis(),
exec: jest.fn(),
}),
},
WhispService,
Logger,
{
provide: DistributionService,
useFactory: () => ({
distributeWhisp: jest.fn(() => true),
}),
},
FileService,
SequenceService,
EventService,
],
}).compile();
whispService = moduleRef.get<WhispService>(WhispService);
whispModel = moduleRef.get<Model<IWhisp>>(getModelToken('Whisp'));
});
save = jest.fn().mockReturnValue(this.data);
}
const moduleRef = await Test.createTestingModule({
providers: [
{
provide: getModelToken('Whisp'),
useValue: mockModel,
},
WhispService,
Logger,
{
provide: DistributionService,
useFactory: () => ({
distributeWhisp: jest.fn(() => true),
}),
},
FileService,
SequenceService,
EventService,
],
}).compile();
whispService = moduleRef.get<WhispService>(WhispService);
whispModel = moduleRef.get(getModelToken('Whisp'));
});

describe('create Whisp', () => {
it('should set Timestamp when no timestamp is provided', async () => {
await whispService.create({});

expect(whispModel.create).toBeCalledWith(
expect.objectContaining({
timestamp: expect.any(Date),
}),
);
expect(constructorData).toHaveProperty('timestamp');
expect(constructorData.timestamp).toBeDefined();
});

it('should keep custom timestamp when timestamp is provided', async () => {
const timestamp = new Date();
await whispService.create({ timestamp });

expect(whispModel.create).toBeCalledWith(
expect.objectContaining({
timestamp,
}),
);
expect(constructorData).toHaveProperty('timestamp');
expect(constructorData.timestamp).toBe(timestamp);
});

it('when ttl is provided expirationDate should be generate and be equal to updated date plus ttl duration', async () => {
Expand Down Expand Up @@ -106,6 +127,7 @@ describe('WhispService', () => {
'time to live must be positive number of seconds or a parsable time string like 2min,1hour',
);
});

it('expirationDate override ttl', async () => {
const now = new Date();
now.setSeconds(now.getSeconds() + 2);
Expand All @@ -118,6 +140,14 @@ describe('WhispService', () => {
});

describe('Update Whisp', () => {
beforeEach(async () => {
const moduleRef = await Test.createTestingModule({
providers: commonProviders,
}).compile();
whispService = moduleRef.get<WhispService>(WhispService);
whispModel = moduleRef.get<Model<IWhisp>>(getModelToken('Whisp'));
});

it('should update timestamp when it is provided', async () => {
const timestamp = new Date();
timestamp.setHours(timestamp.getHours() + 1);
Expand Down Expand Up @@ -145,6 +175,14 @@ describe('WhispService', () => {
});

describe('Count Whisp', () => {
beforeEach(async () => {
const moduleRef = await Test.createTestingModule({
providers: commonProviders,
}).compile();
whispService = moduleRef.get<WhispService>(WhispService);
whispModel = moduleRef.get<Model<IWhisp>>(getModelToken('Whisp'));
});

it('calls mongo aggregate with empty match and group when they are not passed as parameters', async () => {
await whispService.countWhispsGroup();
const expectedMatch = { $match: {} };
Expand Down

0 comments on commit 4c1412a

Please sign in to comment.