Research
Security News
Malicious npm Packages Inject SSH Backdoors via Typosquatted Libraries
Socket’s threat research team has detected six malicious npm packages typosquatting popular libraries to insert SSH backdoors.
nestjs-form-data
Advanced tools
NestJS middleware for handling multipart/form-data, which is primarily used for uploading files
nestjs-form-data is a NestJS middleware for handling multipart/form-data, which is primarily used for uploading files.
nestjs-form-data serializes the form-data request into an object and places it in the body of the request.
The files in the request are transformed into objects.
Standard file storage types:
$ npm install nestjs-form-data
Add the module to your application
@Module({
imports: [
NestjsFormDataModule,
],
})
export class AppModule {
}
Apply @FormDataRequest()
decorator to your controller method
@Controller()
export class NestjsFormDataController {
@Post('load')
@FormDataRequest()
getHello(@Body() testDto: FormDataTestDto): void {
console.log(testDto);
}
}
If you are using class-validator describe dto and specify validation rules
export class FormDataTestDto {
@IsFile()
@MaxFileSize(1e6)
@HasMimeType(['image/jpeg', 'image/png'])
avatar: MemoryStoredFile;
}
You can set the global configuration when connecting the module using the NestjsFormDataModule.config
method:
@Module({
imports: [
NestjsFormDataModule.config({ storage: MemoryStoredFile }),
],
controllers: [],
providers: [],
})
export class AppModule {
}
Quite often you might want to asynchronously pass your module options instead of passing them beforehand.
In such case, use configAsync()
method, that provides a couple of various ways to deal with async data.
NestjsFormDataModule.configAsync({
useFactory: () => ({
storage: MemoryStoredFile
})
});
Our factory behaves like every other one (might be async and is able to inject dependencies through inject).
NestjsFormDataModule.configAsync({
imports: [ConfigModule],
useFactory: async (configService: ConfigService) => ({
storage: MemoryStoredFile,
limits: {
files: configService.get<number>('files'),
}
}),
inject: [ConfigService],
});
NestjsFormDataModule.configAsync({
useClass: MyNestJsFormDataConfigService
});
Above construction will instantiate MyNestJsFormDataConfigService
inside NestjsFormDataModule
and will leverage it
to create options object.
export class MyNestJsFormDataConfigService implements NestjsFormDataConfigFactory {
configAsync(): Promise<FormDataInterceptorConfig> | FormDataInterceptorConfig {
return {
storage: FileSystemStoredFile,
fileSystemStoragePath: '/tmp/nestjs-fd',
};
}
}
NestjsFormDataModule.configAsync({
imports: [MyNestJsFormDataConfigModule],
useExisting: MyNestJsFormDataConfigService
});
It works the same as useClass with one critical difference - NestjsFormDataModule
will lookup imported modules to
reuse already created MyNestJsFormDataConfigService
, instead of instantiating it on its own.
Or pass the config object while using the decorator on the method
@Controller()
export class NestjsFormDataController {
@Post('load')
@FormDataRequest({storage: MemoryStoredFile})
getHello(@Body() testDto: FormDataTestDto): void {
console.log(testDto);
}
}
storage
- The type of storage logic for the uploaded file (Default MemoryStoredFile)fileSystemStoragePath
- The path to the directory for storing temporary files, used only for storage: FileSystemStoredFile
(Default: /tmp/nestjs-tmp-storage)autoDeleteFile
- Automatically delete files after the request ends (Default true)limits
- busboy limits configuration. Constraints in this declaration are handled at the serialization stage, so using these parameters is preferable for performance.MemoryStoredFile
The file is loaded into RAM, files with this storage type are very fast but not suitable for processing large files.
FileSystemStoredFile
The file is loaded into a temporary directory (see configuration) and is available during the processing of the request. The file is automatically deleted after the request finishes
You can define a custom type of file storage, for this, inherit your class from StoredFile
, see examples in the storage directory
By default, several validators are available with which you can check the file
Note: If you need to validate an array of files for size or otherwise, use each: true
property from ValidationOptions
Checks if the value is an uploaded file
@IsFile(validationOptions?: ValidationOptions)
Checks an array of files, the same as @IsFile({ each: true })
For convenience
@IsFiles(validationOptions?: ValidationOptions)
Maximum allowed file size
@MaxFileSize(maxSizeBytes: number, validationOptions?: ValidationOptions)
Minimum allowed file size
@MinFileSize(minSizeBytes: number, validationOptions?: ValidationOptions)
Check the mime type of the file
The library uses two sources to get the mime type for the file:
Priority of receiving mime-type corresponds to the list
The default is simple mode, which does not check the data source, but you can pass a second argument to strictly check the mime-type and data source.
You can also get the mime type and data source via the get mimeTypeWithSource():MetaFieldSource
getter on the StoredFile
@HasMimeType(allowedMimeTypes: string[] | string, strictSource?: MetaSource | ValidationOptions, validationOptions?: ValidationOptions)
Check the extension type of the file The library uses two sources to get the extension for the file:
Priority of receiving extension corresponds to the list
The default is simple mode, which does not check the data source, but you can pass a second argument to strictly check the extension and data source.
You can also get the extension and data source via the get extensionWithSource():MetaFieldSource
getter on the StoredFile
@HasExtension(allowedMimeTypes: string[] | string, strictSource?: MetaSource | ValidationOptions, validationOptions?: ValidationOptions)
Controller
import { FileSystemStoredFile, FormDataRequest } from 'nestjs-form-data';
@Controller()
export class NestjsFormDataController {
@Post('load')
@FormDataRequest({storage: FileSystemStoredFile})
getHello(@Body() testDto: FormDataTestDto): void {
console.log(testDto);
}
}
DTO
import { FileSystemStoredFile, HasMimeType, IsFile, MaxFileSize } from 'nestjs-form-data';
export class FormDataTestDto {
@IsFile()
@MaxFileSize(1e6)
@HasMimeType(['image/jpeg', 'image/png'])
avatar: FileSystemStoredFile;
}
Send request (via Insomnia)
DTO
import { FileSystemStoredFile, HasMimeType, IsFiles, MaxFileSize } from 'nestjs-form-data';
export class FormDataTestDto {
@IsFiles()
@MaxFileSize(1e6, { each: true })
@HasMimeType(['image/jpeg', 'image/png'], { each: true })
avatars: FileSystemStoredFile[];
}
Send request (via Insomnia)
v1.8.0
StoredFile.create()
Your custom classes for saving files will be broken, they will need to be fixed, example
in src/classes/storage/MemoryStoredFile.ts
HasMimeType
validator, added second argument to strictly check mime-type sourceHasExtension
validator, to check file extension, uses file-typeFAQs
NestJS middleware for handling multipart/form-data, which is primarily used for uploading files
The npm package nestjs-form-data receives a total of 25,993 weekly downloads. As such, nestjs-form-data popularity was classified as popular.
We found that nestjs-form-data demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 0 open source maintainers collaborating on the project.
Did you know?
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.
Research
Security News
Socket’s threat research team has detected six malicious npm packages typosquatting popular libraries to insert SSH backdoors.
Security News
MITRE's 2024 CWE Top 25 highlights critical software vulnerabilities like XSS, SQL Injection, and CSRF, reflecting shifts due to a refined ranking methodology.
Security News
In this segment of the Risky Business podcast, Feross Aboukhadijeh and Patrick Gray discuss the challenges of tracking malware discovered in open source softare.