Setup initial project
This commit is contained in:
commit
db79af06f7
119 changed files with 20761 additions and 0 deletions
40
packages/api/src/modules/health/health.routes.test.ts
Normal file
40
packages/api/src/modules/health/health.routes.test.ts
Normal file
|
|
@ -0,0 +1,40 @@
|
|||
import { describe, it, expect } from 'vitest';
|
||||
import Fastify from 'fastify';
|
||||
import { serializerCompiler, validatorCompiler } from 'fastify-type-provider-zod';
|
||||
import healthRoutes from './health.routes.js';
|
||||
|
||||
describe('Health Routes', () => {
|
||||
async function buildTestApp() {
|
||||
const app = Fastify({ logger: false });
|
||||
app.setValidatorCompiler(validatorCompiler);
|
||||
app.setSerializerCompiler(serializerCompiler);
|
||||
await app.register(healthRoutes);
|
||||
return app;
|
||||
}
|
||||
|
||||
it('GET /api/v1/health returns 200 with status ok', async () => {
|
||||
const app = await buildTestApp();
|
||||
|
||||
const response = await app.inject({
|
||||
method: 'GET',
|
||||
url: '/api/v1/health',
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(200);
|
||||
const body = response.json();
|
||||
expect(body).toMatchObject({
|
||||
status: 'ok',
|
||||
version: expect.any(String),
|
||||
uptime: expect.any(Number),
|
||||
});
|
||||
});
|
||||
|
||||
it('GET /api/v1/health returns increasing uptime', async () => {
|
||||
const app = await buildTestApp();
|
||||
|
||||
const first = await app.inject({ method: 'GET', url: '/api/v1/health' });
|
||||
const second = await app.inject({ method: 'GET', url: '/api/v1/health' });
|
||||
|
||||
expect(second.json().uptime).toBeGreaterThanOrEqual(first.json().uptime);
|
||||
});
|
||||
});
|
||||
34
packages/api/src/modules/health/health.routes.ts
Normal file
34
packages/api/src/modules/health/health.routes.ts
Normal file
|
|
@ -0,0 +1,34 @@
|
|||
import fp from 'fastify-plugin';
|
||||
import { z } from 'zod/v4';
|
||||
import type { ZodTypeProvider } from 'fastify-type-provider-zod';
|
||||
|
||||
const packageVersion = '0.0.1';
|
||||
|
||||
export default fp(
|
||||
async (fastify) => {
|
||||
const app = fastify.withTypeProvider<ZodTypeProvider>();
|
||||
|
||||
app.route({
|
||||
method: 'GET',
|
||||
url: '/api/v1/health',
|
||||
config: { public: true },
|
||||
schema: {
|
||||
response: {
|
||||
200: z.object({
|
||||
status: z.literal('ok'),
|
||||
version: z.string(),
|
||||
uptime: z.number(),
|
||||
}),
|
||||
},
|
||||
},
|
||||
handler: async (_request, reply) => {
|
||||
return reply.send({
|
||||
status: 'ok' as const,
|
||||
version: packageVersion,
|
||||
uptime: process.uptime(),
|
||||
});
|
||||
},
|
||||
});
|
||||
},
|
||||
{ name: 'health-routes' },
|
||||
);
|
||||
|
|
@ -0,0 +1,134 @@
|
|||
import { describe, it, expect, vi, beforeEach } from 'vitest';
|
||||
import { HouseholdRole } from '@meshitrack/shared';
|
||||
|
||||
const { _mockLean, mockExec, mockFindById, mockFindOne, mockFindByIdAndUpdate, mockSave } =
|
||||
vi.hoisted(() => {
|
||||
const mockExec = vi.fn();
|
||||
const mockLean = vi.fn(() => ({ exec: mockExec }));
|
||||
return {
|
||||
mockExec,
|
||||
mockLean,
|
||||
mockFindById: vi.fn(() => ({ lean: mockLean })),
|
||||
mockFindOne: vi.fn(() => ({ lean: mockLean })),
|
||||
mockFindByIdAndUpdate: vi.fn(() => ({ exec: mockExec })),
|
||||
mockSave: vi.fn(),
|
||||
};
|
||||
});
|
||||
|
||||
vi.mock('../../schemas/household.schema.js', () => {
|
||||
class MockHouseholdModel {
|
||||
_data: Record<string, unknown>;
|
||||
constructor(data: Record<string, unknown>) {
|
||||
this._data = data;
|
||||
Object.assign(this, data);
|
||||
}
|
||||
save() {
|
||||
mockSave();
|
||||
return Promise.resolve(this);
|
||||
}
|
||||
toObject() {
|
||||
return { _id: 'hh-new', ...this._data };
|
||||
}
|
||||
static findById = mockFindById;
|
||||
static findOne = mockFindOne;
|
||||
static findByIdAndUpdate = mockFindByIdAndUpdate;
|
||||
}
|
||||
return { HouseholdModel: MockHouseholdModel };
|
||||
});
|
||||
|
||||
import { HouseholdsRepository } from './households.repository.js';
|
||||
|
||||
describe('HouseholdsRepository', () => {
|
||||
let repo: HouseholdsRepository;
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
repo = new HouseholdsRepository();
|
||||
});
|
||||
|
||||
describe('findById', () => {
|
||||
it('calls findById with lean', async () => {
|
||||
const household = { _id: 'hh1', name: 'Test' };
|
||||
mockExec.mockResolvedValue(household);
|
||||
|
||||
const result = await repo.findById('hh1');
|
||||
|
||||
expect(mockFindById).toHaveBeenCalledWith('hh1');
|
||||
expect(result).toEqual(household);
|
||||
});
|
||||
});
|
||||
|
||||
describe('findByInviteCode', () => {
|
||||
it('calls findOne with inviteCode', async () => {
|
||||
const household = { _id: 'hh1', inviteCode: 'ABCD' };
|
||||
mockExec.mockResolvedValue(household);
|
||||
|
||||
const result = await repo.findByInviteCode('ABCD');
|
||||
|
||||
expect(mockFindOne).toHaveBeenCalledWith({ inviteCode: 'ABCD' });
|
||||
expect(result).toEqual(household);
|
||||
});
|
||||
});
|
||||
|
||||
describe('create', () => {
|
||||
it('creates a household with owner as first member', async () => {
|
||||
mockSave.mockResolvedValue({});
|
||||
|
||||
const result = await repo.create({ name: 'Test' }, 'owner-1', 'INVITE1');
|
||||
|
||||
expect(mockSave).toHaveBeenCalled();
|
||||
expect(result).toMatchObject({ name: 'Test', ownerUserId: 'owner-1', inviteCode: 'INVITE1' });
|
||||
});
|
||||
});
|
||||
|
||||
describe('update', () => {
|
||||
it('calls findByIdAndUpdate with $set', async () => {
|
||||
mockExec.mockResolvedValue({ _id: 'hh1', name: 'Updated' });
|
||||
|
||||
const result = await repo.update('hh1', { name: 'Updated' });
|
||||
|
||||
expect(mockFindByIdAndUpdate).toHaveBeenCalledWith(
|
||||
'hh1',
|
||||
{ $set: { name: 'Updated' } },
|
||||
{ new: true, lean: true },
|
||||
);
|
||||
expect(result).toEqual({ _id: 'hh1', name: 'Updated' });
|
||||
});
|
||||
});
|
||||
|
||||
describe('addMember', () => {
|
||||
it('pushes a new member to the array', async () => {
|
||||
mockExec.mockResolvedValue({ _id: 'hh1', members: [] });
|
||||
|
||||
await repo.addMember('hh1', 'user-2', HouseholdRole.MEMBER);
|
||||
|
||||
expect(mockFindByIdAndUpdate).toHaveBeenCalledWith(
|
||||
'hh1',
|
||||
{
|
||||
$push: {
|
||||
members: expect.objectContaining({
|
||||
userId: 'user-2',
|
||||
role: HouseholdRole.MEMBER,
|
||||
}),
|
||||
},
|
||||
},
|
||||
{ new: true, lean: true },
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe('updateInviteCode', () => {
|
||||
it('sets the new invite code', async () => {
|
||||
mockExec.mockResolvedValue({ _id: 'hh1', inviteCode: 'NEWCODE' });
|
||||
|
||||
const result = await repo.updateInviteCode('hh1', 'NEWCODE');
|
||||
|
||||
expect(mockFindByIdAndUpdate).toHaveBeenCalledWith(
|
||||
'hh1',
|
||||
{ $set: { inviteCode: 'NEWCODE' } },
|
||||
{ new: true, lean: true },
|
||||
);
|
||||
expect(result).toEqual({ _id: 'hh1', inviteCode: 'NEWCODE' });
|
||||
});
|
||||
});
|
||||
});
|
||||
55
packages/api/src/modules/households/households.repository.ts
Normal file
55
packages/api/src/modules/households/households.repository.ts
Normal file
|
|
@ -0,0 +1,55 @@
|
|||
import type mongoose from 'mongoose';
|
||||
import { HouseholdModel } from '../../schemas/household.schema.js';
|
||||
import type { CreateHouseholdInput, UpdateHouseholdInput } from '@meshitrack/shared';
|
||||
import { HouseholdRole } from '@meshitrack/shared';
|
||||
|
||||
export class HouseholdsRepository {
|
||||
public async findById(id: string) {
|
||||
return HouseholdModel.findById(id).lean().exec();
|
||||
}
|
||||
|
||||
public async findByInviteCode(inviteCode: string) {
|
||||
return HouseholdModel.findOne({ inviteCode }).lean().exec();
|
||||
}
|
||||
|
||||
public async create(
|
||||
data: CreateHouseholdInput,
|
||||
ownerUserId: string,
|
||||
inviteCode: string,
|
||||
session?: mongoose.ClientSession,
|
||||
) {
|
||||
const household = new HouseholdModel({
|
||||
...data,
|
||||
ownerUserId,
|
||||
inviteCode,
|
||||
members: [{ userId: ownerUserId, role: HouseholdRole.OWNER, joinedAt: new Date() }],
|
||||
});
|
||||
const saved = await household.save({ session });
|
||||
return saved.toObject();
|
||||
}
|
||||
|
||||
public async update(id: string, data: UpdateHouseholdInput) {
|
||||
return HouseholdModel.findByIdAndUpdate(id, { $set: data }, { new: true, lean: true }).exec();
|
||||
}
|
||||
|
||||
public async addMember(
|
||||
id: string,
|
||||
userId: string,
|
||||
role: HouseholdRole,
|
||||
session?: mongoose.ClientSession,
|
||||
) {
|
||||
return HouseholdModel.findByIdAndUpdate(
|
||||
id,
|
||||
{ $push: { members: { userId, role, joinedAt: new Date() } } },
|
||||
{ new: true, lean: true, session },
|
||||
).exec();
|
||||
}
|
||||
|
||||
public async updateInviteCode(id: string, inviteCode: string) {
|
||||
return HouseholdModel.findByIdAndUpdate(
|
||||
id,
|
||||
{ $set: { inviteCode } },
|
||||
{ new: true, lean: true },
|
||||
).exec();
|
||||
}
|
||||
}
|
||||
225
packages/api/src/modules/households/households.routes.test.ts
Normal file
225
packages/api/src/modules/households/households.routes.test.ts
Normal file
|
|
@ -0,0 +1,225 @@
|
|||
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
|
||||
import Fastify from 'fastify';
|
||||
import { fastifyAwilixPlugin } from '@fastify/awilix';
|
||||
import { serializerCompiler, validatorCompiler } from 'fastify-type-provider-zod';
|
||||
import { HouseholdRole } from '@meshitrack/shared';
|
||||
|
||||
// Mock jose for auth plugin
|
||||
vi.mock('jose', () => ({
|
||||
createRemoteJWKSet: vi.fn(() => 'mock-jwks'),
|
||||
jwtVerify: vi.fn().mockResolvedValue({
|
||||
payload: {
|
||||
sub: 'kc-1',
|
||||
email: 'test@example.com',
|
||||
preferred_username: 'testuser',
|
||||
realm_access: { roles: ['member'] },
|
||||
householdIds: ['hh1'],
|
||||
},
|
||||
protectedHeader: { alg: 'RS256' },
|
||||
key: {},
|
||||
}),
|
||||
}));
|
||||
|
||||
// Hoist mock fns
|
||||
const {
|
||||
mockCreate,
|
||||
mockFindById,
|
||||
mockUpdate,
|
||||
mockUpdateInviteCode,
|
||||
mockFindByInviteCode,
|
||||
mockAddMember,
|
||||
mockFindByKeycloakId,
|
||||
mockUserUpdate,
|
||||
} = vi.hoisted(() => ({
|
||||
mockCreate: vi.fn(),
|
||||
mockFindById: vi.fn(),
|
||||
mockUpdate: vi.fn(),
|
||||
mockUpdateInviteCode: vi.fn(),
|
||||
mockFindByInviteCode: vi.fn(),
|
||||
mockAddMember: vi.fn(),
|
||||
mockFindByKeycloakId: vi.fn(),
|
||||
mockUserUpdate: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock('./households.repository.js', () => ({
|
||||
HouseholdsRepository: class {
|
||||
create = mockCreate;
|
||||
findById = mockFindById;
|
||||
update = mockUpdate;
|
||||
updateInviteCode = mockUpdateInviteCode;
|
||||
findByInviteCode = mockFindByInviteCode;
|
||||
addMember = mockAddMember;
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock('../users/users.repository.js', () => ({
|
||||
UsersRepository: class {
|
||||
findByKeycloakId = mockFindByKeycloakId;
|
||||
update = mockUserUpdate;
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock('uuid', () => ({
|
||||
v4: vi.fn(() => '12345678-1234-1234-1234-123456789abc'),
|
||||
}));
|
||||
|
||||
vi.mock('mongoose', () => ({
|
||||
default: {
|
||||
startSession: vi.fn().mockResolvedValue({
|
||||
startTransaction: vi.fn(),
|
||||
commitTransaction: vi.fn().mockResolvedValue(undefined),
|
||||
abortTransaction: vi.fn().mockResolvedValue(undefined),
|
||||
endSession: vi.fn(),
|
||||
}),
|
||||
},
|
||||
}));
|
||||
|
||||
import authPlugin from '../../plugins/auth.plugin.js';
|
||||
import householdPlugin from '../../plugins/household.plugin.js';
|
||||
import usersRoutes from '../users/users.routes.js';
|
||||
import householdsRoutes from './households.routes.js';
|
||||
|
||||
function makeFakeHousehold(overrides = {}) {
|
||||
return {
|
||||
_id: 'hh1',
|
||||
name: 'Test Household',
|
||||
ownerUserId: 'kc-1',
|
||||
members: [{ userId: 'kc-1', role: HouseholdRole.OWNER, joinedAt: new Date().toISOString() }],
|
||||
inviteCode: '12345678',
|
||||
settings: { timezone: 'UTC', currency: 'USD', language: 'en' },
|
||||
createdAt: new Date().toISOString(),
|
||||
updatedAt: new Date().toISOString(),
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
describe('households.routes', () => {
|
||||
let app: Awaited<ReturnType<typeof buildTestApp>>;
|
||||
|
||||
async function buildTestApp() {
|
||||
const instance = Fastify({ logger: false });
|
||||
instance.setValidatorCompiler(validatorCompiler);
|
||||
instance.setSerializerCompiler(serializerCompiler);
|
||||
await instance.register(fastifyAwilixPlugin, {
|
||||
disposeOnClose: true,
|
||||
disposeOnResponse: true,
|
||||
strictBooleanEnforced: true,
|
||||
});
|
||||
await instance.register(authPlugin);
|
||||
await instance.register(householdPlugin);
|
||||
await instance.register(usersRoutes);
|
||||
await instance.register(householdsRoutes);
|
||||
await instance.ready();
|
||||
return instance;
|
||||
}
|
||||
|
||||
const authHeaders = { authorization: 'Bearer valid-token' };
|
||||
|
||||
beforeEach(async () => {
|
||||
vi.clearAllMocks();
|
||||
app = await buildTestApp();
|
||||
});
|
||||
|
||||
afterEach(async () => {
|
||||
if (app) await app.close();
|
||||
});
|
||||
|
||||
describe('POST /api/v1/households', () => {
|
||||
it('creates a household', async () => {
|
||||
const household = makeFakeHousehold();
|
||||
mockCreate.mockResolvedValue(household);
|
||||
mockFindByKeycloakId.mockResolvedValue({ householdIds: [], defaultHouseholdId: null });
|
||||
mockUserUpdate.mockResolvedValue({});
|
||||
|
||||
const res = await app.inject({
|
||||
method: 'POST',
|
||||
url: '/api/v1/households',
|
||||
headers: authHeaders,
|
||||
payload: { name: 'Test Household' },
|
||||
});
|
||||
|
||||
expect(res.statusCode).toBe(201);
|
||||
expect(res.json().name).toBe('Test Household');
|
||||
});
|
||||
});
|
||||
|
||||
describe('GET /api/v1/households/:id', () => {
|
||||
it('returns a household', async () => {
|
||||
const household = makeFakeHousehold();
|
||||
mockFindById.mockResolvedValue(household);
|
||||
|
||||
const res = await app.inject({
|
||||
method: 'GET',
|
||||
url: '/api/v1/households/hh1',
|
||||
headers: authHeaders,
|
||||
});
|
||||
|
||||
expect(res.statusCode).toBe(200);
|
||||
expect(res.json().name).toBe('Test Household');
|
||||
});
|
||||
});
|
||||
|
||||
describe('PATCH /api/v1/households/:id', () => {
|
||||
it('updates a household', async () => {
|
||||
const household = makeFakeHousehold();
|
||||
mockFindById.mockResolvedValue(household);
|
||||
mockUpdate.mockResolvedValue({ ...household, name: 'Updated' });
|
||||
|
||||
const res = await app.inject({
|
||||
method: 'PATCH',
|
||||
url: '/api/v1/households/hh1',
|
||||
headers: authHeaders,
|
||||
payload: { name: 'Updated' },
|
||||
});
|
||||
|
||||
expect(res.statusCode).toBe(200);
|
||||
expect(res.json().name).toBe('Updated');
|
||||
});
|
||||
});
|
||||
|
||||
describe('POST /api/v1/households/:id/invite', () => {
|
||||
it('generates a new invite code', async () => {
|
||||
const household = makeFakeHousehold();
|
||||
mockFindById.mockResolvedValue(household);
|
||||
mockUpdateInviteCode.mockResolvedValue({ ...household, inviteCode: '12345678' });
|
||||
|
||||
const res = await app.inject({
|
||||
method: 'POST',
|
||||
url: '/api/v1/households/hh1/invite',
|
||||
headers: authHeaders,
|
||||
});
|
||||
|
||||
expect(res.statusCode).toBe(200);
|
||||
expect(res.json().inviteCode).toBeDefined();
|
||||
});
|
||||
});
|
||||
|
||||
describe('POST /api/v1/households/join', () => {
|
||||
it('joins a household via invite code', async () => {
|
||||
const household = makeFakeHousehold({
|
||||
members: [
|
||||
{ userId: 'kc-other', role: HouseholdRole.OWNER, joinedAt: new Date().toISOString() },
|
||||
],
|
||||
});
|
||||
mockFindByInviteCode.mockResolvedValue(household);
|
||||
mockAddMember.mockResolvedValue({
|
||||
...household,
|
||||
members: [
|
||||
...household.members,
|
||||
{ userId: 'kc-1', role: HouseholdRole.MEMBER, joinedAt: new Date().toISOString() },
|
||||
],
|
||||
});
|
||||
mockFindByKeycloakId.mockResolvedValue({ householdIds: [], defaultHouseholdId: null });
|
||||
mockUserUpdate.mockResolvedValue({});
|
||||
|
||||
const res = await app.inject({
|
||||
method: 'POST',
|
||||
url: '/api/v1/households/join',
|
||||
headers: authHeaders,
|
||||
payload: { inviteCode: '12345678' },
|
||||
});
|
||||
|
||||
expect(res.statusCode).toBe(200);
|
||||
});
|
||||
});
|
||||
});
|
||||
166
packages/api/src/modules/households/households.routes.ts
Normal file
166
packages/api/src/modules/households/households.routes.ts
Normal file
|
|
@ -0,0 +1,166 @@
|
|||
import fp from 'fastify-plugin';
|
||||
import { asClass, Lifetime } from 'awilix';
|
||||
import type { ZodTypeProvider } from 'fastify-type-provider-zod';
|
||||
import { z } from 'zod/v4';
|
||||
import {
|
||||
CreateHouseholdSchema,
|
||||
UpdateHouseholdSchema,
|
||||
JoinHouseholdSchema,
|
||||
HouseholdResponseSchema,
|
||||
} from '@meshitrack/shared';
|
||||
|
||||
type AnyHouseholdDoc = {
|
||||
_id: string | { toString: () => string };
|
||||
name: string;
|
||||
ownerUserId: string;
|
||||
members: ReadonlyArray<{
|
||||
userId: string;
|
||||
role: string;
|
||||
joinedAt: string | { toISOString: () => string };
|
||||
}>;
|
||||
inviteCode: string;
|
||||
settings?: { timezone?: string; currency?: string; language?: string } | null;
|
||||
createdAt: string | { toISOString: () => string };
|
||||
updatedAt: string | { toISOString: () => string };
|
||||
};
|
||||
|
||||
function toStr(v: string | { toString: () => string }): string {
|
||||
return typeof v === 'string' ? v : v.toString();
|
||||
}
|
||||
|
||||
function toIso(v: string | { toISOString: () => string }): string {
|
||||
return typeof v === 'string' ? v : v.toISOString();
|
||||
}
|
||||
|
||||
function toHouseholdResponse(doc: AnyHouseholdDoc): z.infer<typeof HouseholdResponseSchema> {
|
||||
return {
|
||||
_id: toStr(doc._id),
|
||||
name: doc.name,
|
||||
ownerUserId: doc.ownerUserId,
|
||||
members: doc.members.map((m) => ({
|
||||
userId: m.userId,
|
||||
role: m.role,
|
||||
joinedAt: toIso(m.joinedAt),
|
||||
})),
|
||||
inviteCode: doc.inviteCode,
|
||||
settings: {
|
||||
timezone: doc.settings?.timezone ?? 'UTC',
|
||||
currency: doc.settings?.currency ?? 'USD',
|
||||
language: doc.settings?.language ?? 'en',
|
||||
},
|
||||
createdAt: toIso(doc.createdAt),
|
||||
updatedAt: toIso(doc.updatedAt),
|
||||
};
|
||||
}
|
||||
import { HouseholdsRepository } from './households.repository.js';
|
||||
import { HouseholdsService } from './households.service.js';
|
||||
|
||||
declare module '@fastify/awilix' {
|
||||
interface Cradle {
|
||||
householdsRepository: HouseholdsRepository;
|
||||
householdsService: HouseholdsService;
|
||||
}
|
||||
}
|
||||
|
||||
export default fp(
|
||||
async (fastify) => {
|
||||
// Register DI
|
||||
fastify.diContainer.register({
|
||||
householdsRepository: asClass(HouseholdsRepository, { lifetime: Lifetime.SINGLETON }),
|
||||
householdsService: asClass(HouseholdsService, { lifetime: Lifetime.SINGLETON }),
|
||||
});
|
||||
|
||||
const app = fastify.withTypeProvider<ZodTypeProvider>();
|
||||
|
||||
// POST /api/v1/households — create a new household
|
||||
app.route({
|
||||
method: 'POST',
|
||||
url: '/api/v1/households',
|
||||
config: { skipHousehold: true },
|
||||
schema: {
|
||||
body: CreateHouseholdSchema,
|
||||
response: { 201: HouseholdResponseSchema },
|
||||
},
|
||||
handler: async (request, reply) => {
|
||||
const service = fastify.diContainer.resolve('householdsService');
|
||||
const household = await service.create(request.body, request.user.keycloakId);
|
||||
return reply.status(201).send(toHouseholdResponse(household));
|
||||
},
|
||||
});
|
||||
|
||||
// GET /api/v1/households/:householdId — get household by id (members only)
|
||||
app.route({
|
||||
method: 'GET',
|
||||
url: '/api/v1/households/:householdId',
|
||||
schema: {
|
||||
params: z.object({ householdId: z.string() }),
|
||||
response: { 200: HouseholdResponseSchema },
|
||||
},
|
||||
handler: async (request, reply) => {
|
||||
const service = fastify.diContainer.resolve('householdsService');
|
||||
const household = await service.getById(request.params.householdId);
|
||||
return reply.send(toHouseholdResponse(household));
|
||||
},
|
||||
});
|
||||
|
||||
// PATCH /api/v1/households/:householdId — update household settings
|
||||
app.route({
|
||||
method: 'PATCH',
|
||||
url: '/api/v1/households/:householdId',
|
||||
schema: {
|
||||
params: z.object({ householdId: z.string() }),
|
||||
body: UpdateHouseholdSchema,
|
||||
response: { 200: HouseholdResponseSchema },
|
||||
},
|
||||
handler: async (request, reply) => {
|
||||
const service = fastify.diContainer.resolve('householdsService');
|
||||
const household = await service.update(
|
||||
request.params.householdId,
|
||||
request.body,
|
||||
request.user.keycloakId,
|
||||
);
|
||||
return reply.send(toHouseholdResponse(household));
|
||||
},
|
||||
});
|
||||
|
||||
// POST /api/v1/households/:householdId/invite — generate new invite code
|
||||
app.route({
|
||||
method: 'POST',
|
||||
url: '/api/v1/households/:householdId/invite',
|
||||
schema: {
|
||||
params: z.object({ householdId: z.string() }),
|
||||
response: { 200: HouseholdResponseSchema },
|
||||
},
|
||||
handler: async (request, reply) => {
|
||||
const service = fastify.diContainer.resolve('householdsService');
|
||||
const household = await service.generateInviteCode(
|
||||
request.params.householdId,
|
||||
request.user.keycloakId,
|
||||
);
|
||||
return reply.send(toHouseholdResponse(household));
|
||||
},
|
||||
});
|
||||
|
||||
// POST /api/v1/households/join — join via invite code
|
||||
app.route({
|
||||
method: 'POST',
|
||||
url: '/api/v1/households/join',
|
||||
config: { skipHousehold: true },
|
||||
schema: {
|
||||
body: JoinHouseholdSchema,
|
||||
response: { 200: HouseholdResponseSchema },
|
||||
},
|
||||
handler: async (request, reply) => {
|
||||
const service = fastify.diContainer.resolve('householdsService');
|
||||
const household = await service.join(request.body.inviteCode, request.user.keycloakId);
|
||||
return reply.send(toHouseholdResponse(household));
|
||||
},
|
||||
});
|
||||
},
|
||||
{
|
||||
name: 'households-routes',
|
||||
// users-routes must load first: it registers UsersRepository into the DI container,
|
||||
// which HouseholdsService depends on.
|
||||
dependencies: ['auth-plugin', 'users-routes'],
|
||||
},
|
||||
);
|
||||
253
packages/api/src/modules/households/households.service.test.ts
Normal file
253
packages/api/src/modules/households/households.service.test.ts
Normal file
|
|
@ -0,0 +1,253 @@
|
|||
import { describe, it, expect, vi, beforeEach } from 'vitest';
|
||||
import { HouseholdsService } from './households.service.js';
|
||||
import { NotFoundError, ForbiddenError, ConflictError } from '../../common/errors.js';
|
||||
import { HouseholdRole } from '@meshitrack/shared';
|
||||
|
||||
// Mock uuid to return deterministic values
|
||||
vi.mock('uuid', () => ({
|
||||
v4: vi.fn(() => '12345678-1234-1234-1234-123456789abc'),
|
||||
}));
|
||||
|
||||
const { mockSession } = vi.hoisted(() => ({
|
||||
mockSession: {
|
||||
startTransaction: vi.fn(),
|
||||
commitTransaction: vi.fn().mockResolvedValue(undefined),
|
||||
abortTransaction: vi.fn().mockResolvedValue(undefined),
|
||||
endSession: vi.fn(),
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock('mongoose', () => ({
|
||||
default: { startSession: vi.fn().mockResolvedValue(mockSession) },
|
||||
}));
|
||||
|
||||
describe('HouseholdsService', () => {
|
||||
const mockHouseholdsRepo = {
|
||||
findById: vi.fn(),
|
||||
findByInviteCode: vi.fn(),
|
||||
create: vi.fn(),
|
||||
update: vi.fn(),
|
||||
addMember: vi.fn(),
|
||||
updateInviteCode: vi.fn(),
|
||||
};
|
||||
|
||||
const mockUsersRepo = {
|
||||
findByKeycloakId: vi.fn(),
|
||||
findById: vi.fn(),
|
||||
create: vi.fn(),
|
||||
update: vi.fn(),
|
||||
upsertFromToken: vi.fn(),
|
||||
};
|
||||
|
||||
let service: HouseholdsService;
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
service = new HouseholdsService({
|
||||
householdsRepository: mockHouseholdsRepo as never,
|
||||
usersRepository: mockUsersRepo as never,
|
||||
});
|
||||
});
|
||||
|
||||
describe('create', () => {
|
||||
it('creates a household and updates owner user', async () => {
|
||||
const household = { _id: 'hh1', name: 'Test', ownerUserId: 'kc-1', inviteCode: '12345678' };
|
||||
mockHouseholdsRepo.create.mockResolvedValue(household);
|
||||
mockUsersRepo.findByKeycloakId.mockResolvedValue({
|
||||
householdIds: [],
|
||||
defaultHouseholdId: null,
|
||||
});
|
||||
mockUsersRepo.update.mockResolvedValue({});
|
||||
|
||||
const result = await service.create({ name: 'Test' }, 'kc-1');
|
||||
|
||||
expect(result).toEqual(household);
|
||||
expect(mockHouseholdsRepo.create).toHaveBeenCalledWith(
|
||||
{ name: 'Test' },
|
||||
'kc-1',
|
||||
'12345678',
|
||||
mockSession,
|
||||
);
|
||||
expect(mockUsersRepo.update).toHaveBeenCalledWith(
|
||||
'kc-1',
|
||||
{ householdIds: ['hh1'], defaultHouseholdId: 'hh1' },
|
||||
mockSession,
|
||||
);
|
||||
});
|
||||
|
||||
it('preserves existing defaultHouseholdId when user already has one', async () => {
|
||||
const household = { _id: 'hh2', name: 'Second', ownerUserId: 'kc-1' };
|
||||
mockHouseholdsRepo.create.mockResolvedValue(household);
|
||||
mockUsersRepo.findByKeycloakId.mockResolvedValue({
|
||||
householdIds: ['hh1'],
|
||||
defaultHouseholdId: 'hh1',
|
||||
});
|
||||
mockUsersRepo.update.mockResolvedValue({});
|
||||
|
||||
await service.create({ name: 'Second' }, 'kc-1');
|
||||
|
||||
expect(mockUsersRepo.update).toHaveBeenCalledWith(
|
||||
'kc-1',
|
||||
{ householdIds: ['hh1', 'hh2'], defaultHouseholdId: 'hh1' },
|
||||
mockSession,
|
||||
);
|
||||
});
|
||||
|
||||
it('handles case when owner user not found in db', async () => {
|
||||
const household = { _id: 'hh1', name: 'Test', ownerUserId: 'kc-1' };
|
||||
mockHouseholdsRepo.create.mockResolvedValue(household);
|
||||
mockUsersRepo.findByKeycloakId.mockResolvedValue(null);
|
||||
|
||||
const result = await service.create({ name: 'Test' }, 'kc-1');
|
||||
|
||||
expect(result).toEqual(household);
|
||||
expect(mockUsersRepo.update).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe('getById', () => {
|
||||
it('returns household when found', async () => {
|
||||
const household = { _id: 'hh1', name: 'Test' };
|
||||
mockHouseholdsRepo.findById.mockResolvedValue(household);
|
||||
|
||||
const result = await service.getById('hh1');
|
||||
expect(result).toEqual(household);
|
||||
});
|
||||
|
||||
it('throws NotFoundError when not found', async () => {
|
||||
mockHouseholdsRepo.findById.mockResolvedValue(null);
|
||||
|
||||
await expect(service.getById('missing')).rejects.toThrow(NotFoundError);
|
||||
});
|
||||
});
|
||||
|
||||
describe('update', () => {
|
||||
it('allows owner to update', async () => {
|
||||
mockHouseholdsRepo.findById.mockResolvedValue({
|
||||
_id: 'hh1',
|
||||
members: [{ userId: 'kc-1', role: HouseholdRole.OWNER }],
|
||||
});
|
||||
mockHouseholdsRepo.update.mockResolvedValue({ _id: 'hh1', name: 'Updated' });
|
||||
|
||||
const result = await service.update('hh1', { name: 'Updated' }, 'kc-1');
|
||||
expect(result).toEqual({ _id: 'hh1', name: 'Updated' });
|
||||
});
|
||||
|
||||
it('allows admin to update', async () => {
|
||||
mockHouseholdsRepo.findById.mockResolvedValue({
|
||||
_id: 'hh1',
|
||||
members: [{ userId: 'kc-2', role: HouseholdRole.ADMIN }],
|
||||
});
|
||||
mockHouseholdsRepo.update.mockResolvedValue({ _id: 'hh1', name: 'Updated' });
|
||||
|
||||
await service.update('hh1', { name: 'Updated' }, 'kc-2');
|
||||
expect(mockHouseholdsRepo.update).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('throws ForbiddenError for regular member', async () => {
|
||||
mockHouseholdsRepo.findById.mockResolvedValue({
|
||||
_id: 'hh1',
|
||||
members: [{ userId: 'kc-3', role: HouseholdRole.MEMBER }],
|
||||
});
|
||||
|
||||
await expect(service.update('hh1', { name: 'X' }, 'kc-3')).rejects.toThrow(ForbiddenError);
|
||||
});
|
||||
|
||||
it('throws ForbiddenError for non-member', async () => {
|
||||
mockHouseholdsRepo.findById.mockResolvedValue({
|
||||
_id: 'hh1',
|
||||
members: [{ userId: 'kc-1', role: HouseholdRole.OWNER }],
|
||||
});
|
||||
|
||||
await expect(service.update('hh1', { name: 'X' }, 'kc-other')).rejects.toThrow(
|
||||
ForbiddenError,
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe('generateInviteCode', () => {
|
||||
it('generates new invite code for owner', async () => {
|
||||
mockHouseholdsRepo.findById.mockResolvedValue({
|
||||
_id: 'hh1',
|
||||
members: [{ userId: 'kc-1', role: HouseholdRole.OWNER }],
|
||||
});
|
||||
mockHouseholdsRepo.updateInviteCode.mockResolvedValue({ inviteCode: '12345678' });
|
||||
|
||||
const result = await service.generateInviteCode('hh1', 'kc-1');
|
||||
expect(mockHouseholdsRepo.updateInviteCode).toHaveBeenCalledWith('hh1', '12345678');
|
||||
expect(result).toEqual({ inviteCode: '12345678' });
|
||||
});
|
||||
|
||||
it('throws ForbiddenError for regular member', async () => {
|
||||
mockHouseholdsRepo.findById.mockResolvedValue({
|
||||
_id: 'hh1',
|
||||
members: [{ userId: 'kc-3', role: HouseholdRole.MEMBER }],
|
||||
});
|
||||
|
||||
await expect(service.generateInviteCode('hh1', 'kc-3')).rejects.toThrow(ForbiddenError);
|
||||
});
|
||||
});
|
||||
|
||||
describe('join', () => {
|
||||
it('joins a household via invite code', async () => {
|
||||
const household = {
|
||||
_id: 'hh1',
|
||||
members: [{ userId: 'kc-1', role: HouseholdRole.OWNER }],
|
||||
};
|
||||
mockHouseholdsRepo.findByInviteCode.mockResolvedValue(household);
|
||||
mockHouseholdsRepo.addMember.mockResolvedValue({
|
||||
...household,
|
||||
members: [...household.members, { userId: 'kc-2' }],
|
||||
});
|
||||
mockUsersRepo.findByKeycloakId.mockResolvedValue({
|
||||
householdIds: [],
|
||||
defaultHouseholdId: null,
|
||||
});
|
||||
mockUsersRepo.update.mockResolvedValue({});
|
||||
|
||||
const result = await service.join('ABCD1234', 'kc-2');
|
||||
|
||||
expect(mockHouseholdsRepo.addMember).toHaveBeenCalledWith(
|
||||
'hh1',
|
||||
'kc-2',
|
||||
HouseholdRole.MEMBER,
|
||||
mockSession,
|
||||
);
|
||||
expect(mockUsersRepo.update).toHaveBeenCalledWith(
|
||||
'kc-2',
|
||||
{ householdIds: ['hh1'], defaultHouseholdId: 'hh1' },
|
||||
mockSession,
|
||||
);
|
||||
expect(result).toBeDefined();
|
||||
});
|
||||
|
||||
it('throws NotFoundError for invalid invite code', async () => {
|
||||
mockHouseholdsRepo.findByInviteCode.mockResolvedValue(null);
|
||||
|
||||
await expect(service.join('INVALID', 'kc-2')).rejects.toThrow(NotFoundError);
|
||||
});
|
||||
|
||||
it('throws ConflictError when already a member', async () => {
|
||||
mockHouseholdsRepo.findByInviteCode.mockResolvedValue({
|
||||
_id: 'hh1',
|
||||
members: [{ userId: 'kc-1', role: HouseholdRole.OWNER }],
|
||||
});
|
||||
|
||||
await expect(service.join('CODE', 'kc-1')).rejects.toThrow(ConflictError);
|
||||
});
|
||||
|
||||
it('handles case when joining user not found in db', async () => {
|
||||
const household = {
|
||||
_id: 'hh1',
|
||||
members: [{ userId: 'kc-1', role: HouseholdRole.OWNER }],
|
||||
};
|
||||
mockHouseholdsRepo.findByInviteCode.mockResolvedValue(household);
|
||||
mockHouseholdsRepo.addMember.mockResolvedValue({});
|
||||
mockUsersRepo.findByKeycloakId.mockResolvedValue(null);
|
||||
|
||||
await service.join('CODE', 'kc-new');
|
||||
|
||||
expect(mockUsersRepo.update).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
});
|
||||
135
packages/api/src/modules/households/households.service.ts
Normal file
135
packages/api/src/modules/households/households.service.ts
Normal file
|
|
@ -0,0 +1,135 @@
|
|||
import mongoose from 'mongoose';
|
||||
import { v4 as uuidv4 } from 'uuid';
|
||||
import type { HouseholdsRepository } from './households.repository.js';
|
||||
import type { UsersRepository } from '../users/users.repository.js';
|
||||
import type { CreateHouseholdInput, UpdateHouseholdInput } from '@meshitrack/shared';
|
||||
import { HouseholdRole } from '@meshitrack/shared';
|
||||
import { NotFoundError, ForbiddenError, ConflictError } from '../../common/errors.js';
|
||||
|
||||
interface Deps {
|
||||
householdsRepository: HouseholdsRepository;
|
||||
usersRepository: UsersRepository;
|
||||
}
|
||||
|
||||
export class HouseholdsService {
|
||||
private readonly householdsRepository: HouseholdsRepository;
|
||||
private readonly usersRepository: UsersRepository;
|
||||
|
||||
public constructor({ householdsRepository, usersRepository }: Deps) {
|
||||
this.householdsRepository = householdsRepository;
|
||||
this.usersRepository = usersRepository;
|
||||
}
|
||||
|
||||
public async create(data: CreateHouseholdInput, ownerKeycloakId: string) {
|
||||
const inviteCode = uuidv4().slice(0, 8).toUpperCase();
|
||||
const session = await mongoose.startSession();
|
||||
try {
|
||||
session.startTransaction();
|
||||
|
||||
const household = await this.householdsRepository.create(
|
||||
data,
|
||||
ownerKeycloakId,
|
||||
inviteCode,
|
||||
session,
|
||||
);
|
||||
|
||||
const user = await this.usersRepository.findByKeycloakId(ownerKeycloakId, session);
|
||||
if (user) {
|
||||
const householdId = household._id.toString();
|
||||
await this.usersRepository.update(
|
||||
ownerKeycloakId,
|
||||
{
|
||||
householdIds: [...user.householdIds, householdId],
|
||||
defaultHouseholdId: user.defaultHouseholdId ?? householdId,
|
||||
},
|
||||
session,
|
||||
);
|
||||
}
|
||||
|
||||
await session.commitTransaction();
|
||||
return household;
|
||||
} catch (err) {
|
||||
await session.abortTransaction();
|
||||
throw err;
|
||||
} finally {
|
||||
session.endSession();
|
||||
}
|
||||
}
|
||||
|
||||
public async getById(id: string) {
|
||||
const household = await this.householdsRepository.findById(id);
|
||||
if (!household) {
|
||||
throw new NotFoundError('Household not found');
|
||||
}
|
||||
return household;
|
||||
}
|
||||
|
||||
public async update(id: string, data: UpdateHouseholdInput, requestingUserId: string) {
|
||||
const household = await this.getById(id);
|
||||
const member = household.members.find((m) => m.userId === requestingUserId);
|
||||
if (!member || (member.role !== HouseholdRole.OWNER && member.role !== HouseholdRole.ADMIN)) {
|
||||
throw new ForbiddenError('Only owners and admins can update household settings');
|
||||
}
|
||||
const updated = await this.householdsRepository.update(id, data);
|
||||
if (!updated) throw new NotFoundError('Household not found');
|
||||
return updated;
|
||||
}
|
||||
|
||||
public async generateInviteCode(id: string, requestingUserId: string) {
|
||||
const household = await this.getById(id);
|
||||
const member = household.members.find((m) => m.userId === requestingUserId);
|
||||
if (!member || (member.role !== HouseholdRole.OWNER && member.role !== HouseholdRole.ADMIN)) {
|
||||
throw new ForbiddenError('Only owners and admins can generate invite codes');
|
||||
}
|
||||
const newCode = uuidv4().slice(0, 8).toUpperCase();
|
||||
const updated = await this.householdsRepository.updateInviteCode(id, newCode);
|
||||
if (!updated) throw new NotFoundError('Household not found');
|
||||
return updated;
|
||||
}
|
||||
|
||||
public async join(inviteCode: string, userId: string) {
|
||||
const household = await this.householdsRepository.findByInviteCode(inviteCode);
|
||||
if (!household) {
|
||||
throw new NotFoundError('Invalid invite code');
|
||||
}
|
||||
|
||||
const alreadyMember = household.members.some((m) => m.userId === userId);
|
||||
if (alreadyMember) {
|
||||
throw new ConflictError('Already a member of this household');
|
||||
}
|
||||
|
||||
const session = await mongoose.startSession();
|
||||
try {
|
||||
session.startTransaction();
|
||||
|
||||
const updated = await this.householdsRepository.addMember(
|
||||
household._id.toString(),
|
||||
userId,
|
||||
HouseholdRole.MEMBER,
|
||||
session,
|
||||
);
|
||||
if (!updated) throw new NotFoundError('Household not found');
|
||||
|
||||
const user = await this.usersRepository.findByKeycloakId(userId, session);
|
||||
if (user) {
|
||||
const householdId = household._id.toString();
|
||||
await this.usersRepository.update(
|
||||
userId,
|
||||
{
|
||||
householdIds: [...user.householdIds, householdId],
|
||||
defaultHouseholdId: user.defaultHouseholdId ?? householdId,
|
||||
},
|
||||
session,
|
||||
);
|
||||
}
|
||||
|
||||
await session.commitTransaction();
|
||||
return updated;
|
||||
} catch (err) {
|
||||
await session.abortTransaction();
|
||||
throw err;
|
||||
} finally {
|
||||
session.endSession();
|
||||
}
|
||||
}
|
||||
}
|
||||
128
packages/api/src/modules/users/users.repository.test.ts
Normal file
128
packages/api/src/modules/users/users.repository.test.ts
Normal file
|
|
@ -0,0 +1,128 @@
|
|||
import { describe, it, expect, vi, beforeEach } from 'vitest';
|
||||
|
||||
// Use vi.hoisted so mocks are available in vi.mock factory (which is hoisted)
|
||||
const { mockLean, mockExec, mockFindOne, mockFindById, mockFindOneAndUpdate, mockSave } =
|
||||
vi.hoisted(() => {
|
||||
const mockExec = vi.fn();
|
||||
const mockLean = vi.fn(() => ({ exec: mockExec }));
|
||||
return {
|
||||
mockExec,
|
||||
mockLean,
|
||||
mockFindOne: vi.fn(() => ({ lean: mockLean })),
|
||||
mockFindById: vi.fn(() => ({ lean: mockLean })),
|
||||
mockFindOneAndUpdate: vi.fn(() => ({ exec: mockExec })),
|
||||
mockSave: vi.fn(),
|
||||
};
|
||||
});
|
||||
|
||||
vi.mock('../../schemas/user.schema.js', () => {
|
||||
class MockUserModel {
|
||||
_data: Record<string, unknown>;
|
||||
constructor(data: Record<string, unknown>) {
|
||||
this._data = data;
|
||||
Object.assign(this, data);
|
||||
}
|
||||
save() {
|
||||
mockSave();
|
||||
return Promise.resolve(this);
|
||||
}
|
||||
toObject() {
|
||||
return { _id: 'new-id', ...this._data };
|
||||
}
|
||||
static findOne = mockFindOne;
|
||||
static findById = mockFindById;
|
||||
static findOneAndUpdate = mockFindOneAndUpdate;
|
||||
}
|
||||
return { UserModel: MockUserModel };
|
||||
});
|
||||
|
||||
import { UsersRepository } from './users.repository.js';
|
||||
|
||||
describe('UsersRepository', () => {
|
||||
let repo: UsersRepository;
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
repo = new UsersRepository();
|
||||
});
|
||||
|
||||
describe('findByKeycloakId', () => {
|
||||
it('calls findOne with keycloakId and returns lean result', async () => {
|
||||
const user = { _id: 'u1', keycloakId: 'kc-1' };
|
||||
mockExec.mockResolvedValue(user);
|
||||
|
||||
const result = await repo.findByKeycloakId('kc-1');
|
||||
|
||||
expect(mockFindOne).toHaveBeenCalledWith({ keycloakId: 'kc-1' }, null, {
|
||||
session: undefined,
|
||||
});
|
||||
expect(mockLean).toHaveBeenCalled();
|
||||
expect(mockExec).toHaveBeenCalled();
|
||||
expect(result).toEqual(user);
|
||||
});
|
||||
});
|
||||
|
||||
describe('findById', () => {
|
||||
it('calls findById and returns lean result', async () => {
|
||||
const user = { _id: 'u1' };
|
||||
mockExec.mockResolvedValue(user);
|
||||
|
||||
const result = await repo.findById('u1');
|
||||
|
||||
expect(mockFindById).toHaveBeenCalledWith('u1');
|
||||
expect(result).toEqual(user);
|
||||
});
|
||||
});
|
||||
|
||||
describe('create', () => {
|
||||
it('creates a new user and returns plain object', async () => {
|
||||
mockSave.mockResolvedValue({});
|
||||
|
||||
const data = {
|
||||
keycloakId: 'kc-1',
|
||||
email: 'test@example.com',
|
||||
displayName: 'Test',
|
||||
householdIds: [],
|
||||
};
|
||||
const result = await repo.create(data as never);
|
||||
|
||||
expect(mockSave).toHaveBeenCalled();
|
||||
expect(result).toMatchObject({ keycloakId: 'kc-1' });
|
||||
});
|
||||
});
|
||||
|
||||
describe('update', () => {
|
||||
it('calls findOneAndUpdate with $set', async () => {
|
||||
const updated = { _id: 'u1', displayName: 'Updated' };
|
||||
mockExec.mockResolvedValue(updated);
|
||||
|
||||
const result = await repo.update('kc-1', { displayName: 'Updated' } as never);
|
||||
|
||||
expect(mockFindOneAndUpdate).toHaveBeenCalledWith(
|
||||
{ keycloakId: 'kc-1' },
|
||||
{ $set: { displayName: 'Updated' } },
|
||||
{ new: true, lean: true, session: undefined },
|
||||
);
|
||||
expect(result).toEqual(updated);
|
||||
});
|
||||
});
|
||||
|
||||
describe('upsertFromToken', () => {
|
||||
it('upserts user with $set and $setOnInsert', async () => {
|
||||
const upserted = { _id: 'u1', keycloakId: 'kc-1' };
|
||||
mockExec.mockResolvedValue(upserted);
|
||||
|
||||
const result = await repo.upsertFromToken('kc-1', 'a@b.com', 'Name');
|
||||
|
||||
expect(mockFindOneAndUpdate).toHaveBeenCalledWith(
|
||||
{ keycloakId: 'kc-1' },
|
||||
{
|
||||
$set: { email: 'a@b.com', displayName: 'Name' },
|
||||
$setOnInsert: { keycloakId: 'kc-1', householdIds: [], defaultHouseholdId: null },
|
||||
},
|
||||
{ upsert: true, new: true, lean: true },
|
||||
);
|
||||
expect(result).toEqual(upserted);
|
||||
});
|
||||
});
|
||||
});
|
||||
38
packages/api/src/modules/users/users.repository.ts
Normal file
38
packages/api/src/modules/users/users.repository.ts
Normal file
|
|
@ -0,0 +1,38 @@
|
|||
import type mongoose from 'mongoose';
|
||||
import { UserModel } from '../../schemas/user.schema.js';
|
||||
import type { CreateUserInput, UpdateUserInput } from '@meshitrack/shared';
|
||||
|
||||
export class UsersRepository {
|
||||
public async findByKeycloakId(keycloakId: string, session?: mongoose.ClientSession) {
|
||||
return UserModel.findOne({ keycloakId }, null, { session }).lean().exec();
|
||||
}
|
||||
|
||||
public async findById(id: string) {
|
||||
return UserModel.findById(id).lean().exec();
|
||||
}
|
||||
|
||||
public async create(data: CreateUserInput) {
|
||||
const user = new UserModel(data);
|
||||
const saved = await user.save();
|
||||
return saved.toObject();
|
||||
}
|
||||
|
||||
public async update(keycloakId: string, data: UpdateUserInput, session?: mongoose.ClientSession) {
|
||||
return UserModel.findOneAndUpdate(
|
||||
{ keycloakId },
|
||||
{ $set: data },
|
||||
{ new: true, lean: true, session },
|
||||
).exec();
|
||||
}
|
||||
|
||||
public async upsertFromToken(keycloakId: string, email: string, displayName: string) {
|
||||
return UserModel.findOneAndUpdate(
|
||||
{ keycloakId },
|
||||
{
|
||||
$set: { email, displayName },
|
||||
$setOnInsert: { keycloakId, householdIds: [], defaultHouseholdId: null },
|
||||
},
|
||||
{ upsert: true, new: true, lean: true },
|
||||
).exec();
|
||||
}
|
||||
}
|
||||
82
packages/api/src/modules/users/users.routes.test.ts
Normal file
82
packages/api/src/modules/users/users.routes.test.ts
Normal file
|
|
@ -0,0 +1,82 @@
|
|||
import { describe, it, expect, vi, beforeEach } from 'vitest';
|
||||
import Fastify from 'fastify';
|
||||
import { fastifyAwilixPlugin } from '@fastify/awilix';
|
||||
import { serializerCompiler, validatorCompiler } from 'fastify-type-provider-zod';
|
||||
|
||||
// Mock jose for auth plugin
|
||||
vi.mock('jose', () => ({
|
||||
createRemoteJWKSet: vi.fn(() => 'mock-jwks'),
|
||||
jwtVerify: vi.fn().mockResolvedValue({
|
||||
payload: {
|
||||
sub: 'kc-1',
|
||||
email: 'test@example.com',
|
||||
preferred_username: 'testuser',
|
||||
realm_access: { roles: ['member'] },
|
||||
householdIds: ['hh1'],
|
||||
},
|
||||
protectedHeader: { alg: 'RS256' },
|
||||
key: {},
|
||||
}),
|
||||
}));
|
||||
|
||||
// Mock the users repository module with a real class
|
||||
const mockUpsertFromToken = vi.hoisted(() => vi.fn());
|
||||
vi.mock('./users.repository.js', () => ({
|
||||
UsersRepository: class MockUsersRepository {
|
||||
upsertFromToken = mockUpsertFromToken;
|
||||
},
|
||||
}));
|
||||
|
||||
import authPlugin from '../../plugins/auth.plugin.js';
|
||||
import usersRoutes from './users.routes.js';
|
||||
|
||||
describe('users.routes', () => {
|
||||
async function buildTestApp() {
|
||||
const app = Fastify({ logger: false });
|
||||
app.setValidatorCompiler(validatorCompiler);
|
||||
app.setSerializerCompiler(serializerCompiler);
|
||||
await app.register(fastifyAwilixPlugin, {
|
||||
disposeOnClose: true,
|
||||
disposeOnResponse: true,
|
||||
strictBooleanEnforced: true,
|
||||
});
|
||||
await app.register(authPlugin);
|
||||
await app.register(usersRoutes);
|
||||
return app;
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
it('GET /api/v1/users/me syncs user from token and returns profile', async () => {
|
||||
const mockUser = {
|
||||
_id: 'u1',
|
||||
keycloakId: 'kc-1',
|
||||
displayName: 'testuser',
|
||||
email: 'test@example.com',
|
||||
householdIds: ['hh1'],
|
||||
defaultHouseholdId: null,
|
||||
createdAt: new Date().toISOString(),
|
||||
updatedAt: new Date().toISOString(),
|
||||
};
|
||||
mockUpsertFromToken.mockResolvedValue(mockUser);
|
||||
|
||||
const app = await buildTestApp();
|
||||
await app.ready();
|
||||
|
||||
const res = await app.inject({
|
||||
method: 'GET',
|
||||
url: '/api/v1/users/me',
|
||||
headers: { authorization: 'Bearer valid-token' },
|
||||
});
|
||||
|
||||
expect(res.statusCode).toBe(200);
|
||||
const body = res.json();
|
||||
expect(body.keycloakId).toBe('kc-1');
|
||||
expect(body.email).toBe('test@example.com');
|
||||
expect(mockUpsertFromToken).toHaveBeenCalledWith('kc-1', 'test@example.com', 'testuser');
|
||||
|
||||
await app.close();
|
||||
});
|
||||
});
|
||||
81
packages/api/src/modules/users/users.routes.ts
Normal file
81
packages/api/src/modules/users/users.routes.ts
Normal file
|
|
@ -0,0 +1,81 @@
|
|||
import fp from 'fastify-plugin';
|
||||
import { asClass, Lifetime } from 'awilix';
|
||||
import type { ZodTypeProvider } from 'fastify-type-provider-zod';
|
||||
import { z } from 'zod/v4';
|
||||
import { UsersRepository } from './users.repository.js';
|
||||
import { UsersService } from './users.service.js';
|
||||
import { NotFoundError } from '../../common/errors.js';
|
||||
|
||||
type AnyUserDoc = {
|
||||
_id: string | { toString: () => string };
|
||||
keycloakId: string;
|
||||
displayName: string;
|
||||
email: string;
|
||||
householdIds: string[];
|
||||
defaultHouseholdId?: string | null;
|
||||
createdAt: string | { toISOString: () => string };
|
||||
updatedAt: string | { toISOString: () => string };
|
||||
};
|
||||
|
||||
function toUserResponse(doc: AnyUserDoc) {
|
||||
const id = typeof doc._id === 'string' ? doc._id : doc._id.toString();
|
||||
const createdAt = typeof doc.createdAt === 'string' ? doc.createdAt : doc.createdAt.toISOString();
|
||||
const updatedAt = typeof doc.updatedAt === 'string' ? doc.updatedAt : doc.updatedAt.toISOString();
|
||||
return {
|
||||
_id: id,
|
||||
keycloakId: doc.keycloakId,
|
||||
displayName: doc.displayName,
|
||||
email: doc.email,
|
||||
householdIds: doc.householdIds,
|
||||
defaultHouseholdId: doc.defaultHouseholdId ?? null,
|
||||
createdAt,
|
||||
updatedAt,
|
||||
};
|
||||
}
|
||||
|
||||
declare module '@fastify/awilix' {
|
||||
interface Cradle {
|
||||
usersRepository: UsersRepository;
|
||||
usersService: UsersService;
|
||||
}
|
||||
}
|
||||
|
||||
export default fp(
|
||||
async (fastify) => {
|
||||
// Register DI
|
||||
fastify.diContainer.register({
|
||||
usersRepository: asClass(UsersRepository, { lifetime: Lifetime.SINGLETON }),
|
||||
usersService: asClass(UsersService, { lifetime: Lifetime.SINGLETON }),
|
||||
});
|
||||
|
||||
const app = fastify.withTypeProvider<ZodTypeProvider>();
|
||||
|
||||
// GET /api/v1/users/me — get current user profile (syncs from token on first call)
|
||||
app.route({
|
||||
method: 'GET',
|
||||
url: '/api/v1/users/me',
|
||||
config: { skipHousehold: true },
|
||||
schema: {
|
||||
response: {
|
||||
200: z.object({
|
||||
_id: z.string(),
|
||||
keycloakId: z.string(),
|
||||
displayName: z.string(),
|
||||
email: z.string(),
|
||||
householdIds: z.array(z.string()),
|
||||
defaultHouseholdId: z.string().nullable(),
|
||||
createdAt: z.string(),
|
||||
updatedAt: z.string(),
|
||||
}),
|
||||
},
|
||||
},
|
||||
handler: async (request, reply) => {
|
||||
const service = fastify.diContainer.resolve('usersService');
|
||||
const user = await service.syncFromToken(request.user);
|
||||
if (!user) throw new NotFoundError('User sync failed');
|
||||
return reply.send(toUserResponse(user));
|
||||
},
|
||||
});
|
||||
},
|
||||
{ name: 'users-routes', dependencies: ['auth-plugin'] },
|
||||
);
|
||||
61
packages/api/src/modules/users/users.service.test.ts
Normal file
61
packages/api/src/modules/users/users.service.test.ts
Normal file
|
|
@ -0,0 +1,61 @@
|
|||
import { describe, it, expect, vi, beforeEach } from 'vitest';
|
||||
import { UsersService } from './users.service.js';
|
||||
import { NotFoundError } from '../../common/errors.js';
|
||||
|
||||
describe('UsersService', () => {
|
||||
const mockRepo = {
|
||||
findByKeycloakId: vi.fn(),
|
||||
findById: vi.fn(),
|
||||
create: vi.fn(),
|
||||
update: vi.fn(),
|
||||
upsertFromToken: vi.fn(),
|
||||
};
|
||||
|
||||
let service: UsersService;
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
service = new UsersService({ usersRepository: mockRepo as never });
|
||||
});
|
||||
|
||||
describe('syncFromToken', () => {
|
||||
it('upserts user from auth token data', async () => {
|
||||
const authUser = {
|
||||
keycloakId: 'kc-1',
|
||||
email: 'test@example.com',
|
||||
displayName: 'Test User',
|
||||
roles: ['member'],
|
||||
householdIds: [],
|
||||
};
|
||||
const upserted = { _id: 'u1', ...authUser };
|
||||
mockRepo.upsertFromToken.mockResolvedValue(upserted);
|
||||
|
||||
const result = await service.syncFromToken(authUser);
|
||||
|
||||
expect(mockRepo.upsertFromToken).toHaveBeenCalledWith(
|
||||
'kc-1',
|
||||
'test@example.com',
|
||||
'Test User',
|
||||
);
|
||||
expect(result).toEqual(upserted);
|
||||
});
|
||||
});
|
||||
|
||||
describe('getProfile', () => {
|
||||
it('returns user when found', async () => {
|
||||
const user = { _id: 'u1', keycloakId: 'kc-1', displayName: 'Test' };
|
||||
mockRepo.findByKeycloakId.mockResolvedValue(user);
|
||||
|
||||
const result = await service.getProfile('kc-1');
|
||||
|
||||
expect(result).toEqual(user);
|
||||
expect(mockRepo.findByKeycloakId).toHaveBeenCalledWith('kc-1');
|
||||
});
|
||||
|
||||
it('throws NotFoundError when user not found', async () => {
|
||||
mockRepo.findByKeycloakId.mockResolvedValue(null);
|
||||
|
||||
await expect(service.getProfile('kc-missing')).rejects.toThrow(NotFoundError);
|
||||
});
|
||||
});
|
||||
});
|
||||
27
packages/api/src/modules/users/users.service.ts
Normal file
27
packages/api/src/modules/users/users.service.ts
Normal file
|
|
@ -0,0 +1,27 @@
|
|||
import type { UsersRepository } from './users.repository.js';
|
||||
import type { AuthUser } from '../../common/types.js';
|
||||
import { NotFoundError } from '../../common/errors.js';
|
||||
|
||||
interface Deps {
|
||||
usersRepository: UsersRepository;
|
||||
}
|
||||
|
||||
export class UsersService {
|
||||
private readonly usersRepository: UsersRepository;
|
||||
|
||||
public constructor({ usersRepository }: Deps) {
|
||||
this.usersRepository = usersRepository;
|
||||
}
|
||||
|
||||
public async syncFromToken(user: AuthUser) {
|
||||
return this.usersRepository.upsertFromToken(user.keycloakId, user.email, user.displayName);
|
||||
}
|
||||
|
||||
public async getProfile(keycloakId: string) {
|
||||
const user = await this.usersRepository.findByKeycloakId(keycloakId);
|
||||
if (!user) {
|
||||
throw new NotFoundError('User not found');
|
||||
}
|
||||
return user;
|
||||
}
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue