Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Chore/fix user query #2296

Merged
merged 3 commits into from
Mar 18, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ describe('UrlManagementService', () => {
update: jest.fn(),
create: jest.fn(),
findByShortUrlWithTotalClicks: jest.fn(),
isShortUrlAvailable: jest.fn(),
getLongUrl: jest.fn(),
plainTextSearch: jest.fn(),
rawDirectorySearch: jest.fn(),
Expand All @@ -40,7 +41,6 @@ describe('UrlManagementService', () => {

beforeEach(() => {
userRepository.findById.mockReset()
userRepository.findUserByUrl.mockReset()
urlRepository.findByShortUrlWithTotalClicks.mockReset()
urlRepository.create.mockReset()
})
Expand All @@ -51,34 +51,33 @@ describe('UrlManagementService', () => {
service.createUrl(userId, sourceConsole, shortUrl, longUrl),
).rejects.toBeInstanceOf(NotFoundError)
expect(userRepository.findById).toHaveBeenCalledWith(userId)
expect(userRepository.findUserByUrl).not.toHaveBeenCalled()
expect(urlRepository.isShortUrlAvailable).not.toHaveBeenCalledWith(
shortUrl,
)
expect(urlRepository.create).not.toHaveBeenCalled()
})

it('throws AlreadyExistsError on existing url', async () => {
userRepository.findById.mockResolvedValue({ id: userId })
userRepository.findUserByUrl.mockResolvedValue({
shortUrl,
longUrl,
email: userId,
})
urlRepository.isShortUrlAvailable.mockResolvedValue(false)
await expect(
service.createUrl(userId, sourceConsole, shortUrl, longUrl),
).rejects.toBeInstanceOf(AlreadyExistsError)
expect(userRepository.findById).toHaveBeenCalledWith(userId)
expect(userRepository.findUserByUrl).toHaveBeenCalledWith(shortUrl)
expect(urlRepository.isShortUrlAvailable).toHaveBeenCalledWith(shortUrl)
expect(urlRepository.create).not.toHaveBeenCalled()
})

it('processes new non-file url', async () => {
userRepository.findById.mockResolvedValue({ id: userId })
urlRepository.isShortUrlAvailable.mockResolvedValue(true)
urlRepository.findByShortUrlWithTotalClicks.mockResolvedValue(null)
urlRepository.create.mockResolvedValue({ userId, longUrl, shortUrl })
await expect(
service.createUrl(userId, sourceConsole, shortUrl, longUrl),
).resolves.toStrictEqual({ userId, longUrl, shortUrl })
expect(userRepository.findById).toHaveBeenCalledWith(userId)
expect(userRepository.findUserByUrl).toHaveBeenCalledWith(shortUrl)
expect(urlRepository.isShortUrlAvailable).toHaveBeenCalledWith(shortUrl)
expect(urlRepository.create).toHaveBeenCalledWith(
{ userId, longUrl, shortUrl, source: sourceConsole },
undefined,
Expand All @@ -92,13 +91,14 @@ describe('UrlManagementService', () => {
mimetype: 'application/json',
}
userRepository.findById.mockResolvedValue({ id: userId })
urlRepository.isShortUrlAvailable.mockResolvedValue(true)
urlRepository.findByShortUrlWithTotalClicks.mockResolvedValue(null)
urlRepository.create.mockResolvedValue({ userId, longUrl, shortUrl })
await expect(
service.createUrl(userId, sourceConsole, shortUrl, longUrl, file),
).resolves.toStrictEqual({ userId, longUrl, shortUrl })
expect(userRepository.findById).toHaveBeenCalledWith(userId)
expect(userRepository.findUserByUrl).toHaveBeenCalledWith(shortUrl)
expect(urlRepository.isShortUrlAvailable).toHaveBeenCalledWith(shortUrl)
expect(urlRepository.create).toHaveBeenCalledWith(
{ userId, longUrl, shortUrl, source: sourceConsole },
{
Expand All @@ -119,13 +119,14 @@ describe('UrlManagementService', () => {
const service = new UrlManagementService(userRepository, urlRepository)

userRepository.findById.mockResolvedValue({ id: userId })
urlRepository.isShortUrlAvailable.mockResolvedValue(true)
urlRepository.findByShortUrlWithTotalClicks.mockResolvedValue(null)
urlRepository.create.mockResolvedValue({ userId, longUrl, shortUrl })
await expect(
service.createUrl(userId, sourceApi, undefined, longUrl),
).resolves.toStrictEqual({ userId, longUrl, shortUrl })
expect(userRepository.findById).toHaveBeenCalledWith(userId)
expect(userRepository.findUserByUrl).toHaveBeenCalledWith(
expect(urlRepository.isShortUrlAvailable).toHaveBeenCalledWith(
expect.stringMatching(/^.{4}$/),
)
expect(urlRepository.create).toHaveBeenCalledWith(
Expand Down
22 changes: 22 additions & 0 deletions src/server/repositories/UrlRepository.ts
Original file line number Diff line number Diff line change
Expand Up @@ -175,6 +175,28 @@ 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
await this.getLongUrlFromCache(shortUrl)
// if long url does not exist, throws error
// return false if no error since long url exists
return false
} catch {
// Cache failed, look in database
const url = await Url.findOne({
where: { shortUrl },
})
Comment on lines +193 to +195

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

/nit/micro-optimization: since we only care for an exists, you could reduce the selection to just the shortUrl field. Otherwise the query seems to be sent like this atm (according to the traces):

SELECT shortUrl, longUrl, state, isFile, contactEmail, description, source, tagStrings, createdAt, updatedAt, userId FROM urls WHERE url . shortUrl = ?
Suggested change
const url = await Url.findOne({
where: { shortUrl },
})
const url = await Url.findOne({
attributes: ['shortUrl'],
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
4 changes: 4 additions & 0 deletions test/server/mocks/repositories/UrlRepository.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,10 @@ export class UrlRepositoryMock implements UrlRepositoryInterface {
throw new Error('Not implemented')
}

isShortUrlAvailable: (shortUrl: string) => Promise<boolean> = () => {
throw new Error('Not implemented')
}

getLongUrl: (shortUrl: string) => Promise<string> = () => {
throw new Error('Not implemented')
}
Expand Down
Loading