Skip to content

Commit

Permalink
chore: replace query to check if shortlink is available
Browse files Browse the repository at this point in the history
  • Loading branch information
gweiying committed Mar 18, 2024
1 parent a71d1a9 commit 504e539
Show file tree
Hide file tree
Showing 3 changed files with 31 additions and 2 deletions.
6 changes: 4 additions & 2 deletions src/server/modules/user/services/UrlManagementService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -76,8 +76,10 @@ export class UrlManagementService implements interfaces.UrlManagementService {
shortUrl = await generateShortUrl(API_LINK_RANDOM_STR_LENGTH)
}

const owner = await this.userRepository.findUserByUrl(shortUrl)
if (owner) {
const isShortUrlAvailable = await this.urlRepository.isShortUrlAvailable(
shortUrl,
)
if (!isShortUrlAvailable) {
throw new AlreadyExistsError(`Short link "${shortUrl}" is already used.`)
}

Expand Down
21 changes: 21 additions & 0 deletions src/server/repositories/UrlRepository.ts
Original file line number Diff line number Diff line change
Expand Up @@ -175,6 +175,27 @@ export class UrlRepository implements UrlRepositoryInterface {
return this.urlMapper.persistenceToDto(newUrl)
}

/**
* @param {string} shortUrl Short url.
* @returns {Promise<boolean>} Returns true if shortUrl is available and false otherwise.
*/
public isShortUrlAvailable: (shortUrl: string) => Promise<boolean> = async (
shortUrl,
) => {
try {
// Cache lookup
// if long url does not exist, throws error
const longUrl = await this.getLongUrlFromCache(shortUrl)
return !longUrl
} catch {
// Cache failed, look in database
const url = await Url.findOne({
where: { shortUrl },
})
return !url
}
}

public getLongUrl: (shortUrl: string) => Promise<string> = async (
shortUrl,
) => {
Expand Down
6 changes: 6 additions & 0 deletions src/server/repositories/interfaces/UrlRepositoryInterface.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,12 @@ export interface UrlRepositoryInterface {
file?: StorableFile,
): Promise<StorableUrl>

/**
* Returns true if shortUrl is available, otherwise false.
* @param {string} shortUrl The shortUrl.
*/
isShortUrlAvailable: (shortUrl: string) => Promise<boolean>

/**
* Looks up the longUrl given a shortUrl from the cache, falling back
* to the database. The cache is re-populated if the database lookup is
Expand Down

0 comments on commit 504e539

Please sign in to comment.