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() {
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<LinkRedirect>}
*/
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);

View File

@ -28,11 +28,6 @@ const ObjectID = require('bson-objectid').default;
* @prop {({filter: string}) => Promise<ILinkRedirect[]>} getAll
*/
/**
* @typedef {object} ILinkClickTrackingService
* @prop {(link: ILinkRedirect, uuid: string) => Promise<URL>} addTrackingToRedirect
*/
/**
* @typedef {object} IPostLinkRepository
* @prop {(postLink: PostLink) => Promise<void>} 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({