fix mongo class transform

This commit is contained in:
Evert Prants 2022-12-08 20:08:31 +02:00
parent b6a92325a7
commit 8c761c66a8
Signed by: evert
GPG Key ID: 1688DA83D222D0B5
2 changed files with 22 additions and 17 deletions

View File

@ -4,6 +4,7 @@ import {
NotFoundException,
} from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose';
import { instanceToPlain, plainToInstance } from 'class-transformer';
import { Model } from 'mongoose';
import {
ApplicationStatus,
@ -27,17 +28,6 @@ const requestedFields = [
'regulatoryElectionSub',
];
const fieldsToExpose = [
'id',
'residentSub',
'current',
'requested',
'status',
'submittedAt',
'decision',
'objectStatus',
];
@Injectable()
export class IndustryChangeApplicationService {
constructor(
@ -174,12 +164,15 @@ export class IndustryChangeApplicationService {
return findApplication.save();
}
// I wrote this because I could not for the life of me get class-transformer to
// play along with mongo documents. I do not have experience with either, so this
// was a last ditch effort.
makeReadable(input: IndustryChangeApplication | IndustryChangeApplication[]) {
return Array.isArray(input)
? input.map((object) => take(takeMongoObject(object), fieldsToExpose))
: take(takeMongoObject(input), fieldsToExpose);
if (Array.isArray(input)) {
return input.map((item) => this.makeReadable(item));
}
const response = plainToInstance(
IndustryChangeApplication,
(input as IndustryChangeApplicationDocument).toJSON(),
);
return instanceToPlain(response);
}
}

View File

@ -3,6 +3,7 @@ import { HydratedDocument } from 'mongoose';
import { Decision } from './Decision.schema';
import { ApplicationStatus, ObjectStatus } from 'src/enums/status.enum';
import { ICAInformation } from './ICAInformation.schema';
import { Exclude, Expose, Transform } from 'class-transformer';
export type IndustryChangeApplicationDocument =
HydratedDocument<IndustryChangeApplication>;
@ -11,6 +12,13 @@ export type IndustryChangeApplicationDocument =
timestamps: true,
})
export class IndustryChangeApplication {
@Expose({ name: 'id' })
@Transform(({ key, obj }) => obj[key].toString())
_id: string;
@Exclude()
__v: number;
@Prop({
required: true,
})
@ -42,9 +50,11 @@ export class IndustryChangeApplication {
@Prop({ type: Decision })
decision: Decision;
@Exclude()
@Prop()
createdBy: string;
@Exclude()
@Prop()
updatedBy: string;
@ -56,8 +66,10 @@ export class IndustryChangeApplication {
})
objectStatus: ObjectStatus;
@Exclude()
createdAt: Date;
@Exclude()
updatedAt: Date;
}