Skip to content
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
166 changes: 166 additions & 0 deletions quotevote-backend/__tests__/unit/resolvers/heartbeatResolver.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,166 @@
import { GraphQLError } from 'graphql';
import { heartbeatResolver } from '~/data/resolvers/heartbeatResolver';
import Presence from '~/data/models/Presence';
import { pubsub } from '~/data/utils/pubsub';
import { SUBSCRIPTION_EVENTS } from '~/types/graphql';
import type { GraphQLContext } from '~/types/graphql';

jest.mock('~/data/models/Presence');
jest.mock('~/data/utils/pubsub', () => ({
pubsub: {
publish: jest.fn().mockResolvedValue(undefined),
subscribe: jest.fn(),
unsubscribe: jest.fn(),
asyncIterableIterator: jest.fn(),
},
}));

const actorId = '60d5ec49ad414d7a8d5464a0';

function mockContext(overrides: Partial<NonNullable<GraphQLContext['user']>> = {}): GraphQLContext {
return {
req: {} as GraphQLContext['req'],
res: {} as GraphQLContext['res'],
pubsub: {} as GraphQLContext['pubsub'],
user: {
_id: actorId,
username: 'alice',
email: 'alice@example.com',
admin: false,
...overrides,
} as NonNullable<GraphQLContext['user']>,
};
}

describe('heartbeatResolver', () => {
beforeEach(() => {
jest.clearAllMocks();
});

describe('Mutation.heartbeat', () => {
it('requires authentication', async () => {
await expect(
heartbeatResolver.Mutation.heartbeat(null, {}, { ...mockContext(), user: null })
).rejects.toThrow(GraphQLError);
});

it('updates heartbeat and returns success', async () => {
(Presence.updateHeartbeat as jest.Mock).mockResolvedValue({
lastHeartbeat: new Date('2024-01-15T12:00:00.000Z'),
status: 'away',
statusMessage: 'In a meeting',
});

const result = await heartbeatResolver.Mutation.heartbeat(null, {}, mockContext());

expect(Presence.updateHeartbeat).toHaveBeenCalledWith(actorId);
expect(result).toEqual({
success: true,
timestamp: '2024-01-15T12:00:00.000Z',
status: 'away',
statusMessage: 'In a meeting',
});
});
});

describe('Mutation.updatePresence', () => {
it('requires authentication', async () => {
await expect(
heartbeatResolver.Mutation.updatePresence(
null,
{ presence: { status: 'away', statusMessage: 'BRB' } },
{ ...mockContext(), user: null }
)
).rejects.toThrow(GraphQLError);
});

it('rejects invalid status', async () => {
await expect(
heartbeatResolver.Mutation.updatePresence(
null,
{ presence: { status: 'busy' } },
mockContext()
)
).rejects.toThrow(/status must be one of/);
expect(Presence.findOneAndUpdate).not.toHaveBeenCalled();
});

it('upserts presence and publishes update', async () => {
const now = new Date('2024-01-15T12:00:00.000Z');
jest.useFakeTimers().setSystemTime(now);

(Presence.findOneAndUpdate as jest.Mock).mockResolvedValue({
_id: { toString: () => 'presence-1' },
userId: { toString: () => actorId },
status: 'away',
statusMessage: 'In a meeting',
preferredStatus: 'away',
preferredStatusMessage: 'In a meeting',
lastHeartbeat: now,
lastSeen: now,
});

const result = await heartbeatResolver.Mutation.updatePresence(
null,
{ presence: { status: 'away', statusMessage: ' In a meeting ' } },
mockContext()
);

expect(Presence.findOneAndUpdate).toHaveBeenCalledWith(
{ userId: actorId },
{
$set: {
status: 'away',
statusMessage: 'In a meeting',
preferredStatus: 'away',
preferredStatusMessage: 'In a meeting',
lastHeartbeat: now,
lastSeen: now,
},
},
{ upsert: true, new: true, setDefaultsOnInsert: true }
);
expect(pubsub.publish).toHaveBeenCalledWith(SUBSCRIPTION_EVENTS.PRESENCE_UPDATED, {
presence: {
userId: actorId,
status: 'away',
statusMessage: 'In a meeting',
lastSeen: now,
},
});
expect(result).toEqual({
_id: 'presence-1',
userId: actorId,
status: 'away',
statusMessage: 'In a meeting',
lastHeartbeat: now,
lastSeen: now,
});

jest.useRealTimers();
});

it('truncates status messages over 200 characters', async () => {
const longMessage = 'x'.repeat(250);
(Presence.findOneAndUpdate as jest.Mock).mockResolvedValue({
_id: { toString: () => 'presence-1' },
userId: { toString: () => actorId },
status: 'online',
statusMessage: 'x'.repeat(200),
lastHeartbeat: new Date(),
lastSeen: new Date(),
});

await heartbeatResolver.Mutation.updatePresence(
null,
{ presence: { status: 'online', statusMessage: longMessage } },
mockContext()
);

const updateArg = (Presence.findOneAndUpdate as jest.Mock).mock.calls[0][1] as {
$set: { statusMessage: string };
};
expect(updateArg.$set.statusMessage).toHaveLength(200);
});
});
});
118 changes: 88 additions & 30 deletions quotevote-backend/app/data/models/Presence.ts
Original file line number Diff line number Diff line change
@@ -1,47 +1,105 @@
import mongoose, { Schema } from 'mongoose';
import type { PresenceDocument, PresenceModel } from '../../types/mongoose';
import type { PresenceStatus } from '../../types/common';

const STATUS_ENUM = ['online', 'away', 'dnd', 'offline', 'invisible'] as const;

const PresenceSchema = new Schema<PresenceDocument, PresenceModel>(
{
userId: { type: Schema.Types.ObjectId, ref: 'User', required: true, unique: true },
status: {
type: String,
enum: ['online', 'away', 'dnd', 'offline', 'invisible'],
default: 'offline'
},
statusMessage: { type: String },
lastHeartbeat: { type: Date, default: Date.now },
lastSeen: { type: Date, default: Date.now },
{
userId: { type: Schema.Types.ObjectId, ref: 'User', required: true, unique: true },
status: {
type: String,
enum: STATUS_ENUM,
default: 'offline',
},
{
timestamps: true,
toJSON: { virtuals: true },
toObject: { virtuals: true },
}
statusMessage: { type: String },
// Survives stale cleanup (which sets status to offline) so refresh can restore
// the user's chosen status + message.
preferredStatus: {
type: String,
enum: STATUS_ENUM,
},
preferredStatusMessage: { type: String },
lastHeartbeat: { type: Date, default: Date.now },
lastSeen: { type: Date, default: Date.now },
},
{
timestamps: true,
toJSON: { virtuals: true },
toObject: { virtuals: true },
}
);

// Indexes
PresenceSchema.index({ status: 1 });
PresenceSchema.index({ lastHeartbeat: 1 });

// Static method: findByUserId
PresenceSchema.statics.findByUserId = function (userId: string) {
return this.findOne({ userId });
};
function findByUserIdImpl(this: PresenceModel, userId: string) {
return this.findOne({ userId });
}

/**
* Refresh liveness only. Do not overwrite a user-chosen status/message.
* If stale cleanup marked the user offline, restore their preferred status.
*/
async function updateHeartbeatImpl(
this: PresenceModel,
userId: string
): Promise<PresenceDocument> {
const now = new Date();
const existing = await this.findOne({ userId });

// Static method: updateHeartbeat
PresenceSchema.statics.updateHeartbeat = async function (userId: string) {
if (!existing) {
return this.findOneAndUpdate(
{ userId },
{
lastHeartbeat: new Date(),
status: 'online'
{ userId },
{
$set: { lastHeartbeat: now, lastSeen: now },
$setOnInsert: {
status: 'online',
preferredStatus: 'online',
preferredStatusMessage: '',
},
{ upsert: true, new: true, setDefaultsOnInsert: true }
},
{ upsert: true, new: true, setDefaultsOnInsert: true }
);
};
}

existing.lastHeartbeat = now;
existing.lastSeen = now;

// Check if model already exists
const Presence = (mongoose.models.Presence as PresenceModel) || mongoose.model<PresenceDocument, PresenceModel>('Presence', PresenceSchema);
if (existing.status === 'offline') {
const preferred = existing.preferredStatus;
const restore =
preferred && preferred !== 'offline' ? (preferred as PresenceStatus) : 'online';
existing.status = restore;
if (typeof existing.preferredStatusMessage === 'string') {
existing.statusMessage = existing.preferredStatusMessage;
}
}

return existing.save();
}

PresenceSchema.statics.findByUserId = findByUserIdImpl;
PresenceSchema.statics.updateHeartbeat = updateHeartbeatImpl;

/**
* Re-bind every schema static onto the live model.
*
* Under ts-node-dev / hot reload, `mongoose.models.Presence` often already exists
* from a previous module evaluation. In that case `mongoose.model(...)` is skipped
* and schema.statics assigned above never replace the stale methods on the cached
* model. Binding here (for *all* statics, not just one) keeps call sites on the
* latest implementation when new statics are added later.
*/
function bindPresenceStatics(model: PresenceModel): PresenceModel {
model.findByUserId = findByUserIdImpl.bind(model);
model.updateHeartbeat = updateHeartbeatImpl.bind(model);
return model;
}

const Presence = bindPresenceStatics(
(mongoose.models.Presence as PresenceModel) ||
mongoose.model<PresenceDocument, PresenceModel>('Presence', PresenceSchema)
);

export default Presence;
Loading