46 lines
1.4 KiB
TypeScript
46 lines
1.4 KiB
TypeScript
import { BadRequestException, Injectable, Logger } from '@nestjs/common';
|
|
import { Floor } from 'src/objects/building/entities/floor.entity';
|
|
import { PlanRenderer } from './renderer';
|
|
import { FloorDocument } from './renderer/renderer.interfaces';
|
|
import fs from 'fs';
|
|
import { join } from 'path';
|
|
import { isValidLayer } from './renderer/plan-validators';
|
|
|
|
@Injectable()
|
|
export class PlanRendererService {
|
|
public validateFloorDocument(floorDocument: FloorDocument) {
|
|
const valid =
|
|
floorDocument?.layers &&
|
|
!isNaN(floorDocument.height) &&
|
|
!isNaN(floorDocument.width) &&
|
|
floorDocument.height > 0 &&
|
|
floorDocument.width > 0 &&
|
|
Array.isArray(floorDocument.layers) &&
|
|
floorDocument.layers.every(isValidLayer);
|
|
|
|
if (!valid)
|
|
throw new BadRequestException(
|
|
'Floor plan JSON is incorrect or malformed',
|
|
);
|
|
}
|
|
|
|
public renderFloor(floor: Floor) {
|
|
const plan = JSON.parse(floor.plan || '{}') as FloorDocument;
|
|
this.validateFloorDocument(plan);
|
|
|
|
if (plan.layers.every(({ contents }) => !contents.length)) return;
|
|
|
|
const filename = `floorplan-${floor.id}.png`;
|
|
const output = fs.createWriteStream(
|
|
join(process.cwd(), 'usercontent', filename),
|
|
);
|
|
|
|
const pngStream = PlanRenderer.renderFloorDocument(plan);
|
|
pngStream.pipe(output);
|
|
output.on('finish', () =>
|
|
Logger.log(`Floor plan for ID:${plan.id} has been rendered`),
|
|
);
|
|
floor.planImage = filename;
|
|
}
|
|
}
|