nestjs-http-builder
v1.0.4
Published
A NestJS HTTP service with builder pattern
Readme
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-builderSetup
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: '[email protected]',
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 timessetRetryDelay(delay: number)
.setRetryDelay(2000) // Wait 2 seconds between retriessetFormData(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
