40 lines
1.1 KiB
TypeScript
40 lines
1.1 KiB
TypeScript
import { Injectable, InternalServerErrorException } from '@nestjs/common';
|
|
import { ConnectionService } from '../global/database/connection.service';
|
|
import { IdentityDocument } from '../global/database/schema';
|
|
|
|
interface IdentityInput {
|
|
entraOid: string;
|
|
tenantId?: string;
|
|
email?: string;
|
|
displayName?: string;
|
|
}
|
|
|
|
@Injectable()
|
|
export class IdentityService {
|
|
constructor(private readonly connectionService: ConnectionService) {}
|
|
|
|
public async findOrCreateByOid(
|
|
input: IdentityInput,
|
|
): Promise<IdentityDocument> {
|
|
const IdentityModel = await this.connectionService.getModel('identity');
|
|
const identity = await IdentityModel.findOneAndUpdate(
|
|
{ entraOid: input.entraOid },
|
|
{
|
|
$set: {
|
|
tenantId: input.tenantId,
|
|
email: input.email,
|
|
displayName: input.displayName,
|
|
lastSignInAt: new Date(),
|
|
},
|
|
$setOnInsert: { entraOid: input.entraOid },
|
|
},
|
|
{ upsert: true, returnDocument: 'after', setDefaultsOnInsert: true },
|
|
).exec();
|
|
|
|
if (!identity) {
|
|
throw new InternalServerErrorException('Failed to resolve identity.');
|
|
}
|
|
return identity;
|
|
}
|
|
}
|