first commit
This commit is contained in:
@@ -0,0 +1,57 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { InjectModel } from '@nestjs/mongoose';
|
||||
import { UserRegistry } from '@task-stream/api/identity/application';
|
||||
import { User, UserFactory } from '@task-stream/api/identity/domain';
|
||||
import { Model } from 'mongoose';
|
||||
import { UserDocument } from './user.schema';
|
||||
|
||||
@Injectable()
|
||||
export class MongoUserRegistry extends UserRegistry {
|
||||
constructor(
|
||||
@InjectModel(UserDocument.name) private readonly users: Model<UserDocument>,
|
||||
private readonly factory: UserFactory,
|
||||
) {
|
||||
super();
|
||||
}
|
||||
|
||||
async upsert(user: User): Promise<void> {
|
||||
await this.users.updateOne(
|
||||
{ _id: user.id },
|
||||
{ $set: { name: user.name, email: user.email, isActive: user.isActive } },
|
||||
{ upsert: true },
|
||||
);
|
||||
}
|
||||
|
||||
async findById(id: string): Promise<User | null> {
|
||||
const doc = await this.users.findById(id).lean();
|
||||
return doc ? this.toUser(doc) : null;
|
||||
}
|
||||
|
||||
async findByIds(ids: string[]): Promise<User[]> {
|
||||
if (ids.length === 0) return [];
|
||||
const docs = await this.users.find({ _id: { $in: ids } }).lean();
|
||||
return docs.map((d) => this.toUser(d));
|
||||
}
|
||||
|
||||
async search(term: string, limit: number): Promise<User[]> {
|
||||
const pattern = new RegExp(
|
||||
term.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'),
|
||||
'i',
|
||||
);
|
||||
const docs = await this.users
|
||||
.find(term ? { $or: [{ name: pattern }, { email: pattern }] } : {})
|
||||
.sort({ name: 1 })
|
||||
.limit(limit)
|
||||
.lean();
|
||||
return docs.map((d) => this.toUser(d));
|
||||
}
|
||||
|
||||
private toUser(doc: UserDocument): User {
|
||||
return this.factory.restore({
|
||||
id: doc._id,
|
||||
name: doc.name,
|
||||
email: doc.email,
|
||||
isActive: doc.isActive,
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose';
|
||||
|
||||
@Schema({ collection: 'users', timestamps: true, versionKey: false })
|
||||
export class UserDocument {
|
||||
@Prop({ type: String, required: true })
|
||||
_id!: string;
|
||||
|
||||
@Prop({ required: true })
|
||||
name!: string;
|
||||
|
||||
@Prop({ required: true, index: true })
|
||||
email!: string;
|
||||
|
||||
@Prop({ default: true })
|
||||
isActive!: boolean;
|
||||
}
|
||||
|
||||
export const UserSchema = SchemaFactory.createForClass(UserDocument);
|
||||
UserSchema.index({ name: 'text', email: 'text' });
|
||||
Reference in New Issue
Block a user