0
Fork 0
mirror of https://github.com/TryGhost/Ghost.git synced 2025-02-03 23:00:14 -05:00

Cleaned up LinkRedirectsService

no issue
This commit is contained in:
Simon Backx 2022-09-23 13:32:44 +02:00
parent 1290477d71
commit 239d93a725
2 changed files with 15 additions and 17 deletions

View file

@ -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<string>} * @returns {Promise<URL>}
*/ */
async getSlug() { async getSlugUrl() {
return crypto.randomBytes(4).toString('hex'); 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 {URL} to
* @param {string} slug
* *
* @returns {Promise<LinkRedirect>} * @returns {Promise<LinkRedirect>}
*/ */
async addRedirect(to, slug) { async addRedirect(from, to) {
const from = new URL(`r/${slug}`, this.#baseURL);
const link = new LinkRedirect({ const link = new LinkRedirect({
to, from,
from to
}); });
await this.#linkRedirectRepository.save(link); await this.#linkRedirectRepository.save(link);

View file

@ -28,11 +28,6 @@ const ObjectID = require('bson-objectid').default;
* @prop {({filter: string}) => Promise<ILinkRedirect[]>} getAll * @prop {({filter: string}) => Promise<ILinkRedirect[]>} getAll
*/ */
/**
* @typedef {object} ILinkClickTrackingService
* @prop {(link: ILinkRedirect, uuid: string) => Promise<URL>} addTrackingToRedirect
*/
/** /**
* @typedef {object} IPostLinkRepository * @typedef {object} IPostLinkRepository
* @prop {(postLink: PostLink) => Promise<void>} save * @prop {(postLink: PostLink) => Promise<void>} save
@ -85,10 +80,10 @@ class LinkClickTrackingService {
*/ */
async addRedirectToUrl(url, post) { async addRedirectToUrl(url, post) {
// Generate a unique redirect slug // Generate a unique redirect slug
const slug = await this.#linkRedirectService.getSlug(); const slugUrl = await this.#linkRedirectService.getSlugUrl();
// Add redirect for link click tracking // 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 // Store a reference of the link against the post
const postLink = new PostLink({ const postLink = new PostLink({