From 239d93a725db72e55a26e0ef6d15886f65df70cf Mon Sep 17 00:00:00 2001 From: Simon Backx Date: Fri, 23 Sep 2022 13:32:44 +0200 Subject: [PATCH] Cleaned up LinkRedirectsService no issue --- .../lib/LinkRedirectsService.js | 23 +++++++++++-------- .../lib/LinkClickTrackingService.js | 9 ++------ 2 files changed, 15 insertions(+), 17 deletions(-) diff --git a/ghost/link-redirects/lib/LinkRedirectsService.js b/ghost/link-redirects/lib/LinkRedirectsService.js index 70e0036657..81ddfa2041 100644 --- a/ghost/link-redirects/lib/LinkRedirectsService.js +++ b/ghost/link-redirects/lib/LinkRedirectsService.js @@ -34,26 +34,29 @@ class LinkRedirectsService { } /** - * Get a unique slug for a redirect which hasn't already been taken + * Get a unique URL with slug for creating unique redirects * - * @returns {Promise} + * @returns {Promise} */ - async getSlug() { - return crypto.randomBytes(4).toString('hex'); + async getSlugUrl() { + let url; + while (!url || await this.#linkRedirectRepository.getByURL(url)) { + const slug = crypto.randomBytes(4).toString('hex'); + url = new URL(`r/${slug}`, this.#baseURL); + } + return url; } /** + * @param {URL} from * @param {URL} to - * @param {string} slug * * @returns {Promise} */ - async addRedirect(to, slug) { - const from = new URL(`r/${slug}`, this.#baseURL); - + async addRedirect(from, to) { const link = new LinkRedirect({ - to, - from + from, + to }); await this.#linkRedirectRepository.save(link); diff --git a/ghost/link-tracking/lib/LinkClickTrackingService.js b/ghost/link-tracking/lib/LinkClickTrackingService.js index 6ee8424b14..94de18d531 100644 --- a/ghost/link-tracking/lib/LinkClickTrackingService.js +++ b/ghost/link-tracking/lib/LinkClickTrackingService.js @@ -28,11 +28,6 @@ const ObjectID = require('bson-objectid').default; * @prop {({filter: string}) => Promise} getAll */ -/** - * @typedef {object} ILinkClickTrackingService - * @prop {(link: ILinkRedirect, uuid: string) => Promise} addTrackingToRedirect - */ - /** * @typedef {object} IPostLinkRepository * @prop {(postLink: PostLink) => Promise} save @@ -85,10 +80,10 @@ class LinkClickTrackingService { */ async addRedirectToUrl(url, post) { // Generate a unique redirect slug - const slug = await this.#linkRedirectService.getSlug(); + const slugUrl = await this.#linkRedirectService.getSlugUrl(); // Add redirect for link click tracking - const redirect = await this.#linkRedirectService.addRedirect(url, slug); + const redirect = await this.#linkRedirectService.addRedirect(slugUrl, url); // Store a reference of the link against the post const postLink = new PostLink({