Skip to content

Commit

Permalink
Merge pull request #62 from zhumeisongsong/feature/get-user-id-to-Obj…
Browse files Browse the repository at this point in the history
…ectId

fix: 🐛 id for MongooseUsersRepository is not objectId
  • Loading branch information
zhumeisongsong authored Nov 20, 2024
2 parents c12374c + b1990b9 commit 6bf7dba
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 10 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -27,21 +27,27 @@ describe('MongooseUsersRepository', () => {
});

it('should return a user when found', async () => {
const userDoc = { id: '1', name: 'John Doe' };
const mockUser = {
id: '507f1f77bcf86cd799439011',
name: 'Test User',
};

jest.spyOn(userModel, 'findById').mockReturnValue({
exec: jest.fn().mockResolvedValue(userDoc),
exec: jest.fn().mockResolvedValue(mockUser),
} as any);

const user = await repository.findById('1');
expect(user).toEqual(new User('1', 'John Doe'));
const user = await repository.findById(mockUser.id);
expect(user).toBeInstanceOf(User);
expect(user?.id).toBe(mockUser.id);
expect(user?.name).toBe(mockUser.name);
});

it('should return null when user is not found', async () => {
jest.spyOn(userModel, 'findById').mockReturnValue({
exec: jest.fn().mockResolvedValue(null),
} as any);

const user = await repository.findById('1');
const user = await repository.findById('507f1f77bcf86cd799439011');
expect(user).toBeNull();
});
});
Original file line number Diff line number Diff line change
@@ -1,22 +1,24 @@
import { Injectable } from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose';
import { User, UsersRepository } from '@users/domain';
import { Model } from 'mongoose';
import { Model, Types } from 'mongoose';

import { UserDocument } from './user.schema';

@Injectable()
@Injectable()
export class MongooseUsersRepository implements UsersRepository {
constructor(
@InjectModel(UserDocument.name) private userModel: Model<UserDocument>,
) {}

async findById(id: string): Promise<User | null> {
const userDoc = await this.userModel.findById(id).exec();

if (!userDoc) {
const _id = new Types.ObjectId(id);
const userDocument = await this.userModel.findById(_id).exec();

if (!userDocument) {
return null;
}
return new User(userDoc.id, userDoc.name);
return new User(userDocument.id, userDocument.name);
}
}

0 comments on commit 6bf7dba

Please sign in to comment.