NotesController: Use custom logic to access raw markdown

NestJS does not support content-types other than application/json.
Therefore we need to directly access the request object to get the raw body content.

Signed-off-by: David Mehren <git@herrmehren.de>
This commit is contained in:
David Mehren 2020-09-19 14:51:12 +02:00
parent bbba2fc348
commit 93cf9c2c56
No known key found for this signature in database
GPG key ID: 185982BA4C42B7C3
3 changed files with 37 additions and 3 deletions

View file

@ -1,27 +1,50 @@
import {
BadRequestException,
Body,
Controller,
Delete,
Get,
Header,
Logger,
Param,
Post,
Put,
Req,
} from '@nestjs/common';
import { Request } from 'express';
import * as getRawBody from 'raw-body';
import { NotePermissionsUpdateDto } from '../../../notes/note-permissions.dto';
import { NotesService } from '../../../notes/notes.service';
import { RevisionsService } from '../../../revisions/revisions.service';
@Controller('notes')
export class NotesController {
private readonly logger = new Logger(NotesController.name);
constructor(
private noteService: NotesService,
private revisionsService: RevisionsService,
) {}
/**
* Extract the raw markdown from the request body and create a new note with it
*
* Implementation inspired by https://stackoverflow.com/questions/52283713/how-do-i-pass-plain-text-as-my-request-body-using-nestjs
*/
@Post()
createNote(@Body() noteContent: string) {
return this.noteService.createNote(noteContent);
@Header('content-type', 'text/markdown')
async createNote(@Req() req: Request) {
// we have to check req.readable because of raw-body issue #57
// https://github.com/stream-utils/raw-body/issues/57
if (req.readable) {
let bodyText: string = await getRawBody(req, 'utf-8');
bodyText = bodyText.trim();
this.logger.debug('Got raw markdown:\n' + bodyText);
return this.noteService.createNote(bodyText);
} else {
// TODO: Better error message
throw new BadRequestException('Invalid body');
}
}
@Get(':noteIdOrAlias')