اختصار الروابط (shortcut links by api in nestjs)
To create shortened links via an API in a NestJS application, you can use services like **Bitly**, **Firebase Dynamic Links**, or **TinyURL**. Here’s how to create a URL-shortening service in NestJS using Bitly as an example:
### Step-by-Step Guide for Bitly URL Shortening API in NestJS
#### 1. Set Up Your Bitly API Token
First, create an account on Bitly (if you haven’t already), then generate an API access token from your Bitly account under **Settings > API**.
#### 2. Install Axios
Install `axios` if it’s not already installed. We’ll use it to make HTTP requests to the Bitly API.
```bash
npm install axios
```
#### 3. Create a Service in NestJS to Shorten URLs
In your NestJS project, generate a service called `ShortenerService`.
```bash
nest generate service shortener
```
#### 4. Implement URL Shortening in `ShortenerService`
Update `shortener.service.ts` to include a method that sends requests to Bitly’s API.
```typescript
import { Injectable, HttpException, HttpStatus } from '@nestjs/common';
import axios from 'axios';
@Injectable()
export class ShortenerService {
private readonly bitlyAccessToken = 'YOUR_BITLY_ACCESS_TOKEN';
async shortenUrl(longUrl: string): Promise<string> {
try {
const response = await axios.post(
'https://api-ssl.bitly.com/v4/shorten',
{
long_url: longUrl,
},
{
headers: {
Authorization: `Bearer ${this.bitlyAccessToken}`,
'Content-Type': 'application/json',
},
},
);
return response.data.link; // Shortened URL from Bitly
} catch (error) {
console.error('Error shortening URL:', error.response?.data || error.message);
throw new HttpException(
'Failed to shorten URL',
error.response?.status || HttpStatus.INTERNAL_SERVER_ERROR,
);
}
}
}
```
### 5. Create a Controller to Handle Shortening Requests
Generate a controller to accept requests from clients.
```bash
nest generate controller shortener
```
Then update `shortener.controller.ts`:
```typescript
import { Controller, Post, Body } from '@nestjs/common';
import { ShortenerService } from './shortener.service';
@Controller('shortener')
export class ShortenerController {
constructor(private readonly shortenerService: ShortenerService) {}
@Post()
async shortenUrl(@Body('longUrl') longUrl: string) {
return {
shortUrl: await this.shortenerService.shortenUrl(longUrl),
};
}
}
```
### 6. Update `AppModule` to Register the Service and Controller
In `app.module.ts`, ensure `ShortenerService` and `ShortenerController` are added to the module.
```typescript
import { Module } from '@nestjs/common';
import { ShortenerService } from './shortener/shortener.service';
import { ShortenerController } from './shortener/shortener.controller';
@Module({
imports: [],
controllers: [ShortenerController],
providers: [ShortenerService],
})
export class AppModule {}
```
### 7. Test the Endpoint
Start your NestJS server:
```bash
npm run start
```
Then, you can test the endpoint by sending a `POST` request to `http://localhost:3000/shortener` with the following JSON body:
```json
{
"longUrl": "https://www.example.com/long-url"
}
```
The response will be:
```json
{
"shortUrl": "https://bit.ly/shortened-url"
}
```
### Summary
This setup will allow you to shorten URLs by making POST requests to your NestJS API, which, in turn, uses Bitly’s API to generate shortened links. You can replace Bitly with another service like Firebase Dynamic Links or TinyURL by adjusting the API URL and request format accordingly.
تعليقات
إرسال تعليق