import {
Controller, Get, Param, Post, Body
} from '@nestjs/common';
import {SimpleModel} from "@marcj/marshal/tests/entities";
import {plainToClass, Database, classToPlain} from "@marcj/marshal";
import {ValidationPipe} from "@marcj/marshal-nest";
import {createConnection} from "typeorm";
@Controller()
class MyController {
private database: Database;
private async getDatabase() {
if (!this.database) {
const connection = await createConnection({
type: "mongodb",
host: "localhost",
port: 27017,
database: "testing",
useNewUrlParser: true,
});
this.database = new Database(connection, 'testing');
}
return this.database;
}
@Post('/save')
async save(
@Body(ValidationPipe({transform: true})) body: SimpleModel,
) {
body instanceof SimpleModel;
await (await this.getDatabase()).save(SimpleModel, body);
return body.id;
}
@Get('/get/:id')
async get(@Param('id') id: string) {
const instance = await (await this.getDatabase()).get(SimpleModel, {_id: id});
return classToPlain(SimpleModel, instance);
}
}