Skip to content

Commit

Permalink
feat(WEB-2070): WEB-2070 Wait for db write on whisp create
Browse files Browse the repository at this point in the history
  • Loading branch information
sairam459 committed Apr 8, 2024
1 parent 47df68d commit feac2d3
Show file tree
Hide file tree
Showing 3 changed files with 117 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);
}
}
4 changes: 2 additions & 2 deletions src/whisp/whisp.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,8 @@ export class WhispService {
const { timeToLiveSec, expirationDate } = WhispService.fillTTL(whispIn, now);
whisp.timeToLiveSec = timeToLiveSec;
whisp.expirationDate = expirationDate;
const createdWhisp = await this.whispModel.create(whisp);
const whispInstance = new this.whispModel(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 +128,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
162 changes: 114 additions & 48 deletions tests/unit/whisp/whisp.service.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import { FileService } from '../../../src/file/file.service';
import { SequenceService } from '../../../src/sequence/sequence.service';
import { WhispService } from '../../../src/whisp/whisp.service';
import { DistributionService } from '../../../src/distribution/distribution.service';
import { Whisp } from '../../../src/whisp/whisp.entity';

jest.mock('../../../src/distribution/distribution.service');
jest.mock('../../../src/event/event.service');
Expand All @@ -16,66 +17,64 @@ jest.mock('../../../src/sequence/sequence.service');

describe('WhispService', () => {
let whispService: WhispService;
let whispModel: Model<IWhisp>;
let whispModel;
const OBJECT_ID = '56cb91bdc3464f14678934ca';

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'));
});

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

describe('create Whisp', () => {
let constructorData = {};
beforeEach(async () => {
constructorData = {}
class mockModel {
constructor(public data?: any) {
constructorData = data;
this.data = data

}
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'));
});

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 +105,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 +118,39 @@ describe('WhispService', () => {
});

describe('Update Whisp', () => {
beforeEach(async () => {
const moduleRef = await Test.createTestingModule({
providers: [
{
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,
],
}).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 +178,39 @@ describe('WhispService', () => {
});

describe('Count Whisp', () => {
beforeEach(async () => {
const moduleRef = await Test.createTestingModule({
providers: [
{
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,
],
}).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 feac2d3

Please sign in to comment.