auth/src/modules/authentication/authentication.mapper.ts

69 lines
2.1 KiB
TypeScript

import { Mapper } from '@mobicoop/ddd-library';
import { Injectable } from '@nestjs/common';
import { AuthenticationEntity } from './core/domain/authentication.entity';
import { AuthenticationResponseDto } from './interface/dtos/authentication.response.dto';
import {
AuthenticationReadModel,
AuthenticationWriteModel,
UsernameModel,
} from './infrastructure/authentication.repository';
import { Type, UsernameProps } from './core/domain/username.types';
/**
* Mapper constructs objects that are used in different layers:
* Record is an object that is stored in a database,
* Entity is an object that is used in application domain layer,
* and a ResponseDTO is an object returned to a user (usually as json).
*/
@Injectable()
export class AuthenticationMapper
implements
Mapper<
AuthenticationEntity,
AuthenticationReadModel,
AuthenticationWriteModel,
AuthenticationResponseDto
>
{
toPersistence = (entity: AuthenticationEntity): AuthenticationWriteModel => {
const copy = entity.getProps();
const record: AuthenticationWriteModel = {
uuid: copy.id,
password: copy.password,
usernames: copy.usernames
? {
create: copy.usernames.map((username: UsernameProps) => ({
username: username.name,
type: username.type,
})),
}
: undefined,
};
return record;
};
toDomain = (record: AuthenticationReadModel): AuthenticationEntity => {
const entity = new AuthenticationEntity({
id: record.uuid,
createdAt: new Date(record.createdAt),
updatedAt: new Date(record.updatedAt),
props: {
userId: record.uuid,
password: record.password,
usernames: record.usernames?.map((username: UsernameModel) => ({
userId: record.uuid,
name: username.username,
type: username.type as Type,
})),
},
});
return entity;
};
toResponse = (entity: AuthenticationEntity): AuthenticationResponseDto => {
const response = new AuthenticationResponseDto(entity);
return response;
};
}