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鈥檒l occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add feature- The user can ask for specific urlKey #664

Closed
wants to merge 2 commits into from
Closed
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
4 changes: 4 additions & 0 deletions apps/backend/src/shortener/dto/shortener.dto.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,10 @@ export class ShortenerDto {
)
url: string;

@IsString()
@IsOptional()
urlKey?: string;

@IsString()
@IsOptional()
description?: string;
Expand Down
19 changes: 13 additions & 6 deletions apps/backend/src/shortener/shortener.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -81,9 +81,10 @@ export class ShortenerService {
* Create a short URL based on the provided data.
* @param {string} url - The original URL.
* @param {number} ttl The time to live.
* @param {number} urlKey The desired url key.
* @returns {Promise<{ key: string }>} Returns an object containing the newly created key.
*/
createShortenedUrl = async (url: string, ttl?: number): Promise<{ key: string }> => {
createShortenedUrl = async (url: string, ttl?: number, urlKey = ''): Promise<{ key: string }> => {
let parsedUrl: URL;
try {
parsedUrl = new URL(url);
Expand All @@ -98,10 +99,16 @@ export class ShortenerService {

let shortUrl: string;

do {
shortUrl = this.generateKey();
} while (!(await this.isKeyAvailable(shortUrl)));

if (typeof urlKey === 'string' && urlKey.length > 0) {
if (!(await this.isKeyAvailable(urlKey))) {
throw new BadRequestException('The provided shortened key is already in use');
}
shortUrl = urlKey;
} else {
do {
shortUrl = this.generateKey();
} while (!(await this.isKeyAvailable(shortUrl)));
}
await this.addLinkToCache(parsedUrl.href, shortUrl, ttl);
return { key: shortUrl };
};
Expand Down Expand Up @@ -163,7 +170,7 @@ export class ShortenerService {
* @returns {Promise<{ key: string }>} - Returns an object containing the newly created short URL.
*/
createUsersShortenedUrl = async (user: UserContext, shortenerDto: ShortenerDto): Promise<{ key: string }> => {
const { key } = await this.createShortenedUrl(shortenerDto.url, shortenerDto.ttl);
const { key } = await this.createShortenedUrl(shortenerDto.url, shortenerDto.ttl, shortenerDto.urlKey);
await this.createDbUrl(user, shortenerDto, key);

return { key };
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,12 @@ import { Form, globalAction$, zod$ } from '@builder.io/qwik-city';
import { z } from 'zod';
import { ACCESS_COOKIE_NAME } from '../../../../shared/auth.service';
import { normalizeUrl } from '../../../../utils';
import { s } from 'vitest/dist/types-198fd1d9';

export const LINK_MODAL_ID = 'link-modal';

const useCreateLink = globalAction$(
async ({ url }, { fail, cookie }) => {
async ({ url, urlKey }, { fail, cookie }) => {
const response: Response = await fetch(`${process.env.API_DOMAIN}/api/v1/shortener`, {
method: 'POST',
headers: {
Expand All @@ -18,6 +19,7 @@ const useCreateLink = globalAction$(
body: JSON.stringify({
url: normalizeUrl(url),
expirationTime: null, // forever
urlKey,
}),
});

Expand Down Expand Up @@ -45,20 +47,23 @@ const useCreateLink = globalAction$(
.regex(/^(?:https?:\/\/)?(?:[\w-]+\.)+[a-z]{2,}(?::\d{1,5})?(?:\/\S*)?$/, {
message: "The url you've entered is not valid",
}),
urlKey: z.string(),
})
);

export interface LinkModalProps {
onSubmitHandler: () => void;
}

const initValues = { url: '', urlKey: '' };

export const LinkModal = component$(({ onSubmitHandler }: LinkModalProps) => {
const inputValue = useSignal('');
const inputValue = useSignal({ ...initValues });

const action = useCreateLink();

const clearValues = $(() => {
inputValue.value = '';
inputValue.value = { ...initValues };

if (action.value?.fieldErrors) {
action.value.fieldErrors.url = [];
Expand Down Expand Up @@ -106,9 +111,22 @@ export const LinkModal = component$(({ onSubmitHandler }: LinkModalProps) => {
type="text"
placeholder="This should be a very long url..."
class="input input-bordered w-full"
value={inputValue.value}
value={inputValue.value.url}
onInput$={(ev: InputEvent) => {
inputValue.value.url = (ev.target as HTMLInputElement).value;
}}
/>
<label class="label">
<span class="label-text">Shortened Key (optional)</span>
</label>
<input
name="urlKey"
type="text"
placeholder="The reduced.to/<key> you want to use"
class="input input-bordered w-full"
value={inputValue.value.urlKey}
onInput$={(ev: InputEvent) => {
inputValue.value = (ev.target as HTMLInputElement).value;
inputValue.value.urlKey = (ev.target as HTMLInputElement).value;
}}
/>
{action.value?.fieldErrors?.url && (
Expand Down