New Research: Supply Chain Attack on Axios Pulls Malicious Dependency from npm.Details
Socket
Book a DemoSign in
Socket

nestjs-http-builder

Package Overview
Dependencies
Maintainers
0
Versions
5
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

nestjs-http-builder

A NestJS HTTP service with builder pattern

latest
npmnpm
Version
1.0.4
Version published
Weekly downloads
1
Maintainers
0
Weekly downloads
 
Created
Source
A fluent builder pattern for making HTTP requests in NestJS

await this.apiService
      .createRequest()
      .setUrl("/users")
      .setMethod("POST")
      .setData(userData)
      .setRetryAttempts(3)
      .setValidationDto(UserDTO)
      .execute<UserDTO>();

Installation

npm install nestjs-http-builder

Setup

Import and configure the module in your app.module.ts:

import { Module } from "@nestjs/common";
import { ApiModule } from "nestjs-http-builder";

@Module({
  imports: [
    ApiModule.forRoot({
      // Optional axios config
      timeout: 5000,
      baseURL: "https://api.example.com",
    }),
  ],
})
export class AppModule {}

Usage Examples

Basic GET Request

@Injectable()
class UserService {
  constructor(private readonly apiService: ApiService) {}

  async getUsers() {
    return this.apiService
      .createRequest()
      .setUrl("/users")
      .setMethod("GET")
      .execute<User[]>();
  }
}

With Response Validation

class UserDTO {
  @IsString()
  name: string;

  @IsNumber()
  age: number;
}

@Injectable()
class UserService {
  async createUser(userData: any) {
    return this.apiService
      .createRequest()
      .setUrl("/users")
      .setMethod("POST")
      .setData(userData)
      .setValidationDto(UserDTO)
      .execute<UserDTO>();
  }
}

File Upload with Retry

@Injectable()
class UploadService {
  async uploadFile(file: Buffer) {
    return this.apiService
      .createRequest()
      .setUrl("/upload")
      .setMethod("POST")
      .setFormData({
        file: { file, fileName: "document.pdf" },
        description: "User document",
      })
      .setRetryAttempts(3)
      .execute();
  }
}

API Reference

RequestBuilder Methods

setUrl(url: string)

.setUrl('/api/users')

setMethod(method: HttpMethod)

.setMethod('GET')
// Supported: 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH'

setParams(params: Record<string, string | number | boolean>)

.setParams({
  page: 1,
  limit: 10,
  search: 'john',
  active: true
})

setHeaders(headers: Record<string, string>)

.setHeaders({
  'Authorization': 'Bearer your-token',
  'Custom-Header': 'value'
})

setData(data: any)

.setData({
  name: 'John Doe',
  email: 'john@example.com',
  age: 30
})

setValidationDto<T>(dto: new () => T)

class UserDTO {
  @IsString()
  name: string;

  @IsEmail()
  email: string;

  @IsNumber()
  age: number;
}

.setValidationDto(UserDTO)

setResponseType(type: 'json' | 'arraybuffer')

// For regular JSON responses
.setResponseType('json')

// For file downloads
.setResponseType('arraybuffer')

setRetryAttempts(attempts: number)

.setRetryAttempts(3) // Will retry failed requests 3 times

setRetryDelay(delay: number)

.setRetryDelay(2000) // Wait 2 seconds between retries

setFormData(formData: Record<string, { file: Buffer; fileName: string } | string>)

.setFormData({
  file: {
    file: fileBuffer,
    fileName: 'document.pdf'
  },
  description: 'User profile document',
  category: 'profile'
})

execute<T>()

// With type safety
interface UserResponse {
  id: number;
  name: string;
  email: string;
}

const user = await apiService
  .createRequest()
  .setUrl("/users/1")
  .execute<UserResponse>();

// For array responses
const users = await apiService
  .createRequest()
  .setUrl("/users")
  .execute<UserResponse[]>();


## Best Practices

1. Always specify response types with execute<T>()
2. Use DTOs for structured data validation
3. Set appropriate retry attempts for unreliable endpoints
4. Handle errors appropriately in your application code
5. Use type-safe response handling

## License

MIT

FAQs

Package last updated on 08 Feb 2025

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts