From a2e8c3d0316611fdbd970f3af93592b8d1f0a6ad Mon Sep 17 00:00:00 2001 From: David Mehren Date: Wed, 19 May 2021 21:19:08 +0200 Subject: [PATCH] Move `publicID` creation to `Note.create` Before this commit, `Note.create()` did not return a complete object, as the `publicId` property was missing. This adds the generation of the property to the `create` method and moves the actual generation code from the `NotesService` to a utility method. Signed-off-by: David Mehren --- src/notes/note.entity.ts | 2 ++ src/notes/notes.service.ts | 10 ---------- src/notes/utils.ts | 17 +++++++++++++++++ 3 files changed, 19 insertions(+), 10 deletions(-) create mode 100644 src/notes/utils.ts diff --git a/src/notes/note.entity.ts b/src/notes/note.entity.ts index 30f06bb3b..6a3067b76 100644 --- a/src/notes/note.entity.ts +++ b/src/notes/note.entity.ts @@ -21,6 +21,7 @@ import { AuthorColor } from './author-color.entity'; import { Tag } from './tag.entity'; import { HistoryEntry } from '../history/history-entry.entity'; import { MediaUpload } from '../media/media-upload.entity'; +import { generatePublicId } from './utils'; @Entity() export class Note { @@ -85,6 +86,7 @@ export class Note { public static create(owner?: User, alias?: string): Note { const newNote = new Note(); + newNote.publicId = generatePublicId(); newNote.alias = alias ?? null; newNote.viewCount = 0; newNote.owner = owner ?? null; diff --git a/src/notes/notes.service.ts b/src/notes/notes.service.ts index b667d4776..149262aa3 100644 --- a/src/notes/notes.service.ts +++ b/src/notes/notes.service.ts @@ -94,7 +94,6 @@ export class NotesService { newNote.revisions = Promise.resolve([ Revision.create(noteContent, noteContent), ]); - newNote.publicId = this.generatePublicId(); if (alias) { newNote.alias = alias; this.checkNoteIdOrAlias(alias); @@ -213,15 +212,6 @@ export class NotesService { } } - /** - * Generate publicId for a note. - * This is a randomly generated 128-bit value encoded with base32-encode using the crockford variant and converted to lowercase. - */ - generatePublicId(): string { - const randomId = randomBytes(128); - return base32Encode(randomId, 'Crockford').toLowerCase(); - } - /** * @async * Delete a note diff --git a/src/notes/utils.ts b/src/notes/utils.ts new file mode 100644 index 000000000..cbb907171 --- /dev/null +++ b/src/notes/utils.ts @@ -0,0 +1,17 @@ +/* + * SPDX-FileCopyrightText: 2021 The HedgeDoc developers (see AUTHORS file) + * + * SPDX-License-Identifier: AGPL-3.0-only + */ + +import base32Encode from 'base32-encode'; +import { randomBytes } from 'crypto'; + +/** + * Generate publicId for a note. + * This is a randomly generated 128-bit value encoded with base32-encode using the crockford variant and converted to lowercase. + */ +export function generatePublicId(): string { + const randomId = randomBytes(128); + return base32Encode(randomId, 'Crockford').toLowerCase(); +}